App.CreatePoll = function CreatePoll() {
    const [title, setTitle] = React.useState('');
    const [combos, setCombos] = React.useState([]);
    const [selectedIds, setSelectedIds] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [saving, setSaving] = React.useState(false);
    const [error, setError] = React.useState('');
    const [shareCode, setShareCode] = React.useState(null);
    const [generating, setGenerating] = React.useState(false);
    const [showNamePrompt, setShowNamePrompt] = React.useState(false);
    const titleInputRef = React.useRef(null);

    React.useEffect(() => {
        App.API.get('combos?limit=50').then(data => {
            setCombos(data.combos);
            setLoading(false);
        });
    }, []);

    const toggleCombo = (id) => {
        setSelectedIds(prev =>
            prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
        );
    };

    const generateName = () => {
        setGenerating(true);
        App.API.get('name-generator?type=poll&count=1').then(data => {
            if (data.names && data.names.length > 0) {
                setTitle(data.names[0]);
            }
            setGenerating(false);
        }).catch(() => {
            setGenerating(false);
        });
    };

    const handleSubmit = () => {
        setError('');
        if (!title.trim()) {
            setShowNamePrompt(true);
            return;
        }
        if (selectedIds.length === 0) { setError('Please select at least one combo'); return; }

        setSaving(true);
        App.API.post('polls', {
            title: title.trim(),
            comboIds: selectedIds,
            fingerprint: App.fingerprint,
        }).then(data => {
            setShareCode(data.shareCode);
            setSaving(false);
        }).catch(err => {
            setError(err.message);
            setSaving(false);
        });
    };

    const handleNamePromptEnter = () => {
        setShowNamePrompt(false);
        if (titleInputRef.current) titleInputRef.current.focus();
    };

    const handleNamePromptGenerate = () => {
        setShowNamePrompt(false);
        generateName();
    };

    const copyLink = () => {
        const url = window.location.origin + '/poll/' + shareCode;
        navigator.clipboard.writeText(url).then(() => {
            alert('Link copied to clipboard!');
        });
    };

    if (shareCode) {
        const pollUrl = window.location.origin + '/poll/' + shareCode;
        return (
            <div className="page">
                <div className="success-card">
                    <h1>Poll Created!</h1>
                    <p>Share this link with your friends:</p>
                    <div className="share-link-box">
                        <input type="text" readOnly value={pollUrl} className="form-input" />
                        <button className="btn btn-primary" onClick={copyLink}>Copy</button>
                    </div>
                    <div className="success-actions">
                        <a href={'#/poll/' + shareCode} className="btn btn-primary">Vote Now</a>
                        <a href={'#/results/' + shareCode} className="btn">View Results</a>
                    </div>
                </div>
            </div>
        );
    }

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

    return (
        <div className="page">
            <h1>Create Poll</h1>
            <p className="page-subtitle">Select combos to include in your poll, then share the link</p>

            {error && <div className="alert alert-error">{error}</div>}

            <div className="form-name-row">
                <input
                    ref={titleInputRef}
                    type="text"
                    className="form-input"
                    placeholder="e.g., What should we race this weekend?"
                    value={title}
                    onChange={e => setTitle(e.target.value)}
                    maxLength={200}
                />
                <button
                    className="btn btn-primary"
                    onClick={handleSubmit}
                    disabled={saving}
                >
                    {saving ? 'Creating...' : 'Create Poll'}
                </button>
            </div>
            <div className="form-generate-row">
                <button className="btn btn-sm" onClick={generateName} disabled={generating}>
                    {generating ? 'Generating...' : '\uD83C\uDFB2 Generate Name'}
                </button>
            </div>

            <h3>Select Combos ({selectedIds.length} selected)</h3>
            {combos.length === 0 ? (
                <div className="empty-state">
                    <p>No combos available. Create some combos first!</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}
                            selectable={true}
                            selected={selectedIds.includes(combo.id)}
                            onToggle={toggleCombo}
                        />
                    ))}
                </div>
            )}

            {showNamePrompt && (
                <App.NamePromptModal
                    type="poll"
                    onEnterName={handleNamePromptEnter}
                    onGenerate={handleNamePromptGenerate}
                    onClose={() => setShowNamePrompt(false)}
                />
            )}
        </div>
    );
};
