App.ComboLibrary = function ComboLibrary() {
    const [combos, setCombos] = React.useState([]);
    const [myCombos, setMyCombos] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [page, setPage] = React.useState(1);
    const [totalPages, setTotalPages] = React.useState(1);
    const [deleteModal, setDeleteModal] = React.useState(null); // { comboId, comboName, step: 'confirm' | 'in_use', polls: [] }

    const loadCombos = (p) => {
        setLoading(true);
        App.API.get('combos?page=' + p + '&limit=20&fingerprint=' + App.fingerprint).then(data => {
            setCombos(data.combos);
            setMyCombos(data.myCombos || []);
            setTotalPages(data.pages || 1);
            setLoading(false);
        });
    };

    React.useEffect(() => { loadCombos(page); }, [page]);

    const handleDeleteRequest = (comboId, comboName) => {
        setDeleteModal({ comboId: comboId, comboName: comboName, step: 'confirm', polls: [] });
    };

    const handleDeleteConfirm = () => {
        if (!deleteModal) return;
        App.API.post('combos/' + deleteModal.comboId, {
            _action: 'delete',
            fingerprint: App.fingerprint,
        })
            .then((data) => {
                if (data.error === 'in_use') {
                    setDeleteModal(prev => ({ ...prev, step: 'in_use', polls: data.polls || [] }));
                } else {
                    setDeleteModal(null);
                    loadCombos(page);
                }
            })
            .catch(err => {
                setDeleteModal(null);
                alert(err.message);
            });
    };

    if (loading) return <App.Loading />;

    return (
        <div className="page">
            <div className="page-header">
                <h1>Race Combos</h1>
                <a href="#/create-combo" className="btn btn-primary">Create Race Combo</a>
            </div>
            <p className="page-subtitle">Browse and manage race combinations</p>

            {myCombos.length > 0 && (
                <section className="dash-section">
                    <h2 className="dash-section-title">My Combos</h2>
                    <div className="card-grid">
                        {myCombos.map(combo => (
                            <App.ComboCard
                                key={combo.id}
                                combo={combo}
                                showDelete={true}
                                onDelete={handleDeleteRequest}
                            />
                        ))}
                    </div>
                </section>
            )}

            <section className="dash-section">
                <h2 className="dash-section-title">Community Combos</h2>
                {combos.length === 0 ? (
                    <div className="empty-state">
                        <p>No community combos yet. Be the first to create one!</p>
                        <a href="#/create-combo" className="btn btn-primary">Create Race Combo</a>
                    </div>
                ) : (
                    <>
                        <div className="card-grid">
                            {combos.map(combo => (
                                <App.ComboCard
                                    key={combo.id}
                                    combo={combo}
                                    showDelete={combo.creator_fingerprint === App.fingerprint}
                                    onDelete={handleDeleteRequest}
                                />
                            ))}
                        </div>
                        {totalPages > 1 && (
                            <div className="pagination">
                                <button
                                    className="btn"
                                    disabled={page <= 1}
                                    onClick={() => setPage(p => p - 1)}
                                >
                                    Previous
                                </button>
                                <span className="page-info">Page {page} of {totalPages}</span>
                                <button
                                    className="btn"
                                    disabled={page >= totalPages}
                                    onClick={() => setPage(p => p + 1)}
                                >
                                    Next
                                </button>
                            </div>
                        )}
                    </>
                )}
            </section>

            {deleteModal && (
                <div className="modal-overlay" onClick={() => setDeleteModal(null)}>
                    <div className="modal-dialog" onClick={e => e.stopPropagation()}>
                        {deleteModal.step === 'confirm' ? (
                            <>
                                <h2>Delete Combo</h2>
                                <p className="modal-subtitle">
                                    Are you sure you want to delete "{deleteModal.comboName}"?
                                </p>
                                <div className="modal-actions">
                                    <button className="btn" onClick={() => setDeleteModal(null)}>Cancel</button>
                                    <button className="btn btn-danger" onClick={handleDeleteConfirm}>Delete</button>
                                </div>
                            </>
                        ) : (
                            <>
                                <h2>Cannot Delete</h2>
                                <p className="modal-subtitle">
                                    "{deleteModal.comboName}" is used in the following polls. Remove it from these polls first:
                                </p>
                                <ul className="poll-link-list">
                                    {deleteModal.polls.map(poll => (
                                        <li key={poll.share_code}>
                                            <a href={'#/poll/' + poll.share_code}>{poll.title}</a>
                                        </li>
                                    ))}
                                </ul>
                                <div className="modal-actions">
                                    <button className="btn" onClick={() => setDeleteModal(null)}>Close</button>
                                </div>
                            </>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
};
