App.VotePoll = function VotePoll({ code }) {
    const [poll, setPoll] = React.useState(null);
    const [combos, setCombos] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [error, setError] = React.useState('');
    const [voting, setVoting] = React.useState({});
    const [removing, setRemoving] = React.useState(null);
    const [showAddCombo, setShowAddCombo] = React.useState(false);

    const loadPoll = () => {
        App.API.get('polls/' + code + '?fingerprint=' + App.fingerprint)
            .then(data => {
                setPoll(data.poll);
                setCombos(data.combos);
                setLoading(false);
            })
            .catch(err => {
                setError(err.message);
                setLoading(false);
            });
    };

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

    const handleRate = (pollComboId, rating) => {
        setVoting(prev => ({ ...prev, [pollComboId]: true }));
        App.API.post('votes', {
            pollComboId: pollComboId,
            rating: rating,
            fingerprint: App.fingerprint,
        }).then(() => {
            setCombos(prev => prev.map(c =>
                c.poll_combo_id === pollComboId ? { ...c, userRating: rating } : c
            ));
            setVoting(prev => ({ ...prev, [pollComboId]: false }));
        }).catch(err => {
            alert(err.message);
            setVoting(prev => ({ ...prev, [pollComboId]: false }));
        });
    };

    const handleRemoveCombo = (pollComboId, comboName) => {
        if (!confirm('Remove "' + comboName + '" from this poll? All votes for it will be deleted.')) return;
        setRemoving(pollComboId);
        App.API.post('polls/' + code, {
            _action: 'remove-combo',
            pollComboId: pollComboId,
            fingerprint: App.fingerprint,
        }).then(() => {
            setRemoving(null);
            loadPoll();
        }).catch(err => {
            alert(err.message);
            setRemoving(null);
        });
    };

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

    if (showAddCombo) {
        return (
            <App.AddComboModal
                shareCode={code}
                onComboAdded={() => { setShowAddCombo(false); loadPoll(); }}
                onClose={() => setShowAddCombo(false)}
            />
        );
    }

    const renderCarList = (combo) => {
        const cars = combo.cars || [];
        const catBadges = (combo.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>
        );
    };

    return (
        <div className="page">
            <div className="page-header">
                <h1>{poll.title}</h1>
                <div className="page-header-actions">
                    <button className="btn" onClick={() => setShowAddCombo(true)}>+ Add Combo</button>
                    <button className="btn" onClick={() => App.sharePoll(code)}>Share</button>
                    <a href={'#/results/' + code} className="btn btn-primary">View Results</a>
                </div>
            </div>
            <p className="page-subtitle">Rate each combo from 1 to 5 stars</p>

            <div className="vote-list">
                {combos.map(combo => (
                    <div key={combo.poll_combo_id} className="vote-card">
                        <div className="vote-card-img">
                            <img
                                src={'images/tracks/' + combo.track_image}
                                alt={combo.track_name}
                                loading="lazy"
                            />
                        </div>
                        <div className="vote-card-body">
                            <div className="vote-card-header">
                                <h3>{combo.combo_name}</h3>
                                {(poll.isPollOwner || combo.is_mine) && (
                                    <button
                                        className="btn btn-danger btn-sm"
                                        disabled={removing === combo.poll_combo_id}
                                        onClick={() => handleRemoveCombo(combo.poll_combo_id, combo.combo_name)}
                                    >
                                        {removing === combo.poll_combo_id ? 'Removing...' : 'Remove'}
                                    </button>
                                )}
                            </div>
                            <div className="combo-details">
                                <div><strong>Track:</strong> {combo.track_name}</div>
                                {renderCarList(combo)}
                            </div>
                            <div className="vote-rating">
                                <App.StarRating
                                    rating={combo.userRating || 0}
                                    onRate={(r) => handleRate(combo.poll_combo_id, r)}
                                />
                                {combo.userRating && (
                                    <span className="vote-status">Your vote: {combo.userRating}/5</span>
                                )}
                            </div>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};
