/* Pagina /login — email + senha (e turnstile depois). */

const { useState } = React;


function LoginPage() {
    const [email, setEmail]       = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading]   = useState(false);
    const [error, setError]       = useState(null);
    const [tsToken, setTsToken]   = useState(null);
    const [tsReset, setTsReset]   = useState(0);

    const on_submit = async (e) => {
        e.preventDefault();
        setError(null);
        setLoading(true);
        try {
            const data = await window.C7_API.login(email, password, tsToken);
            if (data.requires_2fa) {
                window.sessionStorage.setItem('c7_twofa_token', data.twofa_token);
                window.C7_ROUTER.navigate('/login/2fa');
                return;
            }
            // Sem 2FA — direto pro dashboard. Hidrata user.
            await hydrate_user_then_go();
        } catch (err) {
            if (err.status === 401)      setError('Email ou senha inválidos.');
            else if (err.status === 403) setError('Conta inativa.');
            else if (err.status === 423) setError('Conta bloqueada temporariamente.');
            else if (err.status === 429) setError('Muitas tentativas. Aguarde alguns minutos.');
            else                          setError('Erro: ' + (err.message || 'desconhecido'));
            setTsToken(null);
            setTsReset(n => n + 1);   // forca novo desafio
        } finally {
            setLoading(false);
        }
    };

    const { CenterScreen } = window.C7_Layout;
    const { Field, Alert, Turnstile } = window.C7_Forms;

    return (
        <CenterScreen>
            <h2 style={{ marginTop: 0 }}>Entrar</h2>
            <Alert kind="error">{error}</Alert>
            <form onSubmit={on_submit}>
                <Field label="E-mail">
                    <input type="email" value={email} onChange={e => setEmail(e.target.value)}
                           autoComplete="email" required autoFocus />
                </Field>
                <Field label="Senha">
                    <input type="password" value={password} onChange={e => setPassword(e.target.value)}
                           autoComplete="current-password" required />
                </Field>
                <Turnstile on_token={setTsToken} reset_signal={tsReset} />
                <button type="submit" className="c-btn" style={{ width: '100%', marginTop: 8 }}
                        disabled={loading || !tsToken}>
                    {loading ? 'entrando…' : 'Entrar'}
                </button>
            </form>
            <div className="login-links">
                <a href="#/forgot-password" className="login-link">Esqueci minha senha</a>
                <span className="login-sep">·</span>
                <a href="#/register" className="login-link login-link-primary">Criar conta</a>
            </div>
            <style>{`
                .login-links {
                    margin-top: 22px;
                    text-align: center;
                    font-size: 13px;
                    color: rgba(200,200,205,0.6);
                }
                .login-link {
                    color: rgba(200,200,205,0.85);
                    text-decoration: none;
                    transition: color 0.15s;
                }
                .login-link:hover { color: var(--c7-white); }
                .login-link-primary {
                    color: var(--c7-platinum);
                    font-weight: 500;
                    text-decoration: underline;
                }
                .login-sep { margin: 0 12px; opacity: 0.4; }
            `}</style>
        </CenterScreen>
    );
}


async function hydrate_user_then_go() {
    // Busca /auth/me pra popular store com totp_enabled, must_change_password,
    // terms_accepted_at, etc. O guard em app.jsx usa isso pra decidir o chain
    // de onboarding (setup-2fa -> change-password -> aceitar-termos -> dashboard).
    try {
        const me = await window.C7_API.get('/auth/me');
        window.C7_STORE.set({ user: me });
    } catch (e) {
        window.C7_STORE.set({ user: { ok: true } });
    }
    window.C7_ROUTER.navigate('/dashboard');
}


window.C7_LoginPage = LoginPage;
window.C7_hydrate_user_then_go = hydrate_user_then_go;
