
// Desktop form — reuses same logic as mobile, just different container
function DesktopLoginForm({ theme, mode, step, setStep, setMode, email, setEmail, pass, setPass, showPass, setShowPass, otp, setOtpDigit, otpRefs, newPass, setNewPass, showNew, setShowNew, actOtp, setActDigit, actOtpRefs, loading, submitCredentials, submitForgot, submitSetPass, errorMsg, setErrorMsg, setSuccessMsg }) {
  const ink = '#0C2557';
  const inkMute = '#7A88A6';
  const border = 'rgba(30,100,214,0.15)';
  const surface = theme.surface;

  const inputStyle = {
    width: '100%', padding: '11px 13px',
    background: '#fff', border: '1px solid ' + border,
    borderRadius: 9, fontSize: 14, color: ink,
    fontFamily: 'inherit', outline: 'none',
  };
  const labelStyle = {
    display: 'block', fontSize: 10.5, fontWeight: 600,
    letterSpacing: 1.4, textTransform: 'uppercase', color: inkMute, marginBottom: 6,
  };

  if (mode === 'signin' && step === 'credentials') return (
    <div>
      <div style={{ fontSize: 11, color: inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>Sign in</div>
      <h2 className="serif" style={{ fontSize: 30, fontWeight: 500, color: ink, margin: '8px 0 24px', letterSpacing: -0.4, lineHeight: 1.1 }}>Welcome back.</h2>
      <div style={{ marginBottom: 14 }}>
        <label style={labelStyle}>Email</label>
        <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" style={inputStyle}/>
      </div>
      <div style={{ marginBottom: 8 }}>
        <label style={labelStyle}>Password</label>
        <div style={{ position: 'relative' }}>
          <input type={showPass ? 'text' : 'password'} value={pass} onChange={e => setPass(e.target.value)} placeholder="••••••••" style={{ ...inputStyle, paddingRight: 44 }}/>
          <button type="button" onClick={() => setShowPass(!showPass)} style={{ position: 'absolute', right: 4, top: 4, width: 36, height: 36, borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'none', border: 'none', cursor: 'pointer' }}>
            <Icon name={showPass ? 'eyeOff' : 'eye'} size={15} color={inkMute}/>
          </button>
        </div>
      </div>
      <div style={{ textAlign: 'right', marginBottom: 20 }}>
        <button onClick={() => { setMode('forgot'); }} style={{ fontSize: 12.5, color: surface, fontWeight: 600, background: 'none', border: 'none', cursor: 'pointer' }}>Forgot password</button>
      </div>
      <button onClick={submitCredentials} disabled={loading} style={{ width: '100%', padding: '13px', background: loading ? inkMute : surface, color: '#fff', borderRadius: 10, fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, cursor: loading ? 'not-allowed' : 'pointer', border: 'none' }}>
        {loading ? 'Signing in…' : 'Sign in'}
        {!loading && <Icon name="chevR" size={13} color="#fff" strokeWidth={2.2}/>}
      </button>
      <div style={{ marginTop: 18, textAlign: 'center' }}>
        <button onClick={() => { setMode('activate'); setStep('credentials'); setErrorMsg(''); setSuccessMsg(''); }} style={{ fontSize: 12.5, color: inkMute, background: 'none', border: 'none', cursor: 'pointer' }}>
          First time here? <span style={{ color: surface, fontWeight: 600 }}>Activate your account</span>
        </button>
      </div>
      <div style={{ marginTop: 20, paddingTop: 16, borderTop: '1px solid ' + border, fontSize: 11, color: inkMute, textAlign: 'center', letterSpacing: 0.3 }}>Encrypted end-to-end · TLS 1.3</div>
    </div>
  );

  if (mode === 'signin' && step === 'otp') return (
    <div>
      <button onClick={() => setStep('credentials')} style={{ fontSize: 12.5, color: inkMute, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18, background: 'none', border: 'none', cursor: 'pointer' }}>
        <Icon name="chevL" size={13} color={inkMute}/>Back
      </button>
      <div style={{ fontSize: 11, color: inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>Verification</div>
      <h2 className="serif" style={{ fontSize: 30, fontWeight: 500, color: ink, margin: '8px 0 8px', letterSpacing: -0.4 }}>Check your email.</h2>
      <div style={{ fontSize: 13.5, color: inkMute, marginBottom: 24 }}>We sent a 6-digit code to <strong style={{ color: ink }}>{email}</strong>.</div>
      <div style={{ display: 'flex', gap: 10 }}>
        {otp.map((d, i) => (
          <input key={i} ref={el => otpRefs.current[i] = el} value={d} onChange={e => setOtpDigit(i, e.target.value)} onKeyDown={e => { if (e.key === 'Backspace' && !d && i > 0) otpRefs.current[i-1]?.focus(); }} inputMode="numeric" maxLength={1} className="tnum" disabled={loading}
            style={{ width: 52, height: 60, textAlign: 'center', fontSize: 26, fontWeight: 500, color: ink, background: '#fff', border: '1.5px solid ' + (d ? surface : border), borderRadius: 10, outline: 'none', fontFamily: 'Newsreader, serif', opacity: loading ? 0.6 : 1 }}/>
        ))}
      </div>
    </div>
  );

  if (mode === 'activate') return (
    <div>
      <button onClick={() => { setMode('signin'); setStep('credentials'); setErrorMsg(''); }} style={{ fontSize: 12.5, color: inkMute, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18, background: 'none', border: 'none', cursor: 'pointer' }}>
        <Icon name="chevL" size={13} color={inkMute}/>Back to sign in
      </button>
      <div style={{ fontSize: 11, color: inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>Activate account</div>
      <h2 className="serif" style={{ fontSize: 30, fontWeight: 500, color: ink, margin: '8px 0 8px', letterSpacing: -0.4 }}>
        {step === 'credentials' ? 'Enter your code.' : 'Set your password.'}
      </h2>
      {step === 'credentials' && (
        <>
          <div style={{ fontSize: 13.5, color: inkMute, marginBottom: 20, lineHeight: 1.5 }}>Enter your email and the activation code from your welcome email.</div>
          <div style={{ marginBottom: 14 }}>
            <label style={labelStyle}>Email</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} style={inputStyle}/>
          </div>
          <div style={{ marginBottom: 6 }}>
            <label style={labelStyle}>Activation code</label>
            <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
              {actOtp.map((d, i) => (
                <input key={i} ref={el => actOtpRefs.current[i] = el} value={d} onChange={e => setActDigit(i, e.target.value)} onKeyDown={e => { if (e.key === 'Backspace' && !d && i > 0) actOtpRefs.current[i-1]?.focus(); }} inputMode="numeric" maxLength={1} className="tnum"
                  style={{ width: 52, height: 60, textAlign: 'center', fontSize: 26, fontWeight: 500, color: ink, background: '#fff', border: '1.5px solid ' + (d ? surface : border), borderRadius: 10, outline: 'none', fontFamily: 'Newsreader, serif' }}/>
              ))}
            </div>
          </div>
        </>
      )}
      {step === 'setpass' && (
        <>
          <div style={{ fontSize: 13.5, color: inkMute, marginBottom: 20 }}>Must be at least 12 characters.</div>
          <div style={{ marginBottom: 14 }}>
            <label style={labelStyle}>New password</label>
            <div style={{ position: 'relative' }}>
              <input type={showNew ? 'text' : 'password'} value={newPass} onChange={e => setNewPass(e.target.value)} placeholder="12+ characters" style={{ ...inputStyle, paddingRight: 44 }}/>
              <button type="button" onClick={() => setShowNew(!showNew)} style={{ position: 'absolute', right: 4, top: 4, width: 36, height: 36, borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'none', border: 'none', cursor: 'pointer' }}>
                <Icon name={showNew ? 'eyeOff' : 'eye'} size={15} color={inkMute}/>
              </button>
            </div>
          </div>
          <button onClick={submitSetPass} disabled={loading} style={{ width: '100%', padding: '13px', background: loading ? inkMute : surface, color: '#fff', borderRadius: 10, fontSize: 14, fontWeight: 600, border: 'none', cursor: loading ? 'not-allowed' : 'pointer' }}>
            {loading ? 'Activating…' : 'Activate account'}
          </button>
        </>
      )}
    </div>
  );

  if (mode === 'forgot') return (
    <div>
      <button onClick={() => setMode('signin')} style={{ fontSize: 12.5, color: inkMute, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18, background: 'none', border: 'none', cursor: 'pointer' }}>
        <Icon name="chevL" size={13} color={inkMute}/>Back
      </button>
      <div style={{ fontSize: 11, color: inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>Reset password</div>
      <h2 className="serif" style={{ fontSize: 30, fontWeight: 500, color: ink, margin: '8px 0 8px', letterSpacing: -0.4 }}>Forgot your password?</h2>
      <div style={{ fontSize: 13.5, color: inkMute, marginBottom: 20 }}>Enter your email and we'll send a reset code.</div>
      <div style={{ marginBottom: 16 }}>
        <label style={labelStyle}>Email</label>
        <input type="email" value={email} onChange={e => setEmail(e.target.value)} style={inputStyle}/>
      </div>
      <button onClick={submitForgot} disabled={loading} style={{ width: '100%', padding: '13px', background: loading ? inkMute : surface, color: '#fff', borderRadius: 10, fontSize: 14, fontWeight: 600, border: 'none', cursor: loading ? 'not-allowed' : 'pointer' }}>
        {loading ? 'Sending…' : 'Send reset code'}
      </button>
    </div>
  );

  // Fallback — show signin form
  return (
    <div>
      <div style={{ fontSize: 11, color: '#7A88A6', fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>Sign in</div>
      <h2 className="serif" style={{ fontSize: 30, fontWeight: 500, color: '#0C2557', margin: '8px 0 24px', letterSpacing: -0.4, lineHeight: 1.1 }}>Welcome back.</h2>
      <div style={{ marginBottom: 14 }}>
        <label style={{ display: 'block', fontSize: 10.5, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: '#7A88A6', marginBottom: 6 }}>Email</label>
        <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" style={{ width: '100%', padding: '11px 13px', background: '#fff', border: '1px solid rgba(30,100,214,0.15)', borderRadius: 9, fontSize: 14, color: '#0C2557', fontFamily: 'inherit', outline: 'none' }}/>
      </div>
      <div style={{ marginBottom: 20 }}>
        <label style={{ display: 'block', fontSize: 10.5, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: '#7A88A6', marginBottom: 6 }}>Password</label>
        <input type="password" value={pass} onChange={e => setPass(e.target.value)} placeholder="••••••••" style={{ width: '100%', padding: '11px 13px', background: '#fff', border: '1px solid rgba(30,100,214,0.15)', borderRadius: 9, fontSize: 14, color: '#0C2557', fontFamily: 'inherit', outline: 'none' }}/>
      </div>
      <button onClick={submitCredentials} disabled={loading} style={{ width: '100%', padding: '13px', background: surface, color: '#fff', borderRadius: 10, fontSize: 14, fontWeight: 600, border: 'none', cursor: 'pointer' }}>
        {loading ? 'Signing in…' : 'Sign in'}
      </button>
      <div style={{ marginTop: 18, textAlign: 'center' }}>
        <button onClick={() => { setMode('activate'); setStep('credentials'); }} style={{ fontSize: 12.5, color: '#7A88A6', background: 'none', border: 'none', cursor: 'pointer' }}>
          First time here? <span style={{ color: surface, fontWeight: 600 }}>Activate your account</span>
        </button>
      </div>
      <div style={{ marginTop: 16, fontSize: 11, color: '#7A88A6', textAlign: 'center' }}>mode: {mode} step: {step}</div>
    </div>
  );
}

// client-login.jsx — Production client sign-in + account activation

function SignInScreen({ theme, onLogin, onVerifyOtp, onForgotPassword }) {
  const [mode, setMode]         = React.useState('signin');   // 'signin' | 'activate' | 'forgot'
  const [step, setStep]         = React.useState('credentials'); // 'credentials' | 'otp' | 'setpass'
  const [email, setEmail]       = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPass, setShowPass] = React.useState(false);
  const [otpId, setOtpId]       = React.useState(null);
  const [otp, setOtp]           = React.useState(['', '', '', '', '', '']);
  const [newPass, setNewPass]   = React.useState('');
  const [showNew, setShowNew]   = React.useState(false);
  const [loading, setLoading]   = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState('');
  const [successMsg, setSuccessMsg] = React.useState('');
  const otpRefs = React.useRef([]);

  const reset = () => {
    setStep('credentials');
    setOtp(['', '', '', '', '', '']);
    setOtpId(null);
    setErrorMsg('');
    setSuccessMsg('');
    setLoading(false);
  };

  // ── SIGN IN ──────────────────────────────────────────────────
  const submitSignIn = async (e) => {
    e?.preventDefault();
    setErrorMsg('');
    setLoading(true);
    try {
      const res = await onLogin(email, password);
      if (res?.otp_id) {
        setOtpId(res.otp_id);
        setStep('otp');
        setTimeout(() => otpRefs.current[0]?.focus(), 100);
      }
    } catch (err) {
      setErrorMsg(err.message || 'Invalid email or password.');
    } finally {
      setLoading(false);
    }
  };

  const submitOtp = async (code) => {
    setLoading(true);
    setErrorMsg('');
    try {
      await onVerifyOtp(otpId, code);
      // onVerifyOtp saves token + triggers re-render in app.jsx
    } catch (err) {
      setErrorMsg(err.message || 'Invalid code. Try again.');
      setOtp(['', '', '', '', '', '']);
      setTimeout(() => otpRefs.current[0]?.focus(), 100);
    } finally {
      setLoading(false);
    }
  };

  const setOtpDigit = (i, v) => {
    const next = [...otp];
    next[i] = v.replace(/\D/g, '').slice(0, 1);
    setOtp(next);
    if (next[i] && i < 5) otpRefs.current[i + 1]?.focus();
    if (next.every(d => d)) submitOtp(next.join(''));
  };

  // ── ACTIVATE ─────────────────────────────────────────────────
  const [activateOtp, setActivateOtp] = React.useState(['', '', '', '', '', '']);
  const activateOtpRefs = React.useRef([]);

  const submitActivateCode = (code) => {
    setStep('setpass');
    setErrorMsg('');
  };

  const setActivateDigit = (i, v) => {
    const next = [...activateOtp];
    next[i] = v.replace(/\D/g, '').slice(0, 1);
    setActivateOtp(next);
    if (next[i] && i < 5) activateOtpRefs.current[i + 1]?.focus();
    if (next.every(d => d)) submitActivateCode(next.join(''));
  };

  const submitActivate = async (e) => {
    e?.preventDefault();
    if (newPass.length < 12) {
      setErrorMsg('Password must be at least 12 characters.');
      return;
    }
    setLoading(true);
    setErrorMsg('');
    try {
      await api.activateByEmail(email, activateOtp.join(''), newPass);
      setSuccessMsg('Account activated! Sign in with your new password.');
      setMode('signin');
      reset();
    } catch (err) {
      setErrorMsg(err.message || 'Activation failed. Check your code and try again.');
      setStep('credentials');
    } finally {
      setLoading(false);
    }
  };

  // ── FORGOT PASSWORD ───────────────────────────────────────────
  const submitForgot = async (e) => {
    e?.preventDefault();
    setLoading(true);
    setErrorMsg('');
    try {
      await onForgotPassword(email);
      setSuccessMsg('If that email exists, a reset code is on its way.');
    } catch (err) {
      setErrorMsg(err.message || 'Something went wrong.');
    } finally {
      setLoading(false);
    }
  };

  // ── SHARED LAYOUT ─────────────────────────────────────────────
  const isDesktop = window.innerWidth >= 768;

  if (isDesktop) {
    return (
      <div style={{ width: '100vw', height: '100vh', overflow: 'hidden', display: 'grid', gridTemplateColumns: '1.1fr 1fr', fontFamily: 'Inter, sans-serif' }}>
        {/* Left brand panel */}
        <div style={{
          position: 'relative', overflow: 'hidden',
          background: `linear-gradient(155deg, ${theme.surface} 0%, ${theme.gradEnd || theme.surface} 100%)`,
          color: theme.onSurface, padding: '48px 56px',
          display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        }}>
          <div aria-hidden style={{ position: 'absolute', right: -80, bottom: -90, fontFamily: 'Newsreader, serif', fontSize: 540, lineHeight: 1, fontWeight: 400, color: theme.onSurface, opacity: 0.045, letterSpacing: -20 }}>dl</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10 }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, marginBottom: 4 }}>
              <span style={{ width: 5, height: 14, background: 'rgba(255,255,255,0.5)', borderRadius: 2 }}/>
              <span style={{ width: 5, height: 22, background: 'rgba(255,255,255,0.78)', borderRadius: 2 }}/>
              <span style={{ width: 5, height: 32, background: '#FFFFFF', borderRadius: 2 }}/>
            </div>
            <span className="serif" style={{ fontSize: 34, fontWeight: 500, color: theme.onSurface, letterSpacing: -0.6, lineHeight: 1 }}>debtlift</span>
          </div>
          <div style={{ maxWidth: 460, position: 'relative' }}>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', fontWeight: 600, letterSpacing: 2, textTransform: 'uppercase', marginBottom: 18 }}>Member Portal</div>
            <h1 className="serif" style={{ fontSize: 44, lineHeight: 1.1, fontWeight: 400, color: theme.onSurface, margin: 0, letterSpacing: -0.8 }}>Your settlement, your progress, in one place.</h1>
            <div style={{ fontSize: 14.5, color: 'rgba(255,255,255,0.72)', marginTop: 22, lineHeight: 1.55 }}>Track your lenders, view offers, and stay on top of your debt relief journey.</div>
          </div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)', letterSpacing: 0.3 }}>DebtLift · Settling business debt with dignity</div>
        </div>
        {/* Right form panel */}
        <div style={{ background: '#F4F7FD', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px' }}>
          <div style={{ width: 'min(400px, 100%)' }}>
            {errorMsg && <div style={{ marginBottom: 16, padding: '10px 14px', background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, fontSize: 13, color: '#DC2626' }}>{errorMsg}</div>}
            {successMsg && <div style={{ marginBottom: 16, padding: '10px 14px', background: '#DBE7DC', border: '1px solid #BBD6BC', borderRadius: 8, fontSize: 13, color: '#173C2C' }}>{successMsg}</div>}
            <DesktopLoginForm theme={theme} mode={mode} step={step} setStep={setStep} setMode={setMode} email={email} setEmail={setEmail} pass={password} setPass={setPassword} showPass={showPass} setShowPass={setShowPass} otp={otp} setOtpDigit={setOtpDigit} otpRefs={otpRefs} newPass={newPass} setNewPass={setNewPass} showNew={showNew} setShowNew={setShowNew} actOtp={activateOtp} setActDigit={setActivateDigit} actOtpRefs={activateOtpRefs} loading={loading} submitCredentials={submitSignIn} submitForgot={submitForgot} submitSetPass={submitActivate} errorMsg={errorMsg} setErrorMsg={setErrorMsg} setSuccessMsg={setSuccessMsg}/>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{
      minHeight: '100dvh',
      background: `linear-gradient(180deg, ${theme.surface} 0%, ${theme.gradEnd || theme.surface} 100%)`,
      color: theme.onSurface,
      display: 'flex', flexDirection: 'column',
      padding: '60px 28px 36px',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* engraved monogram */}
      <div aria-hidden style={{
        position: 'absolute', top: -50, right: -40,
        fontFamily: 'Newsreader, serif', fontSize: 240, lineHeight: 1, fontWeight: 400,
        color: theme.onSurface, opacity: 0.05, letterSpacing: -8, pointerEvents: 'none',
      }}>dl</div>

      {/* Brand */}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 9 }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2.5, marginBottom: 3 }}>
          <span style={{ width: 3.5, height: 10, background: 'rgba(245,240,230,0.5)', borderRadius: 1.5 }}/>
          <span style={{ width: 3.5, height: 15, background: 'rgba(245,240,230,0.78)', borderRadius: 1.5 }}/>
          <span style={{ width: 3.5, height: 21, background: theme.onSurface, borderRadius: 1.5 }}/>
        </div>
        <span className="serif" style={{ fontSize: 24, fontWeight: 500, color: theme.onSurface, letterSpacing: -0.4, lineHeight: 1 }}>
          debtlift
        </span>
      </div>

      {/* Error / success */}
      {errorMsg && (
        <div style={{
          marginTop: 16, padding: '10px 14px',
          background: 'rgba(220,38,38,0.15)', border: '1px solid rgba(220,38,38,0.3)',
          borderRadius: 10, fontSize: 13, color: '#FCA5A5',
        }}>{errorMsg}</div>
      )}
      {successMsg && (
        <div style={{
          marginTop: 16, padding: '10px 14px',
          background: 'rgba(47,106,79,0.2)', border: '1px solid rgba(47,106,79,0.4)',
          borderRadius: 10, fontSize: 13, color: '#86EFAC',
        }}>{successMsg}</div>
      )}

      {/* ── SIGN IN: credentials ── */}
      {mode === 'signin' && step === 'credentials' && (
        <form onSubmit={submitSignIn} style={{ marginTop: 32, display: 'flex', flexDirection: 'column', flex: 1 }}>
          <h1 className="serif" style={{ fontSize: 30, fontWeight: 400, color: theme.onSurface, margin: 0, letterSpacing: -0.6, lineHeight: 1.1 }}>
            Welcome back.
          </h1>
          <div style={{ fontSize: 13, color: theme.onSurfaceDim, marginTop: 8, lineHeight: 1.5 }}>
            Sign in to your DebtLift member portal.
          </div>

          <label style={labelStyle(theme)}>Email</label>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)}
            autoComplete="email" required style={authInputStyle(theme)}/>

          <label style={labelStyle(theme)}>Password</label>
          <div style={{ position: 'relative' }}>
            <input
              type={showPass ? 'text' : 'password'}
              value={password} onChange={e => setPassword(e.target.value)}
              autoComplete="current-password" placeholder="••••••••" required
              style={{ ...authInputStyle(theme), paddingRight: 44 }}
            />
            <button type="button" onClick={() => setShowPass(!showPass)} style={{
              position: 'absolute', right: 6, top: 6,
              width: 34, height: 34, borderRadius: 8,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name={showPass ? 'eyeOff' : 'eye'} size={16} color={theme.onSurfaceDim}/>
            </button>
          </div>

          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 10 }}>
            <button type="button" onClick={() => { setMode('forgot'); setErrorMsg(''); setSuccessMsg(''); }}
              style={{ fontSize: 12, color: theme.onSurfaceDim, fontWeight: 500, textDecoration: 'underline', textDecorationColor: 'rgba(255,255,255,0.3)' }}>
              Forgot password
            </button>
          </div>

          <button type="submit" disabled={loading} style={primaryBtn(theme, loading)}>
            {loading ? 'Signing in…' : 'Sign in'}
            {!loading && <Icon name="chevR" size={14} color={theme.surface} strokeWidth={2.2}/>}
          </button>

          <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(245,240,230,0.12)', textAlign: 'center' }}>
            <button type="button" onClick={() => { setMode('activate'); setErrorMsg(''); setSuccessMsg(''); reset(); }}
              style={{ fontSize: 12.5, color: theme.onSurfaceDim }}>
              First time here? <span style={{ color: theme.onSurface, fontWeight: 600 }}>Activate your account</span>
            </button>
          </div>

          <div style={{ marginTop: 'auto', paddingTop: 24, textAlign: 'center', fontSize: 10, color: theme.onSurfaceMute, letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 500, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
            <Icon name="lock" size={10} color={theme.onSurfaceMute}/>
            Encrypted end-to-end · TLS 1.3
          </div>
        </form>
      )}

      {/* ── SIGN IN: OTP ── */}
      {mode === 'signin' && step === 'otp' && (
        <div style={{ marginTop: 32, display: 'flex', flexDirection: 'column', flex: 1 }}>
          <button onClick={() => { setStep('credentials'); setOtp(['','','','','','']); setErrorMsg(''); }}
            style={{ fontSize: 12.5, color: theme.onSurfaceDim, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18 }}>
            <Icon name="chevL" size={13} color={theme.onSurfaceDim}/>
            Back
          </button>
          <h1 className="serif" style={{ fontSize: 28, fontWeight: 400, color: theme.onSurface, margin: 0, letterSpacing: -0.5, lineHeight: 1.1 }}>
            Confirm it's you.
          </h1>
          <div style={{ fontSize: 13, color: theme.onSurfaceDim, marginTop: 10, lineHeight: 1.5 }}>
            We emailed a 6-digit code to <strong style={{ color: theme.onSurface }}>{email}</strong>.
          </div>

          <div style={{ display: 'flex', gap: 8, marginTop: 28, justifyContent: 'space-between' }}>
            {otp.map((d, i) => (
              <input key={i} ref={el => otpRefs.current[i] = el}
                value={d} onChange={e => setOtpDigit(i, e.target.value)}
                onKeyDown={e => { if (e.key === 'Backspace' && !d && i > 0) otpRefs.current[i - 1]?.focus(); }}
                inputMode="numeric" maxLength={1} className="tnum"
                disabled={loading}
                style={{
                  width: 46, height: 56, textAlign: 'center', fontSize: 24, fontWeight: 600,
                  color: theme.onSurface, background: 'rgba(245,240,230,0.08)',
                  border: `1.5px solid ${d ? theme.onSurface : 'rgba(245,240,230,0.25)'}`,
                  borderRadius: 12, outline: 'none', fontFamily: 'Newsreader, serif',
                  opacity: loading ? 0.6 : 1,
                }}
              />
            ))}
          </div>
          {loading && <div style={{ marginTop: 14, fontSize: 13, color: theme.onSurfaceDim }}>Verifying…</div>}
        </div>
      )}

      {/* ── ACTIVATE: enter email + code ── */}
      {mode === 'activate' && step === 'credentials' && (
        <div style={{ marginTop: 32, display: 'flex', flexDirection: 'column', flex: 1 }}>
          <button onClick={() => { setMode('signin'); reset(); }}
            style={{ fontSize: 12.5, color: theme.onSurfaceDim, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18 }}>
            <Icon name="chevL" size={13} color={theme.onSurfaceDim}/>
            Back to sign in
          </button>
          <h1 className="serif" style={{ fontSize: 28, fontWeight: 400, color: theme.onSurface, margin: 0, letterSpacing: -0.5, lineHeight: 1.1 }}>
            Activate your account.
          </h1>
          <div style={{ fontSize: 13, color: theme.onSurfaceDim, marginTop: 10, lineHeight: 1.5 }}>
            Enter your email and the 6-digit code from your invitation email.
          </div>

          <label style={labelStyle(theme)}>Email</label>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)}
            autoComplete="email" required style={authInputStyle(theme)}/>

          <label style={{ ...labelStyle(theme), marginTop: 18 }}>Activation code</label>
          <div style={{ display: 'flex', gap: 8, marginTop: 8, justifyContent: 'space-between' }}>
            {activateOtp.map((d, i) => (
              <input key={i} ref={el => activateOtpRefs.current[i] = el}
                value={d} onChange={e => setActivateDigit(i, e.target.value)}
                onKeyDown={e => { if (e.key === 'Backspace' && !d && i > 0) activateOtpRefs.current[i - 1]?.focus(); }}
                inputMode="numeric" maxLength={1} className="tnum"
                style={{
                  width: 46, height: 56, textAlign: 'center', fontSize: 24, fontWeight: 600,
                  color: theme.onSurface, background: 'rgba(245,240,230,0.08)',
                  border: `1.5px solid ${d ? theme.onSurface : 'rgba(245,240,230,0.25)'}`,
                  borderRadius: 12, outline: 'none', fontFamily: 'Newsreader, serif',
                }}
              />
            ))}
          </div>
        </div>
      )}

      {/* ── ACTIVATE: set password ── */}
      {mode === 'activate' && step === 'setpass' && (
        <form onSubmit={submitActivate} style={{ marginTop: 32, display: 'flex', flexDirection: 'column', flex: 1 }}>
          <h1 className="serif" style={{ fontSize: 28, fontWeight: 400, color: theme.onSurface, margin: 0, letterSpacing: -0.5, lineHeight: 1.1 }}>
            Set your password.
          </h1>
          <div style={{ fontSize: 13, color: theme.onSurfaceDim, marginTop: 10, lineHeight: 1.5 }}>
            Choose a strong password for your account.
          </div>

          <label style={labelStyle(theme)}>New password</label>
          <div style={{ position: 'relative' }}>
            <input
              type={showNew ? 'text' : 'password'}
              value={newPass} onChange={e => setNewPass(e.target.value)}
              placeholder="12+ characters" required minLength={12}
              style={{ ...authInputStyle(theme), paddingRight: 44 }}
            />
            <button type="button" onClick={() => setShowNew(!showNew)} style={{
              position: 'absolute', right: 6, top: 6,
              width: 34, height: 34, borderRadius: 8,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name={showNew ? 'eyeOff' : 'eye'} size={16} color={theme.onSurfaceDim}/>
            </button>
          </div>

          <button type="submit" disabled={loading} style={{ ...primaryBtn(theme, loading), marginTop: 24 }}>
            {loading ? 'Activating…' : 'Activate account'}
          </button>
        </form>
      )}

      {/* ── FORGOT PASSWORD ── */}
      {mode === 'forgot' && (
        <form onSubmit={submitForgot} style={{ marginTop: 32, display: 'flex', flexDirection: 'column', flex: 1 }}>
          <button type="button" onClick={() => { setMode('signin'); reset(); }}
            style={{ fontSize: 12.5, color: theme.onSurfaceDim, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18 }}>
            <Icon name="chevL" size={13} color={theme.onSurfaceDim}/>
            Back to sign in
          </button>
          <h1 className="serif" style={{ fontSize: 28, fontWeight: 400, color: theme.onSurface, margin: 0, letterSpacing: -0.5, lineHeight: 1.1 }}>
            Reset your password.
          </h1>
          <div style={{ fontSize: 13, color: theme.onSurfaceDim, marginTop: 10, lineHeight: 1.5 }}>
            Enter your email and we'll send a reset code.
          </div>

          <label style={labelStyle(theme)}>Email</label>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)}
            autoComplete="email" required style={authInputStyle(theme)}/>

          <button type="submit" disabled={loading} style={{ ...primaryBtn(theme, loading), marginTop: 24 }}>
            {loading ? 'Sending…' : 'Send reset code'}
          </button>
        </form>
      )}
    </div>
  );
}

function labelStyle(theme) {
  return {
    fontSize: 10, fontWeight: 600, letterSpacing: 1.6,
    textTransform: 'uppercase', color: theme.onSurfaceMute, marginTop: 18,
  };
}

function authInputStyle(theme) {
  return {
    marginTop: 8, width: '100%', padding: '13px 14px',
    background: 'rgba(245,240,230,0.08)',
    border: '1.5px solid rgba(245,240,230,0.25)',
    borderRadius: 12, fontSize: 15, color: theme.onSurface,
    fontFamily: 'inherit', outline: 'none', caretColor: theme.onSurface,
  };
}

function primaryBtn(theme, loading) {
  return {
    marginTop: 28, padding: '14px',
    background: loading ? 'rgba(245,240,230,0.3)' : theme.onSurface,
    color: theme.surface, borderRadius: 12, fontSize: 14, fontWeight: 600,
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    cursor: loading ? 'not-allowed' : 'pointer',
  };
}

Object.assign(window, { SignInScreen });
