const LoginScreen = ({ onLogin }) => {
    const [form, setForm]       = React.useState({ email: '', password: '' });
    const [error, setError]     = React.useState('');
    const [loading, setLoading] = React.useState(false);

    // Two-step login: after a correct password, users with 2FA get a short-
    // lived pending token and must present a second factor before the real
    // session token exists. `stage` flips this screen between the two steps.
    // 'invite' = arriving via an activation link (#invite=<token>): the user
    // sets their own password and lands straight in the app.
    const inviteToken = (window.location.hash.match(/^#invite=(.+)$/) || [])[1] || null;
    const [stage, setStage]     = React.useState(inviteToken ? 'invite' : 'password');   // 'password' | '2fa' | 'invite'
    const [pending, setPending] = React.useState(null);          // { token, methods }
    const [code, setCode]       = React.useState('');

    // Invite state
    const [invite, setInvite]         = React.useState(null);    // { first_name, tenant_name, email }
    const [newPass, setNewPass]       = React.useState('');
    const [newPass2, setNewPass2]     = React.useState('');

    React.useEffect(() => {
        if (!inviteToken) return;
        api.getInvite(inviteToken)
            .then(setInvite)
            .catch(err => { setError(err.message); setStage('password'); });
    }, []);

    const finish = (data) => {
        // Drop the invite token from the URL so it never lingers in history.
        if (window.location.hash) history.replaceState(null, '', window.location.pathname);
        setToken(data.token); onLogin(data.user);
    };

    const handleActivate = async (e) => {
        e.preventDefault();
        if (newPass !== newPass2) { setError('Passwords don\'t match.'); return; }
        setLoading(true); setError('');
        try {
            finish(await api.redeemInvite(inviteToken, newPass));
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError('');
        try {
            const data = await api.login(form.email, form.password);
            if (data.requires_2fa) {
                setPending({ token: data.pending_token, methods: data.methods });
                setStage('2fa');
            } else {
                finish(data);
            }
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleCode = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError('');
        try {
            finish(await api.verify2faTotp(pending.token, code));
        } catch (err) {
            setError(err.message);
            // Pending tokens expire in 5 min / rate-limit at 10 tries — a 429
            // or expiry means the whole login restarts, so send them back.
            if (/sign in again|expired/i.test(err.message)) backToPassword();
        } finally {
            setLoading(false);
        }
    };

    const handleSecurityKey = async () => {
        setLoading(true);
        setError('');
        try {
            const options = await api.verify2faKeyOptions(pending.token);
            const assertion = await SimpleWebAuthnBrowser.startAuthentication({ optionsJSON: options });
            finish(await api.verify2faKey(pending.token, assertion));
        } catch (err) {
            // NotAllowedError = the user cancelled the browser prompt — not an error worth shouting about.
            setError(err.name === 'NotAllowedError' ? 'Security key prompt was cancelled.' : err.message);
        } finally {
            setLoading(false);
        }
    };

    const backToPassword = () => {
        setStage('password');
        setPending(null);
        setCode('');
    };

    return (
        <div className="login-screen">
            <div className="login-card">
                <div className="login-logo">
                    <img className="login-logo-mark" src="assets/logo.svg" alt="CRM logo" />
                    <h1>Clerical Repetition Machine</h1>
                    <p>{stage === '2fa' ? 'Two-factor verification'
                        : stage === 'invite' ? (invite ? `Welcome, ${invite.first_name}!` : 'Checking your invite…')
                        : 'Sign in to your account'}</p>
                </div>

                {error && (
                    <div className="login-error">
                        <i className="fas fa-exclamation-circle"></i>
                        {error}
                    </div>
                )}

                {stage === 'invite' && invite && (
                    <form onSubmit={handleActivate}>
                        <p style={{ fontSize: '0.875rem', marginBottom: '1rem', opacity: 0.85 }}>
                            You've been invited to <strong>{invite.tenant_name}</strong>.
                            Choose a password for <strong>{invite.email}</strong> and you're in.
                        </p>
                        <div className="form-group" style={{ marginBottom: '1rem' }}>
                            <label className="form-label">Choose a password</label>
                            <input type="password" className="form-input" value={newPass}
                                   onChange={(e) => setNewPass(e.target.value)}
                                   placeholder="At least 8 characters" minLength={8} required autoFocus />
                        </div>
                        <div className="form-group" style={{ marginBottom: '1.5rem' }}>
                            <label className="form-label">Repeat password</label>
                            <input type="password" className="form-input" value={newPass2}
                                   onChange={(e) => setNewPass2(e.target.value)}
                                   placeholder="Same again" minLength={8} required />
                        </div>
                        <button type="submit" className="login-submit" disabled={loading}>
                            {loading ? <><i className="fas fa-spinner fa-spin"></i> Activating…</> : 'Activate my account'}
                        </button>
                    </form>
                )}

                {stage === 'password' && (
                    <form onSubmit={handleSubmit}>
                        <div className="form-group" style={{ marginBottom: '1rem' }}>
                            <label className="form-label">Email</label>
                            <input
                                type="email"
                                className="form-input"
                                value={form.email}
                                onChange={(e) => setForm(p => ({ ...p, email: e.target.value }))}
                                placeholder="you@example.com"
                                required
                                autoFocus
                            />
                        </div>
                        <div className="form-group" style={{ marginBottom: '1.5rem' }}>
                            <label className="form-label">Password</label>
                            <input
                                type="password"
                                className="form-input"
                                value={form.password}
                                onChange={(e) => setForm(p => ({ ...p, password: e.target.value }))}
                                placeholder="••••••••"
                                required
                            />
                        </div>
                        <button type="submit" className="login-submit" disabled={loading}>
                            {loading ? <><i className="fas fa-spinner fa-spin"></i> Signing in…</> : 'Sign In'}
                        </button>
                    </form>
                )}

                {stage === '2fa' && (
                    <div>
                        {pending.methods.webauthn && (
                            <button type="button" className="login-submit" onClick={handleSecurityKey} disabled={loading} style={{ marginBottom: '1rem' }}>
                                <i className="fas fa-key" style={{ marginRight: '0.5rem' }}></i>
                                Use security key
                            </button>
                        )}
                        {pending.methods.totp && (
                            <form onSubmit={handleCode}>
                                <div className="form-group" style={{ marginBottom: '1rem' }}>
                                    <label className="form-label">Authenticator code</label>
                                    <input
                                        type="text"
                                        className="form-input"
                                        value={code}
                                        onChange={(e) => setCode(e.target.value)}
                                        placeholder="123 456 — or a backup code"
                                        autoComplete="one-time-code"
                                        inputMode="numeric"
                                        autoFocus={!pending.methods.webauthn}
                                        required
                                    />
                                </div>
                                <button type="submit" className="login-submit" disabled={loading}>
                                    {loading ? <><i className="fas fa-spinner fa-spin"></i> Verifying…</> : 'Verify'}
                                </button>
                            </form>
                        )}
                        <p className="settings-hint" style={{ textAlign: 'center', marginTop: '1rem' }}>
                            <a href="#" onClick={(e) => { e.preventDefault(); backToPassword(); }}>← Back to sign in</a>
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
};
