/* ============================================================================
 *  components-2fa-email.jsx
 *
 *  React components for the new features:
 *    - TwoFactorLoginStep   — shown after password login when 2FA is required
 *    - TwoFactorEnrollment  — forced enrollment after login when platform requires 2FA
 *    - TwoFactorSettings    — user-facing setup/disable/regenerate
 *    - EmailForwarding      — user settings for SMS-to-email
 *    - AdminSmtpSettings    — admin SMTP relay configuration
 *    - AdminSecuritySettings — admin require_2fa toggle
 *
 *  These are written as CDN-React (Babel standalone), matching the existing
 *  index.html. Wire into the existing App by importing/using them where
 *  appropriate. The functions assume the existing fetch wrapper exposes:
 *    window.api.get(path)       → JSON
 *    window.api.post(path, body)
 *    window.api.put(path, body)
 *  If your existing app uses a different convention, swap the calls inline.
 * ============================================================================ */

/* eslint-disable */
const { useState, useEffect, useCallback } = React;

// ─── Small UI primitives that match the existing look ──────────────────────
function Field({ label, children, help }) {
    return (
        <div className="mb-3">
            <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
            {children}
            {help && <p className="mt-1 text-xs text-gray-500">{help}</p>}
        </div>
    );
}

function Alert({ kind, children }) {
    const styles = {
        ok:    'bg-green-50 text-green-800 border-green-200',
        warn:  'bg-yellow-50 text-yellow-800 border-yellow-200',
        err:   'bg-red-50 text-red-800 border-red-200',
        info:  'bg-blue-50 text-blue-800 border-blue-200',
    };
    return <div className={`p-3 border rounded-md text-sm ${styles[kind] || styles.info}`}>{children}</div>;
}

function Btn({ children, kind = 'primary', ...rest }) {
    const cls = {
        primary:   'bg-blue-600 hover:bg-blue-700 text-white',
        secondary: 'bg-gray-200 hover:bg-gray-300 text-gray-800',
        danger:    'bg-red-600 hover:bg-red-700 text-white',
    }[kind];
    return (
        <button
            className={`px-4 py-2 rounded-md text-sm font-medium disabled:opacity-50 ${cls}`}
            {...rest}
        >
            {children}
        </button>
    );
}

// ========================================================================
//  TwoFactorLoginStep
//  Shown after the password step when the server returns requires_2fa.
//  Props: tmp_token, onSuccess({token, user, used_backup_code}), onCancel()
// ========================================================================
function TwoFactorLoginStep({ tmp_token, onSuccess, onCancel }) {
    const [code, setCode] = useState('');
    const [err, setErr]   = useState(null);
    const [busy, setBusy] = useState(false);

    const submit = async (e) => {
        e && e.preventDefault();
        if (busy) return;
        setErr(null); setBusy(true);
        try {
            const r = await fetch('/api/auth/2fa/verify', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ tmp_token, code }),
            });
            const data = await r.json();
            if (!r.ok) throw new Error(data.error || 'Verification failed');
            onSuccess(data);
        } catch (e) {
            setErr(e.message);
        } finally {
            setBusy(false);
        }
    };

    return (
        <form onSubmit={submit} className="space-y-3">
            <h2 className="text-lg font-semibold">Two-factor authentication</h2>
            <p className="text-sm text-gray-600">
                Enter the 6-digit code from your authenticator app, or one of your recovery codes.
            </p>
            <input
                type="text"
                value={code}
                onChange={e => setCode(e.target.value.replace(/[^0-9A-Za-z-]/g, ''))}
                placeholder="123456 or XXXX-XXXX-XX"
                autoFocus
                inputMode="text"
                maxLength={14}
                className="w-full px-3 py-2 border rounded-md font-mono text-center text-lg tracking-widest"
            />
            {err && <Alert kind="err">{err}</Alert>}
            <div className="flex gap-2 justify-end">
                {onCancel && <Btn type="button" kind="secondary" onClick={onCancel}>Cancel</Btn>}
                <Btn type="submit" disabled={busy || code.length < 6}>
                    {busy ? 'Verifying…' : 'Verify'}
                </Btn>
            </div>
        </form>
    );
}

