// Security section of the Settings modal — manage TOTP (authenticator app)
// and WebAuthn security keys / passkeys. Self-contained: owns its own status
// fetch and all enrollment sub-flows so SettingsModal just drops it in.
const TwoFactorSettings = () => {
    const [status, setStatus]   = React.useState(null);   // { totp_enabled, credentials, backup_codes_remaining }
    const [error, setError]     = React.useState('');
    const [busy, setBusy]       = React.useState(false);

    // Sub-flow state. `flow` is which mini-wizard is open:
    // null | 'totp-setup' | 'totp-disable' | 'key-add' | { removeKey: id }
    const [flow, setFlow]       = React.useState(null);
    const [qr, setQr]           = React.useState(null);    // { qr, secret } during TOTP setup
    const [code, setCode]       = React.useState('');
    const [password, setPassword] = React.useState('');
    const [keyName, setKeyName] = React.useState('');
    const [backupCodes, setBackupCodes] = React.useState(null);  // shown exactly once after enable

    const refresh = async () => {
        try { setStatus(await api.get2faStatus()); }
        catch (err) { setError(err.message); }
    };
    React.useEffect(() => { refresh(); }, []);

    const closeFlow = () => { setFlow(null); setQr(null); setCode(''); setPassword(''); setKeyName(''); };

    const run = async (fn) => {   // shared busy/error wrapper for the action handlers
        setBusy(true);
        setError('');
        try { await fn(); }
        catch (err) { setError(err.name === 'NotAllowedError' ? 'Security key prompt was cancelled.' : err.message); }
        finally { setBusy(false); }
    };

    const startTotpSetup = () => run(async () => {
        setQr(await api.setupTotp());
        setFlow('totp-setup');
    });

    const confirmTotp = (e) => { e.preventDefault(); run(async () => {
        const result = await api.confirmTotp(code);
        setBackupCodes(result.backup_codes);
        closeFlow();
        await refresh();
    }); };

    const disableTotp = (e) => { e.preventDefault(); run(async () => {
        await api.disableTotp(password);
        setBackupCodes(null);
        closeFlow();
        await refresh();
    }); };

    const addKey = (e) => { e.preventDefault(); run(async () => {
        const options = await api.webauthnRegisterOptions();
        const attestation = await SimpleWebAuthnBrowser.startRegistration({ optionsJSON: options });
        await api.webauthnRegister(attestation, keyName);
        closeFlow();
        await refresh();
    }); };

    const removeKey = (e) => { e.preventDefault(); run(async () => {
        await api.removeWebauthnKey(flow.removeKey, password);
        closeFlow();
        await refresh();
    }); };

    if (!status) return <div className="form-section"><h4><i className="fas fa-shield-alt" style={{ marginRight: '0.375rem' }}></i>Security</h4><p className="settings-hint">Loading…</p></div>;

    const mono = { fontFamily: 'monospace', userSelect: 'all', wordBreak: 'break-all' };

    return (
        <div className="form-section">
            <h4><i className="fas fa-shield-alt" style={{ marginRight: '0.375rem' }}></i>Security</h4>
            {error && <div className="api-error">{error}</div>}

            {/* Backup codes — displayed exactly once, right after TOTP enable */}
            {backupCodes && (
                <div className="login-error" style={{ background: 'transparent' }}>
                    <div>
                        <strong>Backup codes — save these now.</strong> Each works once if you lose your phone; they will never be shown again.
                        <div style={{ ...mono, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.25rem 1rem', margin: '0.5rem 0' }}>
                            {backupCodes.map(c => <span key={c}>{c}</span>)}
                        </div>
                        <button className="btn btn-secondary" onClick={() => { navigator.clipboard.writeText(backupCodes.join('\n')); }}>
                            <i className="fas fa-copy"></i> Copy all
                        </button>
                        <button className="btn btn-secondary" style={{ marginLeft: '0.5rem' }} onClick={() => setBackupCodes(null)}>
                            I saved them
                        </button>
                    </div>
                </div>
            )}

            {/* ── Authenticator app (TOTP) ─────────────────────────── */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '0.75rem 0 0.25rem' }}>
                <div>
                    <strong>Authenticator app</strong>
                    <p className="settings-hint" style={{ margin: 0 }}>
                        {status.totp_enabled
                            ? `On — ${status.backup_codes_remaining} backup code${status.backup_codes_remaining === 1 ? '' : 's'} left`
                            : 'Six-digit codes from an app like Google Authenticator or 1Password.'}
                    </p>
                </div>
                {!flow && (status.totp_enabled
                    ? <button className="btn btn-secondary" onClick={() => setFlow('totp-disable')}>Turn off</button>
                    : <button className="btn btn-primary" onClick={startTotpSetup} disabled={busy}>Set up</button>)}
            </div>

            {flow === 'totp-setup' && qr && (
                <form onSubmit={confirmTotp} style={{ margin: '0.75rem 0' }}>
                    <p className="settings-hint">Scan with your authenticator app, then enter the code it shows.</p>
                    <img src={qr.qr} alt="TOTP QR code" style={{ display: 'block', margin: '0.5rem 0', borderRadius: '8px' }} />
                    <p className="settings-hint">Can't scan? Enter manually: <span style={mono}>{qr.secret}</span></p>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <input type="text" className="form-input" value={code} onChange={e => setCode(e.target.value)}
                               placeholder="123 456" inputMode="numeric" autoComplete="one-time-code" required autoFocus style={{ maxWidth: '10rem' }} />
                        <button type="submit" className="btn btn-primary" disabled={busy}>Confirm</button>
                        <button type="button" className="btn btn-secondary" onClick={closeFlow}>Cancel</button>
                    </div>
                </form>
            )}

            {flow === 'totp-disable' && (
                <form onSubmit={disableTotp} style={{ margin: '0.75rem 0' }}>
                    <p className="settings-hint">Confirm your password to turn off the authenticator app. Your backup codes will be deleted too.</p>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <input type="password" className="form-input" value={password} onChange={e => setPassword(e.target.value)}
                               placeholder="Current password" required autoFocus style={{ maxWidth: '14rem' }} />
                        <button type="submit" className="btn btn-primary" disabled={busy}>Turn off</button>
                        <button type="button" className="btn btn-secondary" onClick={closeFlow}>Cancel</button>
                    </div>
                </form>
            )}

            {/* ── Security keys / passkeys ─────────────────────────── */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '1rem 0 0.25rem' }}>
                <div>
                    <strong>Security keys</strong>
                    <p className="settings-hint" style={{ margin: 0 }}>A hardware key (YubiKey) or the passkey built into your phone or laptop.</p>
                </div>
                {!flow && <button className="btn btn-primary" onClick={() => setFlow('key-add')}>Add key</button>}
            </div>

            {status.credentials.map(c => (
                <div key={c.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0.375rem 0' }}>
                    <span><i className="fas fa-key" style={{ marginRight: '0.5rem', opacity: 0.6 }}></i>{c.name}
                        <span className="settings-hint" style={{ marginLeft: '0.5rem' }}>
                            added {formatDate(c.created_at)}{c.last_used_at ? ` · last used ${formatDate(c.last_used_at)}` : ''}
                        </span>
                    </span>
                    {!flow && <button className="btn btn-secondary" onClick={() => setFlow({ removeKey: c.id })}>Remove</button>}
                </div>
            ))}

            {flow === 'key-add' && (
                <form onSubmit={addKey} style={{ margin: '0.75rem 0' }}>
                    <p className="settings-hint">Name the key, then follow your browser's prompt.</p>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <input type="text" className="form-input" value={keyName} onChange={e => setKeyName(e.target.value)}
                               placeholder="e.g. YubiKey, iPhone" required autoFocus style={{ maxWidth: '14rem' }} />
                        <button type="submit" className="btn btn-primary" disabled={busy}>{busy ? 'Waiting for key…' : 'Register'}</button>
                        <button type="button" className="btn btn-secondary" onClick={closeFlow}>Cancel</button>
                    </div>
                </form>
            )}

            {flow && flow.removeKey && (
                <form onSubmit={removeKey} style={{ margin: '0.75rem 0' }}>
                    <p className="settings-hint">Confirm your password to remove this key.</p>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <input type="password" className="form-input" value={password} onChange={e => setPassword(e.target.value)}
                               placeholder="Current password" required autoFocus style={{ maxWidth: '14rem' }} />
                        <button type="submit" className="btn btn-primary" disabled={busy}>Remove key</button>
                        <button type="button" className="btn btn-secondary" onClick={closeFlow}>Cancel</button>
                    </div>
                </form>
            )}
        </div>
    );
};
