/* Pagina /setup-2fa — primeira configuracao do TOTP do user.
   Mostra QR code + campo pra digitar primeiro codigo + lista backup codes. */

const { useState, useEffect } = React;


function Setup2FAPage() {
    const [secret, setSecret]   = useState(null);
    const [uri, setUri]         = useState(null);
    const [code, setCode]       = useState('');
    const [step, setStep]       = useState('init');  // init | confirm | done
    const [backup, setBackup]   = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError]     = useState(null);

    useEffect(() => {
        (async () => {
            setLoading(true);
            try {
                const data = await window.C7_API.post('/auth/2fa/setup');
                setSecret(data.secret);
                setUri(data.provisioning_uri);
                setStep('confirm');
            } catch (err) {
                setError('Falha ao iniciar 2FA: ' + (err.message || 'erro'));
            } finally {
                setLoading(false);
            }
        })();
    }, []);

    const on_confirm = async (e) => {
        e.preventDefault();
        setError(null);
        setLoading(true);
        try {
            const data = await window.C7_API.post('/auth/2fa/enable', { code: code.trim() });
            setBackup(data.backup_codes || []);
            setStep('done');
        } catch (err) {
            if (err.status === 401) setError('Código inválido.');
            else                    setError(err.message);
        } finally {
            setLoading(false);
        }
    };

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

    return (
        <AppShell current_path="/setup-2fa">
            <div className="c-card" style={{ maxWidth: 600, margin: '0 auto' }}>
                <h2>Configurar 2FA</h2>

                {step === 'init' && <p style={{ color: 'rgba(200,200,205,0.6)' }}>iniciando…</p>}

                {step === 'confirm' && (
                    <>
                        <p style={{ color: 'rgba(200,200,205,0.7)', fontSize: 14 }}>
                            1. Abra o Google Authenticator (ou Authy) e escaneie o QR code abaixo.
                            <br/>2. Digite o código de 6 dígitos pra confirmar.
                        </p>
                        <div style={{ background: '#fff', padding: 16, borderRadius: 6,
                                      display: 'inline-block', margin: '14px 0' }}>
                            <window.C7_Forms.QRImage data={uri || ''} size={200} />
                        </div>
                        <Alert kind="error">{error}</Alert>
                        <form onSubmit={on_confirm} style={{ marginTop: 18 }}>
                            <Field label="Código de 6 dígitos">
                                <input type="text" value={code}
                                       onChange={e => setCode(e.target.value)}
                                       inputMode="numeric" autoComplete="one-time-code"
                                       pattern="[0-9]{6}" required autoFocus
                                       style={{ letterSpacing: 4, fontFamily: 'monospace', fontSize: 18 }} />
                            </Field>
                            <button type="submit" className="c-btn" disabled={loading}>
                                {loading ? 'confirmando…' : 'Habilitar 2FA'}
                            </button>
                        </form>
                    </>
                )}

                {step === 'done' && (
                    <>
                        <Alert kind="ok">2FA habilitado com sucesso.</Alert>
                        <h3>Backup codes (anote AGORA — não serão mostrados de novo)</h3>
                        <p style={{ color: 'rgba(200,200,205,0.65)', fontSize: 13 }}>
                            Use um destes códigos se perder acesso ao app autenticador.
                            Cada código funciona uma vez só.
                        </p>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8,
                                      fontFamily: 'monospace', fontSize: 14, margin: '14px 0',
                                      padding: 14, background: 'rgba(255,200,87,0.05)',
                                      border: '1px solid rgba(255,200,87,0.3)', borderRadius: 4 }}>
                            {backup.map((c, i) => <code key={i}>{c}</code>)}
                        </div>
                        <button className="c-btn"
                                onClick={async () => {
                                    // Atualiza store apos habilitar 2FA pra que o
                                    // chain (change-password / aceitar-termos) prossiga.
                                    try {
                                        const me = await window.C7_API.get('/auth/me');
                                        window.C7_STORE.set({ user: me });
                                    } catch (e) { /* segue */ }
                                    window.C7_ROUTER.navigate('/dashboard');
                                }}>
                            Anotei, ir pro Dashboard
                        </button>
                    </>
                )}
            </div>
        </AppShell>
    );
}

window.C7_Setup2FAPage = Setup2FAPage;
