App.Dashboard = function Dashboard({ user }) {
    const [data, setData] = React.useState(null);
    const [loading, setLoading] = React.useState(true);
    const [quote, setQuote] = React.useState(null);
    const quotesRef = React.useRef([]);

    React.useEffect(() => {
        App.API.get('dashboard?fingerprint=' + App.fingerprint)
            .then(d => {
                setData(d);
                setLoading(false);
            })
            .catch(() => setLoading(false));

        fetch('data/quotes.json')
            .then(r => r.json())
            .then(quotes => {
                quotesRef.current = quotes;
                if (quotes.length > 0) {
                    setQuote(quotes[Math.floor(Math.random() * quotes.length)]);
                }
            })
            .catch(() => {});
    }, []);

    function newQuote() {
        const quotes = quotesRef.current;
        if (quotes.length <= 1) return;
        let next;
        do {
            next = quotes[Math.floor(Math.random() * quotes.length)];
        } while (next === quote);
        setQuote(next);
    }

    if (loading) return <App.Loading />;
    if (!data) return <div className="page"><p>Failed to load dashboard.</p></div>;

    const greeting = user && user.nickname
        ? 'Welcome back, ' + user.nickname + '!'
        : 'Welcome to I Race Builder!';

    return (
        <div className="page">
            <h1>{greeting}</h1>
            {quote ? (
                <div className="quote-block">
                    <p className="page-subtitle page-quote">
                        "{quote.text}" <span className="quote-author">— {quote.author}</span>
                    </p>
                    <button className="btn btn-sm stfu-btn" onClick={newQuote}>STFU</button>
                </div>
            ) : (
                <p className="page-subtitle">Your racing command center</p>
            )}

            {/* Quick Actions */}
            <section className="dash-section">
                <h2 className="dash-section-title">Quick Actions</h2>
                <div className="dash-actions">
                    <a href="#/create-combo" className="btn btn-primary">Create Race Combo</a>
                    <a href="#/create-poll" className="btn btn-primary">Create Poll</a>
                </div>
            </section>

            {/* Polls Needing Your Vote */}
            <section className="dash-section">
                <h2 className="dash-section-title">Polls Needing Your Vote</h2>
                {data.pollsToVote.length === 0 ? (
                    <p className="dash-empty">You're all caught up!</p>
                ) : (
                    <div className="dash-poll-grid">
                        {data.pollsToVote.map(poll => (
                            <div key={poll.id} className="dash-poll-card">
                                <h3>{poll.title}</h3>
                                <div className="dash-poll-meta">
                                    <span>{poll.comboCount} combo{poll.comboCount !== 1 ? 's' : ''}</span>
                                    <span>{poll.votesRemaining} vote{poll.votesRemaining !== 1 ? 's' : ''} remaining</span>
                                </div>
                                {poll.combos && poll.combos.length > 0 && (
                                    <div className="poll-combo-list">
                                        {poll.combos.map((combo, i) => (
                                            <div key={i} className="poll-combo-row">
                                                <div className="poll-combo-track">{combo.track_name}</div>
                                                {combo.car_names.map((car, ci) => (
                                                    <div key={ci} className="poll-combo-car">{car}</div>
                                                ))}
                                            </div>
                                        ))}
                                    </div>
                                )}
                                <a href={'#/poll/' + poll.shareCode} className="btn btn-primary btn-sm">Vote Now</a>
                            </div>
                        ))}
                    </div>
                )}
            </section>

            {/* Recent Results */}
            <section className="dash-section">
                <h2 className="dash-section-title">Recent Results</h2>
                {data.recentResults.length === 0 ? (
                    <p className="dash-empty">No poll results yet.</p>
                ) : (
                    <div className="dash-results-list">
                        {data.recentResults.map(poll => (
                            <div key={poll.id} className="dash-result-card">
                                <div className="dash-result-body">
                                    <h3>{poll.title}</h3>
                                    {poll.allResults && poll.allResults.length > 0 ? (
                                        poll.allResults.map((combo, i) => (
                                            <p key={i} className="dash-result-top">
                                                #{combo.rank}: {combo.name} at {combo.trackName}
                                                {combo.voteCount > 0 && (
                                                    <span className="dash-result-rating"> ({combo.avgRating.toFixed(1)} avg)</span>
                                                )}
                                            </p>
                                        ))
                                    ) : (
                                        <p className="dash-result-top">No votes yet</p>
                                    )}
                                </div>
                                <a href={'#/results/' + poll.shareCode} className="btn btn-sm">View Results</a>
                            </div>
                        ))}
                    </div>
                )}
            </section>

            {/* Your Combos */}
            <section className="dash-section">
                <h2 className="dash-section-title">Your Combos</h2>
                {data.yourCombos.length === 0 ? (
                    <p className="dash-empty">You haven't created any combos yet.</p>
                ) : (
                    <>
                        <div className="card-grid">
                            {data.yourCombos.map(combo => (
                                <App.ComboCard
                                    key={combo.id}
                                    combo={combo}
                                    showDelete={false}
                                />
                            ))}
                        </div>
                        <a href="#/combos" className="btn btn-sm" style={{ marginTop: '0.75rem' }}>View All Combos</a>
                    </>
                )}
            </section>
        </div>
    );
};
