// Security — sign-in protection for the signed-in user's own account:
// password change, authenticator-app 2FA, security keys / passkeys, backup
// codes. Split out of My Preferences (2026-08-02, owner's call) so "how I
// sign in" and "how the app looks" are separate cards. TwoFactorSettings is
// self-contained (owns its status fetch and enrollment flows).

// Change password — re-authenticates with the current password (the server
// enforces it; a walked-away session must not be enough to set a new one)
// and runs the new one through the same policy as every other set-password
// path (server/lib/password.js).
const ChangePasswordCard = () => {
    const [open, setOpen]       = React.useState(false);
    const [current, setCurrent] = React.useState('');
    const [next, setNext]       = React.useState('');
    const [confirm, setConfirm] = React.useState('');
    const [busy, setBusy]       = React.useState(false);
    const [error, setError]     = React.useState('');
    const [done, setDone]       = React.useState(false);

    const reset = () => { setCurrent(''); setNext(''); setConfirm(''); setError(''); };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (next !== confirm) { setError('New passwords don\'t match.'); return; }
        setBusy(true); setError('');
        try {
            await api.changePassword(current, next);
            reset(); setOpen(false); setDone(true);
        } catch (err) { setError(err.message); }
        finally { setBusy(false); }
    };

    return (
        <div className="form-section">
            <h4><i className="fas fa-key" style={{ marginRight: '0.375rem' }}></i>Password</h4>
            {done && !open && (
                <p className="api-success" style={{ fontSize: '0.875rem' }}>
                    <i className="fas fa-check"></i> Password updated. Any password-reset links that were out there are now dead.
                </p>
            )}
            {!open ? (
                <button className="btn btn-secondary btn-small" onClick={() => { setDone(false); setOpen(true); }}>
                    <i className="fas fa-pencil-alt"></i> Change password
                </button>
            ) : (
                <form onSubmit={handleSubmit} style={{ maxWidth: 420 }}>
                    {error && <div className="api-error">{error}</div>}
                    <div className="form-group">
                        <label className="form-label">Current password</label>
                        <input type="password" className="form-input" value={current} autoComplete="current-password"
                               onChange={e => setCurrent(e.target.value)} required autoFocus />
                    </div>
                    <div className="form-group">
                        <label className="form-label">New password</label>
                        <input type="password" className="form-input" value={next} autoComplete="new-password"
                               onChange={e => setNext(e.target.value)} required minLength={12} />
                        <p className="form-hint">At least 12 characters. Length beats complexity — a passphrase works great.</p>
                    </div>
                    <div className="form-group">
                        <label className="form-label">Confirm new password</label>
                        <input type="password" className="form-input" value={confirm} autoComplete="new-password"
                               onChange={e => setConfirm(e.target.value)} required minLength={12} />
                    </div>
                    <div className="btn-group">
                        <button type="button" className="btn btn-secondary" onClick={() => { reset(); setOpen(false); }} disabled={busy}>Cancel</button>
                        <button type="submit" className="btn btn-primary" disabled={busy}>
                            {busy ? <><i className="fas fa-spinner fa-spin"></i> Updating…</> : <><i className="fas fa-check"></i> Update password</>}
                        </button>
                    </div>
                </form>
            )}
        </div>
    );
};

const SecuritySection = () => (
    <div>
        <ChangePasswordCard />
        <TwoFactorSettings />
    </div>
);
