/* Pagina /login/2fa — confirma codigo TOTP apos password. */

const { useState } = React;

function Login2FAPage() {
    const [code, setCode]       = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError]     = useState(null);

    const twofa_token = window.sessionStorage.getItem('c7_twofa_token');

    if (!twofa_token) {
        // Veio direto sem passar pelo /login — manda de volta
        window.C7_ROUTER.replace('/login');
        return null;
    }

    const on_submit = async (e) => {
        e.preventDefault();
        setError(null);
        setLoading(true);
        try {
            await window.C7_API.login_2fa(twofa_token, code.trim());
            window.sessionStorage.removeItem('c7_twofa_token');
            await window.C7_hydrate_user_then_go();
        } catch (err) {
            if (err.status === 401) setError('Código inválido.');
            else                    setError(err.message || 'erro desconhecido');
        } finally {
            setLoading(false);
        }
    };

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

    return (
        <CenterScreen>
            <h2 style={{ marginTop: 0 }}>Verificação 2FA</h2>
            <p style={{ color: 'rgba(200,200,205,0.55)', fontSize: 13, marginTop: -4 }}>
                Cole o código de 6 dígitos do seu app autenticador (Google Authenticator, Authy)
                ou um backup code.
            </p>
            <Alert kind="error">{error}</Alert>
            <form onSubmit={on_submit}>
                <Field label="Código">
                    <input type="text" value={code}
                           onChange={e => setCode(e.target.value)}
                           inputMode="numeric" autoComplete="one-time-code"
                           pattern="[0-9A-Za-z_\-]{6,12}" autoFocus required
                           style={{ letterSpacing: 4, fontFamily: 'monospace', fontSize: 18 }} />
                </Field>
                <button type="submit" className="c-btn" style={{ width: '100%', marginTop: 8 }}
                        disabled={loading}>
                    {loading ? 'verificando…' : 'Confirmar'}
                </button>
            </form>
        </CenterScreen>
    );
}

window.C7_Login2FAPage = Login2FAPage;
