App.WelcomeModal = function WelcomeModal({ userId, onSave, onSkip }) {
    const [nickname, setNickname] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const [error, setError] = React.useState('');

    const handleSave = () => {
        const trimmed = nickname.trim();
        if (!trimmed) { setError('Please enter a nickname'); return; }
        if (trimmed.length > 50) { setError('Max 50 characters'); return; }
        setSaving(true);
        setError('');
        App.API.post('user', {
            fingerprint: App.fingerprint,
            nickname: trimmed,
        }).then(data => {
            onSave(data);
        }).catch(err => {
            setError(err.message);
            setSaving(false);
        });
    };

    const handleKeyDown = (e) => {
        if (e.key === 'Enter') handleSave();
    };

    return (
        <div className="modal-overlay">
            <div className="modal-dialog">
                <h2>Welcome to Race Builder!</h2>
                <p className="modal-subtitle">Your ID is <strong>{userId}</strong>. Set a nickname?</p>
                {error && <div className="alert alert-error">{error}</div>}
                <input
                    type="text"
                    className="form-input"
                    placeholder="Enter a nickname..."
                    value={nickname}
                    onChange={e => setNickname(e.target.value)}
                    onKeyDown={handleKeyDown}
                    maxLength={50}
                    autoFocus
                />
                <div className="modal-actions">
                    <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
                        {saving ? 'Saving...' : 'Save'}
                    </button>
                    <button className="btn" onClick={onSkip}>Skip</button>
                </div>
            </div>
        </div>
    );
};
