// ============================================
// LOGIN / REGISTER SCREEN
// ============================================

function LoginScreen({ navigate }) {
    const [mode, setMode]        = React.useState('login');     // 'login' | 'register'
    const [email, setEmail]      = React.useState('');
    const [password, setPass]    = React.useState('');
    const [nick, setNick]        = React.useState('');
    const [country, setCountry]  = React.useState('BR');
    const [showPwd, setShowPwd]  = React.useState(false);
    const [error, setError]      = React.useState(null);
    const [loading, setLoading]  = React.useState(false);

    React.useEffect(() => { setError(null); }, [mode]);

    const submit = async (e) => {
        e.preventDefault();
        setError(null);
        setLoading(true);
        try {
            if (mode === 'login') {
                await window.MastershotAuth.login(email.trim(), password);
            } else {
                await window.MastershotAuth.register({
                    nick: nick.trim(), email: email.trim(), password, country,
                });
            }
            navigate('menu');
        } catch (err) {
            setError(prettyError(err));
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="screen active" style={{ opacity: 1 }}>
            <AmbientBackdrop/>
            <Particles count={16}/>

            <div style={{
                position: 'relative', zIndex: 5,
                width: '100%', height: '100%',
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center',
                padding: 24,
            }}>
                <div style={{ marginBottom: 28 }}>
                    <MastershotLogo size={120}/>
                </div>

                <div style={{
                    width: 420, maxWidth: '90vw',
                    background: 'linear-gradient(180deg, var(--ink-800) 0%, var(--ink-900) 100%)',
                    border: '1px solid var(--gold-800)',
                    borderRadius: 'var(--r-lg)',
                    padding: '32px 32px 24px',
                    boxShadow: 'var(--sh-xl)',
                    animation: 'card-in 0.5s var(--ease-out)',
                }}>
                    <div style={{ textAlign: 'center', marginBottom: 24 }}>
                        <div style={{
                            fontFamily: 'var(--font-display)', fontSize: 24,
                            color: 'var(--gold-300)', letterSpacing: '0.06em',
                            fontWeight: 600,
                        }}>{mode === 'login' ? 'Entrar' : 'Criar Conta'}</div>
                        <div style={{
                            fontSize: 12, color: 'var(--ink-300)',
                            letterSpacing: '0.16em', textTransform: 'uppercase',
                            marginTop: 6,
                        }}>{mode === 'login' ? 'Acesse sua conta' : 'Junte-se ao salão'}</div>
                    </div>

                    <form onSubmit={submit} style={{ display: 'grid', gap: 14 }}>
                        {mode === 'register' && (
                            <Field label="Nick" hint="3-24 caracteres, letras/números/_/-">
                                <input className="input" type="text"
                                    value={nick} onChange={e => setNick(e.target.value)}
                                    autoComplete="username" required minLength={3} maxLength={24}
                                    pattern="[A-Za-z0-9_-]+" disabled={loading}/>
                            </Field>
                        )}
                        <Field label="E-mail">
                            <input className="input" type="email"
                                value={email} onChange={e => setEmail(e.target.value)}
                                autoComplete={mode === 'login' ? 'email' : 'email'}
                                required disabled={loading}/>
                        </Field>
                        <Field label="Senha" hint={mode === 'register' ? 'Mín. 8 chars com maiúscula, minúscula e dígito' : null}>
                            <div style={{ position: 'relative' }}>
                                <input className="input" type={showPwd ? 'text' : 'password'}
                                    value={password} onChange={e => setPass(e.target.value)}
                                    autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
                                    required minLength={mode === 'register' ? 8 : 1} maxLength={128}
                                    disabled={loading} style={{ width: '100%', paddingRight: 64 }}/>
                                <button type="button" onClick={() => setShowPwd(s => !s)}
                                    style={{
                                        position: 'absolute', right: 8, top: '50%',
                                        transform: 'translateY(-50%)',
                                        background: 'none', border: 'none',
                                        color: 'var(--ink-300)', fontSize: 11, fontWeight: 600,
                                        letterSpacing: '0.1em', textTransform: 'uppercase',
                                        cursor: 'pointer', padding: '4px 8px',
                                    }}>{showPwd ? 'ocultar' : 'mostrar'}</button>
                            </div>
                        </Field>

                        {error && (
                            <div style={{
                                padding: '10px 12px',
                                background: 'rgba(255, 82, 82, 0.10)',
                                border: '1px solid rgba(255, 82, 82, 0.4)',
                                borderRadius: 'var(--r-sm)',
                                color: '#ff8d8d', fontSize: 13,
                            }}>{error}</div>
                        )}

                        <button type="submit" className="btn-cta" disabled={loading}
                            style={{ marginTop: 8 }}>
                            {loading ? '…' : (mode === 'login' ? 'Entrar' : 'Criar conta')}
                        </button>
                    </form>

                    <div style={{
                        marginTop: 20, paddingTop: 16,
                        borderTop: '1px solid var(--ink-700)',
                        textAlign: 'center', fontSize: 12,
                        color: 'var(--ink-300)',
                    }}>
                        {mode === 'login' ? 'Ainda não tem conta?' : 'Já tem uma conta?'}
                        {' '}
                        <button onClick={() => setMode(mode === 'login' ? 'register' : 'login')}
                            style={{
                                background: 'none', border: 'none',
                                color: 'var(--gold-400)', cursor: 'pointer',
                                fontWeight: 600, padding: 0,
                            }}>
                            {mode === 'login' ? 'Criar agora' : 'Entrar'}
                        </button>
                    </div>
                </div>

                <div style={{
                    position: 'absolute', bottom: 28, left: 0, right: 0,
                    textAlign: 'center', fontSize: 10,
                    color: 'var(--ink-400)', letterSpacing: '0.18em',
                    textTransform: 'uppercase',
                }}>v1.0.4 · © Mastershot Studios</div>
            </div>
        </div>
    );
}

function Field({ label, hint, children }) {
    return (
        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{
                fontSize: 11, color: 'var(--gold-500)',
                letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 600,
            }}>{label}</span>
            {children}
            {hint && (
                <span style={{ fontSize: 11, color: 'var(--ink-400)', marginTop: 2 }}>{hint}</span>
            )}
        </label>
    );
}

function prettyError(err) {
    if (!err) return 'erro desconhecido';
    if (err.code === 'invalid_credentials') return 'E-mail ou senha incorretos.';
    if (err.code === 'email_taken')         return 'Este e-mail já está em uso.';
    if (err.code === 'nick_taken')          return 'Este nick já está em uso.';
    if (err.code === 'account_inactive')    return 'Conta inativa ou bloqueada. Contate o suporte.';
    if (err.code === 'too_many_requests')   return 'Muitas tentativas. Aguarde alguns minutos.';
    if (err.code === 'invalid_input' && Array.isArray(err.issues)) {
        return err.issues.map(i => `${(i.path || []).join('.')}: ${i.message}`).join(' · ');
    }
    return err.message || 'erro ao processar';
}

window.LoginScreen = LoginScreen;