// ========================================================================
//  TwoFactorEnrollment
//  Forced enrollment after login when platform requires 2FA.
//  Props: tmp_token, onSuccess({token, user, backup_codes})
// ========================================================================
function TwoFactorEnrollment({ tmp_token, onSuccess }) {
    const [qr, setQr]               = useState(null);
    const [secret, setSecret]       = useState(null);
    const [code, setCode]           = useState('');
    const [busy, setBusy]           = useState(false);
    const [err, setErr]             = useState(null);
    const [backupCodes, setBackupCodes] = useState(null);
    const [pendingResult, setPendingResult] = useState(null);

    useEffect(() => {
        (async () => {
            try {
                const r = await fetch('/api/auth/2fa/setup', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ tmp_token }),
                });
                const d = await r.json();
                if (!r.ok) throw new Error(d.error || 'Setup failed');
                setQr(d.qr_data_url); setSecret(d.secret);
            } catch (e) { setErr(e.message); }
        })();
    }, [tmp_token]);

    const enable = async () => {
        if (busy) return;
        setErr(null); setBusy(true);
        try {
            const r = await fetch('/api/auth/2fa/enable', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ tmp_token, code }),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Enable failed');
            setBackupCodes(d.backup_codes);
            setPendingResult(d);
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    if (backupCodes) {
        return (
            <div className="space-y-3">
                <h2 className="text-lg font-semibold">Save your recovery codes</h2>
                <Alert kind="warn">
                    Store these somewhere safe. Each can be used once if you lose your authenticator.
                    They will not be shown again.
                </Alert>
                <pre className="bg-gray-50 p-3 rounded text-sm font-mono">
                    {backupCodes.join('\n')}
                </pre>
                <div className="flex justify-end">
                    <Btn onClick={() => onSuccess(pendingResult)}>I've saved them — continue</Btn>
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-3">
            <h2 className="text-lg font-semibold">Set up two-factor authentication</h2>
            <p className="text-sm text-gray-600">
                Two-factor authentication is required on this platform. Scan the QR with your
                authenticator app (Google Authenticator, Authy, 1Password, etc.) and enter the
                6-digit code to finish.
            </p>
            {qr ? (
                <div className="text-center">
                    <img src={qr} alt="Scan with authenticator" className="mx-auto"/>
                    <p className="mt-2 text-xs text-gray-500 font-mono break-all">{secret}</p>
                </div>
            ) : <p className="text-sm text-gray-500">Generating secret…</p>}
            <Field label="6-digit code from your app">
                <input
                    type="text"
                    value={code}
                    onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                    maxLength={6}
                    inputMode="numeric"
                    className="w-full px-3 py-2 border rounded-md font-mono text-center text-lg tracking-widest"
                    placeholder="123456"
                />
            </Field>
            {err && <Alert kind="err">{err}</Alert>}
            <div className="flex justify-end">
                <Btn onClick={enable} disabled={busy || code.length !== 6}>
                    {busy ? 'Enabling…' : 'Enable 2FA'}
                </Btn>
            </div>
        </div>
    );
}

// ========================================================================
//  TwoFactorSettings (user-facing, in Settings page)
//  Props: user (current user object with totp_enabled), onChange (refresh user)
// ========================================================================
function TwoFactorSettings({ user, onChange }) {
    const [mode, setMode]               = useState('idle'); // idle | enrolling | confirming | disabling | regenerating
    const [qr, setQr]                   = useState(null);
    const [secret, setSecret]           = useState(null);
    const [code, setCode]               = useState('');
    const [password, setPassword]       = useState('');
    const [busy, setBusy]               = useState(false);
    const [err, setErr]                 = useState(null);
    const [backupCodes, setBackupCodes] = useState(null);

    const auth = useCallback(() => {
        const t = localStorage.getItem('token');
        return t ? { Authorization: `Bearer ${t}` } : {};
    }, []);

    const reset = () => {
        setMode('idle'); setQr(null); setSecret(null);
        setCode(''); setPassword(''); setErr(null); setBackupCodes(null);
    };

    const startEnrollment = async () => {
        setBusy(true); setErr(null);
        try {
            const r = await fetch('/api/auth/2fa/setup', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', ...auth() },
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Setup failed');
            setQr(d.qr_data_url); setSecret(d.secret); setMode('confirming');
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    const confirmEnable = async () => {
        setBusy(true); setErr(null);
        try {
            const r = await fetch('/api/auth/2fa/enable', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', ...auth() },
                body: JSON.stringify({ code }),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Enable failed');
            setBackupCodes(d.backup_codes);
            onChange && onChange();
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    const disable = async () => {
        setBusy(true); setErr(null);
        try {
            const r = await fetch('/api/auth/2fa/disable', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', ...auth() },
                body: JSON.stringify({ password, code }),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Disable failed');
            reset();
            onChange && onChange();
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    const regenerate = async () => {
        setBusy(true); setErr(null);
        try {
            const r = await fetch('/api/auth/2fa/regenerate-codes', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', ...auth() },
                body: JSON.stringify({ password, code }),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Regenerate failed');
            setBackupCodes(d.backup_codes);
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    if (backupCodes) {
        return (
            <div className="space-y-3 border rounded-lg p-4 bg-white">
                <h3 className="font-semibold">Two-Factor Authentication</h3>
                <Alert kind="warn">
                    Save these recovery codes. Each can be used once. They will not be shown again.
                </Alert>
                <pre className="bg-gray-50 p-3 rounded text-sm font-mono">{backupCodes.join('\n')}</pre>
                <div className="flex justify-end">
                    <Btn onClick={reset}>Done</Btn>
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-3 border rounded-lg p-4 bg-white">
            <div className="flex items-center justify-between">
                <h3 className="font-semibold">Two-Factor Authentication</h3>
                <span className={`px-2 py-1 text-xs rounded ${user.totp_enabled ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'}`}>
                    {user.totp_enabled ? 'Enabled' : 'Disabled'}
                </span>
            </div>

            {mode === 'idle' && !user.totp_enabled && (
                <>
                    <p className="text-sm text-gray-600">
                        Protect your account with an authenticator app. You'll be asked for
                        a 6-digit code each time you log in.
                    </p>
                    {err && <Alert kind="err">{err}</Alert>}
                    <Btn onClick={startEnrollment} disabled={busy}>Enable 2FA</Btn>
                </>
            )}

            {mode === 'idle' && user.totp_enabled && (
                <>
                    <p className="text-sm text-gray-600">
                        Two-factor authentication is active on your account.
                    </p>
                    {err && <Alert kind="err">{err}</Alert>}
                    <div className="flex gap-2">
                        <Btn kind="secondary" onClick={() => setMode('regenerating')}>Regenerate recovery codes</Btn>
                        <Btn kind="danger" onClick={() => setMode('disabling')}>Disable 2FA</Btn>
                    </div>
                </>
            )}

            {mode === 'confirming' && (
                <>
                    <p className="text-sm text-gray-600">
                        Scan with your authenticator app, then enter the code it shows.
                    </p>
                    {qr && <img src={qr} alt="Scan" className="mx-auto"/>}
                    {secret && <p className="text-xs text-gray-500 font-mono break-all text-center">{secret}</p>}
                    <Field label="Code from your app">
                        <input
                            type="text"
                            value={code}
                            onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                            maxLength={6}
                            inputMode="numeric"
                            className="w-full px-3 py-2 border rounded-md font-mono text-center text-lg tracking-widest"
                            placeholder="123456"
                        />
                    </Field>
                    {err && <Alert kind="err">{err}</Alert>}
                    <div className="flex gap-2 justify-end">
                        <Btn kind="secondary" onClick={reset}>Cancel</Btn>
                        <Btn onClick={confirmEnable} disabled={busy || code.length !== 6}>
                            {busy ? 'Enabling…' : 'Confirm & enable'}
                        </Btn>
                    </div>
                </>
            )}

            {(mode === 'disabling' || mode === 'regenerating') && (
                <>
                    <p className="text-sm text-gray-600">
                        Confirm with your password and a current 2FA code.
                    </p>
                    <Field label="Current password">
                        <input type="password" value={password} onChange={e => setPassword(e.target.value)}
                            className="w-full px-3 py-2 border rounded-md"/>
                    </Field>
                    <Field label="6-digit code">
                        <input type="text" value={code}
                            onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                            maxLength={6} inputMode="numeric"
                            className="w-full px-3 py-2 border rounded-md font-mono text-center tracking-widest"/>
                    </Field>
                    {err && <Alert kind="err">{err}</Alert>}
                    <div className="flex gap-2 justify-end">
                        <Btn kind="secondary" onClick={reset}>Cancel</Btn>
                        <Btn kind={mode === 'disabling' ? 'danger' : 'primary'}
                             onClick={mode === 'disabling' ? disable : regenerate}
                             disabled={busy || !password || code.length !== 6}>
                            {busy ? '…' : (mode === 'disabling' ? 'Disable 2FA' : 'Generate new codes')}
                        </Btn>
                    </div>
                </>
            )}
        </div>
    );
}

// ========================================================================
//  EmailForwarding (user Settings)
// ========================================================================
function EmailForwarding({ userDIDs = [] }) {
    const [cfg, setCfg]     = useState(null);
    const [busy, setBusy]   = useState(false);
    const [msg, setMsg]     = useState(null);
    const [err, setErr]     = useState(null);

    const auth = () => {
        const t = localStorage.getItem('token');
        return t ? { Authorization: `Bearer ${t}` } : {};
    };

    const load = async () => {
        try {
            const r = await fetch('/api/email-forwards', { headers: auth() });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Load failed');
            setCfg({
                enabled: !!d.enabled,
                recipients: d.recipients || '',
                subject_template: d.subject_template || 'SMS from {from} to {to}',
                did_filter: d.did_filter || [],
                last_sent_at: d.last_sent_at,
                last_error: d.last_error,
            });
        } catch (e) { setErr(e.message); }
    };

    useEffect(() => { load(); }, []);

    const save = async () => {
        setBusy(true); setErr(null); setMsg(null);
        try {
            const r = await fetch('/api/email-forwards', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json', ...auth() },
                body: JSON.stringify({
                    enabled: cfg.enabled,
                    recipients: cfg.recipients,
                    subject_template: cfg.subject_template,
                    did_filter: cfg.did_filter && cfg.did_filter.length ? cfg.did_filter : null,
                }),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Save failed');
            setMsg('Saved.');
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    const test = async () => {
        setBusy(true); setErr(null); setMsg(null);
        try {
            const r = await fetch('/api/email-forwards/test', {
                method: 'POST', headers: auth(),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Test failed');
            setMsg(`Test email sent to ${d.sent_to.join(', ')}`);
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    const toggleDid = (number) => {
        setCfg(c => {
            const cur = new Set(c.did_filter || []);
            cur.has(number) ? cur.delete(number) : cur.add(number);
            return { ...c, did_filter: Array.from(cur) };
        });
    };

    if (!cfg) return <div className="p-4 text-gray-500">Loading…</div>;

    return (
        <div className="space-y-3 border rounded-lg p-4 bg-white">
            <h3 className="font-semibold">SMS → Email Forwarding</h3>
            <p className="text-sm text-gray-600">
                Forward inbound SMS to one or more email addresses. Up to 3 recipients.
            </p>

            <label className="flex items-center gap-2">
                <input
                    type="checkbox"
                    checked={cfg.enabled}
                    onChange={e => setCfg({ ...cfg, enabled: e.target.checked })}
                />
                <span className="text-sm font-medium">Enable forwarding</span>
            </label>

            <Field label="Recipient emails (comma-separated, max 3)">
                <input
                    type="text"
                    value={cfg.recipients}
                    onChange={e => setCfg({ ...cfg, recipients: e.target.value })}
                    placeholder="alice@example.com, ops@example.com"
                    className="w-full px-3 py-2 border rounded-md"
                />
            </Field>

            <Field label="Subject template" help="{from} = sender, {to} = your DID">
                <input
                    type="text"
                    value={cfg.subject_template}
                    onChange={e => setCfg({ ...cfg, subject_template: e.target.value })}
                    className="w-full px-3 py-2 border rounded-md"
                />
            </Field>

            {userDIDs.length > 0 && (
                <Field label="DID filter (optional)" help="Empty = forward all DIDs. Select to limit which DIDs forward.">
                    <div className="space-y-1 max-h-40 overflow-y-auto border rounded-md p-2">
                        {userDIDs.map(d => (
                            <label key={d.number} className="flex items-center gap-2 text-sm">
                                <input
                                    type="checkbox"
                                    checked={(cfg.did_filter || []).includes(d.number)}
                                    onChange={() => toggleDid(d.number)}
                                />
                                <span className="font-mono">{d.number}</span>
                            </label>
                        ))}
                    </div>
                </Field>
            )}

            {cfg.last_sent_at && (
                <p className="text-xs text-gray-500">Last forwarded: {new Date(cfg.last_sent_at).toLocaleString()}</p>
            )}
            {cfg.last_error && <Alert kind="warn">Last error: {cfg.last_error}</Alert>}
            {msg && <Alert kind="ok">{msg}</Alert>}
            {err && <Alert kind="err">{err}</Alert>}

            <div className="flex gap-2 justify-end">
                <Btn kind="secondary" onClick={test} disabled={busy || !cfg.recipients}>Send test</Btn>
                <Btn onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Save'}</Btn>
            </div>
        </div>
    );
}

// ========================================================================
//  AdminSmtpSettings (admin only)
// ========================================================================
function AdminSmtpSettings() {
    const [s, setS]       = useState(null);
    const [test, setTest] = useState('');
    const [busy, setBusy] = useState(false);
    const [msg, setMsg]   = useState(null);
    const [err, setErr]   = useState(null);

    const auth = () => {
        const t = localStorage.getItem('token');
        return t ? { Authorization: `Bearer ${t}` } : {};
    };

    useEffect(() => {
        (async () => {
            const r = await fetch('/api/admin/smtp', { headers: auth() });
            const d = await r.json();
            if (r.ok) setS(d); else setErr(d.error);
        })();
    }, []);

    const save = async () => {
        setBusy(true); setErr(null); setMsg(null);
        try {
            const payload = { ...s };
            // Send booleans as '1'/'0' strings — backend normalizes
            payload.smtp_enabled = (s.smtp_enabled === '1' || s.smtp_enabled === 1 || s.smtp_enabled === true) ? '1' : '0';
            payload.smtp_secure  = (s.smtp_secure  === '1' || s.smtp_secure  === 1 || s.smtp_secure  === true) ? '1' : '0';
            const r = await fetch('/api/admin/smtp', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json', ...auth() },
                body: JSON.stringify(payload),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Save failed');
            setMsg('Saved.');
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    const sendTest = async () => {
        setBusy(true); setErr(null); setMsg(null);
        try {
            const r = await fetch('/api/admin/smtp/test', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', ...auth() },
                body: JSON.stringify({ to: test }),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Test failed');
            setMsg(`Test email sent to ${test}`);
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    if (!s) return <div className="p-4 text-gray-500">Loading…</div>;

    const setK = (k, v) => setS(prev => ({ ...prev, [k]: v }));

    return (
        <div className="space-y-3 border rounded-lg p-4 bg-white">
            <h3 className="font-semibold">SMTP Relay (SMS-to-Email)</h3>

            <label className="flex items-center gap-2">
                <input
                    type="checkbox"
                    checked={s.smtp_enabled === '1' || s.smtp_enabled === true}
                    onChange={e => setK('smtp_enabled', e.target.checked ? '1' : '0')}
                />
                <span className="text-sm font-medium">Enable SMTP relay</span>
            </label>

            <div className="grid grid-cols-2 gap-3">
                <Field label="Host"><input className="w-full px-3 py-2 border rounded-md" value={s.smtp_host} onChange={e => setK('smtp_host', e.target.value)} placeholder="smtp.sendgrid.net"/></Field>
                <Field label="Port"><input className="w-full px-3 py-2 border rounded-md" value={s.smtp_port} onChange={e => setK('smtp_port', e.target.value)} placeholder="587"/></Field>
                <Field label="Username"><input className="w-full px-3 py-2 border rounded-md" value={s.smtp_user} onChange={e => setK('smtp_user', e.target.value)} placeholder="apikey"/></Field>
                <Field label="Password"><input type="password" className="w-full px-3 py-2 border rounded-md" value={s.smtp_pass} onChange={e => setK('smtp_pass', e.target.value)} placeholder="••••••••"/></Field>
                <Field label="From address"><input className="w-full px-3 py-2 border rounded-md" value={s.smtp_from} onChange={e => setK('smtp_from', e.target.value)} placeholder="noreply@smscloud.io"/></Field>
                <Field label="From name"><input className="w-full px-3 py-2 border rounded-md" value={s.smtp_from_name} onChange={e => setK('smtp_from_name', e.target.value)} placeholder="SMS Cloud"/></Field>
            </div>

            <label className="flex items-center gap-2">
                <input type="checkbox" checked={s.smtp_secure === '1' || s.smtp_secure === true} onChange={e => setK('smtp_secure', e.target.checked ? '1' : '0')}/>
                <span className="text-sm">Use TLS (port 465). Leave unchecked for STARTTLS on 587.</span>
            </label>

            {msg && <Alert kind="ok">{msg}</Alert>}
            {err && <Alert kind="err">{err}</Alert>}

            <div className="flex gap-2 justify-end">
                <Btn onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Save'}</Btn>
            </div>

            <hr className="my-2"/>

            <Field label="Send test email to">
                <div className="flex gap-2">
                    <input className="flex-1 px-3 py-2 border rounded-md" value={test} onChange={e => setTest(e.target.value)} placeholder="you@example.com"/>
                    <Btn kind="secondary" onClick={sendTest} disabled={busy || !test}>Send test</Btn>
                </div>
            </Field>
        </div>
    );
}

// ========================================================================
//  AdminSecuritySettings — require_2fa platform-wide toggle
// ========================================================================
function AdminSecuritySettings() {
    const [require2fa, setRequire2fa] = useState(null);
    const [busy, setBusy]             = useState(false);
    const [err, setErr]               = useState(null);
    const [msg, setMsg]               = useState(null);

    const auth = () => {
        const t = localStorage.getItem('token');
        return t ? { Authorization: `Bearer ${t}` } : {};
    };

    useEffect(() => {
        (async () => {
            const r = await fetch('/api/admin/smtp/security', { headers: auth() });
            const d = await r.json();
            if (r.ok) setRequire2fa(d.require_2fa); else setErr(d.error);
        })();
    }, []);

    const save = async () => {
        setBusy(true); setErr(null); setMsg(null);
        try {
            const r = await fetch('/api/admin/smtp/security', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json', ...auth() },
                body: JSON.stringify({ require_2fa: require2fa }),
            });
            const d = await r.json();
            if (!r.ok) throw new Error(d.error || 'Save failed');
            setMsg('Saved.');
        } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    if (require2fa === null) return <div className="p-4 text-gray-500">Loading…</div>;

    return (
        <div className="space-y-3 border rounded-lg p-4 bg-white">
            <h3 className="font-semibold">Platform Security</h3>
            <label className="flex items-center gap-2">
                <input type="checkbox" checked={require2fa} onChange={e => setRequire2fa(e.target.checked)}/>
                <span className="text-sm font-medium">Require 2FA for all users</span>
            </label>
            <p className="text-xs text-gray-500">
                When enabled, all users without 2FA will be forced to enroll on next login.
                Existing 2FA-enabled users cannot disable it.
            </p>
            {msg && <Alert kind="ok">{msg}</Alert>}
            {err && <Alert kind="err">{err}</Alert>}
            <div className="flex justify-end">
                <Btn onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Save'}</Btn>
            </div>
        </div>
    );
}

// Expose components globally so they can be picked up by the existing app
window.SMSPlatformComponents = {
    TwoFactorLoginStep,
    TwoFactorEnrollment,
    TwoFactorSettings,
    EmailForwarding,
    AdminSmtpSettings,
    AdminSecuritySettings,
};
