App.PollResults = function PollResults({ code }) {
    const [poll, setPoll] = React.useState(null);
    const [results, setResults] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [error, setError] = React.useState('');

    const loadResults = () => {
        App.API.get('results/' + code)
            .then(data => {
                setPoll(data.poll);
                setResults(data.results);
                setLoading(false);
            })
            .catch(err => {
                setError(err.message);
                setLoading(false);
            });
    };

    React.useEffect(() => { loadResults(); }, [code]);

    if (loading) return <App.Loading />;
    if (error) return <div className="page"><div className="alert alert-error">{error}</div></div>;

    const renderCarList = (result) => {
        const cars = result.cars || [];
        const catBadges = (result.categories || []).map((cat, i) => (
            <span key={'cat-' + i} className="combo-cat-badge">All {cat.category_name}</span>
        ));
        return (
            <div className="result-car-list">
                {cars.map((car, i) => (
                    <div key={'car-' + i} className="result-car-item">
                        <img
                            src={'images/cars/' + car.image_filename}
                            alt={car.name}
                            className="combo-car-thumb"
                            loading="lazy"
                        />
                        <span className="result-car-name">{car.name}</span>
                    </div>
                ))}
                {catBadges}
            </div>
        );
    };

    const renderVoterList = (result) => {
        if (!result.votes || result.votes.length === 0) return null;
        return (
            <div className="voter-list">
                <div className="voter-list-title">Individual Votes</div>
                {result.votes.map((vote, i) => {
                    const voterName = vote.voter_nickname
                        ? vote.voter_nickname
                        : vote.voter_id
                            ? 'User #' + vote.voter_id
                            : 'Anonymous';
                    return (
                        <div key={i} className="voter-row">
                            <span className="voter-name">{voterName}</span>
                            <App.StarRating rating={vote.rating} readonly />
                        </div>
                    );
                })}
            </div>
        );
    };

    return (
        <div className="page">
            <div className="page-header">
                <h1>Results: {poll.title}</h1>
                <div className="page-header-actions">
                    <button className="btn" onClick={() => App.sharePoll(code)}>Share</button>
                    <a href={'#/poll/' + code} className="btn btn-primary">Back to Voting</a>
                </div>
            </div>
            <button className="btn btn-sm" onClick={loadResults}>Refresh Results</button>

            <div className="results-list">
                {results.map((result, index) => (
                    <div key={result.poll_combo_id} className={'result-card' + (index === 0 ? ' winner' : '')}>
                        <div className="result-rank">#{index + 1}</div>
                        <div className="result-img">
                            <img
                                src={'images/tracks/' + result.track_image}
                                alt={result.track_name}
                                loading="lazy"
                            />
                        </div>
                        <div className="result-body">
                            <h3>{result.combo_name}</h3>
                            <div className="combo-details">
                                <div><strong>Track:</strong> {result.track_name}</div>
                                {renderCarList(result)}
                            </div>
                            <div className="result-distribution-row">
                                <div className="result-rating-section">
                                    <div className="result-stats">
                                        <div className="avg-rating">
                                            <App.StarRating rating={Math.round(result.avg_rating)} readonly />
                                            <span className="rating-number">{result.avg_rating.toFixed(1)}</span>
                                        </div>
                                        <div className="vote-count">{result.vote_count} vote{result.vote_count !== 1 ? 's' : ''}</div>
                                    </div>
                                    <div className="rating-distribution">
                                        {[5, 4, 3, 2, 1].map(star => {
                                            const count = result.distribution[star] || 0;
                                            const pct = result.vote_count > 0 ? (count / result.vote_count * 100) : 0;
                                            return (
                                                <div key={star} className="dist-row">
                                                    <span className="dist-label">{star}&#9733;</span>
                                                    <div className="dist-bar-track">
                                                        <div className="dist-bar-fill" style={{ width: pct + '%' }}></div>
                                                    </div>
                                                    <span className="dist-count">{count}</span>
                                                </div>
                                            );
                                        })}
                                    </div>
                                </div>
                                {renderVoterList(result)}
                            </div>
                        </div>
                    </div>
                ))}
                {results.length === 0 && (
                    <div className="empty-state">
                        <p>No votes yet. Share the poll link to get started!</p>
                    </div>
                )}
            </div>
        </div>
    );
};
