// admin-login.jsx — Operations console sign-in (admins + referral partners)

function AdminLogin({ theme, onSignedIn }) {
  const [step, setStep]         = React.useState('credentials');
  const [email, setEmail]       = React.useState('');
  const [password, setPass]     = React.useState('');
  const [showPass, setShowPass] = React.useState(false);
  const [otpId, setOtpId]       = React.useState(null);
  const [otp, setOtp]           = React.useState(['', '', '', '', '', '']);
  const [errorMsg, setErrorMsg] = React.useState('');
  const [loading, setLoading]   = React.useState(false);
  const otpRefs = React.useRef([]);

  const inferredRole = email.endsWith('@debtlift.co') ? 'admin' : 'referral';

  // Step 1 — submit email + password → get otp_id back
  const submit = async (e) => {
    e?.preventDefault();
    setErrorMsg('');
    setLoading(true);
    try {
      const res = await api.login(email, password);
      if (res?.otp_id) {
        setOtpId(res.otp_id);
        setStep('2fa');
        setTimeout(() => otpRefs.current[0]?.focus(), 100);
      }
    } catch (err) {
      setErrorMsg(err.message || 'Invalid credentials.');
      setStep('credentials');
    } finally {
      setLoading(false);
    }
  };

  // Step 2 — verify OTP → get session token → call onSignedIn
  const verifyOtp = async (code) => {
    if (!otpId) return;
    setLoading(true);
    setErrorMsg('');
    try {
      const res = await api.verifyOtp(otpId, code);
      if (res?.user) {
        onSignedIn(res.user.role);
      }
    } 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)) {
      verifyOtp(next.join(''));
    }
  };

  return (
    <div style={{
      width: '100vw', height: '100vh', overflow: 'hidden',
      display: 'grid', gridTemplateColumns: '1.05fr 1fr',
      fontFamily: 'Inter, sans-serif',
    }}>
      {/* LEFT — brand panel */}
      <div style={{
        position: 'relative', overflow: 'hidden',
        background: `linear-gradient(155deg, ${theme.surface2} 0%, ${theme.surface} 60%, ${theme.gradEnd} 115%)`,
        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: 12 }}>
          <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 }}>
            Operations Console
          </div>
          <h1 className="serif" style={{
            fontSize: 44, lineHeight: 1.1, fontWeight: 400,
            color: theme.onSurface, margin: 0, letterSpacing: -0.8,
          }}>
            The casefile, the lenders, and the client — open in one place.
          </h1>
          <div style={{ fontSize: 14.5, color: 'rgba(255,255,255,0.72)', marginTop: 22, lineHeight: 1.55 }}>
            Negotiate, sign, and post in seconds. Every action audited, every word optional to your client.
          </div>
        </div>

        <div style={{
          display: 'flex', gap: 24,
          fontSize: 11, color: 'rgba(255,255,255,0.55)',
          letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 500,
        }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <Icon name="shield" size={12} color="rgba(255,255,255,0.55)"/>
            SOC 2 Type II
          </span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <Icon name="lock" size={12} color="rgba(255,255,255,0.55)"/>
            AES-256 at rest
          </span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <Icon name="bank" size={12} color="rgba(255,255,255,0.55)"/>
            FINRA-aware audit log
          </span>
        </div>
      </div>

      {/* RIGHT — form */}
      <div style={{
        background: theme.canvas,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '40px', position: 'relative',
      }}>
        <div style={{
          position: 'absolute', top: 24, right: 28,
          fontSize: 12, color: theme.inkMute,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <span>Need help signing in?</span>
          <a href="mailto:support@debtlift.co" style={{ color: theme.surface, fontWeight: 600, textDecoration: 'none' }}>
            Contact support →
          </a>
        </div>

        <div style={{ width: 'min(420px, 100%)' }}>

          {/* Error message */}
          {errorMsg && (
            <div style={{
              marginBottom: 16, padding: '10px 14px',
              background: '#FEF2F2', border: '1px solid #FECACA',
              borderRadius: 8, fontSize: 13, color: '#DC2626',
            }}>
              {errorMsg}
            </div>
          )}

          {(step === 'credentials') && (
            <form onSubmit={submit}>
              <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
                Sign in
              </div>
              <h2 className="serif" style={{
                fontSize: 30, fontWeight: 500, color: theme.ink,
                margin: '8px 0 24px', letterSpacing: -0.4, lineHeight: 1.1,
              }}>
                Welcome back.
              </h2>

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

              <AdminField label="Password">
                <div style={{ position: 'relative' }}>
                  <input
                    type={showPass ? 'text' : 'password'}
                    value={password} onChange={e => setPass(e.target.value)}
                    autoComplete="current-password"
                    placeholder="••••••••" required
                    style={{ ...adminInputStyle(theme), 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',
                    color: theme.inkMute,
                  }}>
                    <Icon name={showPass ? 'eyeOff' : 'eye'} size={15} color={theme.inkMute}/>
                  </button>
                </div>
              </AdminField>

              <div style={{ marginBottom: 22, textAlign: 'right' }}>
                <a href="#" style={{ fontSize: 12.5, color: theme.surface, fontWeight: 600, textDecoration: 'none' }}>
                  Forgot password
                </a>
              </div>

              <button type="submit" disabled={loading} style={{
                width: '100%', padding: '13px',
                background: loading ? theme.inkMute : theme.surface,
                color: theme.onSurface,
                borderRadius: 10, fontSize: 14, fontWeight: 600,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                cursor: loading ? 'not-allowed' : 'pointer',
              }}>
                {loading ? 'Signing in…' : 'Continue'}
                {!loading && <Icon name="chevR" size={13} color={theme.onSurface} strokeWidth={2.2}/>}
              </button>

              <div style={{
                marginTop: 18, padding: '10px 12px',
                background: theme.canvas2, border: `1px solid ${theme.rule}`,
                borderRadius: 9, display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <Icon name="info" size={13} color={theme.inkMute}/>
                <span style={{ fontSize: 11.5, color: theme.inkMute }}>
                  Signing in as {inferredRole === 'admin'
                    ? <strong style={{ color: theme.ink }}>Admin</strong>
                    : <strong style={{ color: theme.ink }}>Referral Partner (read-only)</strong>}
                  {' '}based on your email.
                </span>
              </div>

              <div style={{
                marginTop: 32, paddingTop: 16, borderTop: `1px solid ${theme.rule}`,
                fontSize: 11, color: theme.inkMute, textAlign: 'center', letterSpacing: 0.3,
              }}>
                Protected by Cloudflare · TLS 1.3
              </div>
            </form>
          )}

          {step === '2fa' && (
            <div>
              <button onClick={() => { setStep('credentials'); setOtp(['','','','','','']); setErrorMsg(''); }} style={{
                fontSize: 12.5, color: theme.inkDim, fontWeight: 500,
                display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18,
              }}>
                <Icon name="chevL" size={13} color={theme.inkDim}/>
                Back
              </button>
              <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
                Two-factor
              </div>
              <h2 className="serif" style={{
                fontSize: 30, fontWeight: 500, color: theme.ink,
                margin: '8px 0 8px', letterSpacing: -0.4, lineHeight: 1.1,
              }}>
                Confirm it's you.
              </h2>
              <div style={{ fontSize: 13.5, color: theme.inkDim, marginBottom: 24 }}>
                We emailed a 6-digit code to <strong style={{ color: theme.ink }}>{email}</strong>. Enter it below.
              </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: theme.ink,
                      background: theme.raised,
                      border: `1.5px solid ${d ? theme.surface : theme.rule}`,
                      borderRadius: 10, outline: 'none',
                      fontFamily: 'Newsreader, serif',
                      transition: 'border-color 150ms',
                      opacity: loading ? 0.6 : 1,
                    }}
                  />
                ))}
              </div>

              {loading && (
                <div style={{ marginTop: 16, fontSize: 13, color: theme.inkMute }}>Verifying…</div>
              )}

              <div style={{ marginTop: 18, display: 'flex', gap: 14, fontSize: 12.5, color: theme.inkMute }}>
                <button type="button" onClick={submit} style={{ color: theme.surface, fontWeight: 600 }}>
                  Resend code
                </button>
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}

function AdminField({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <label style={{
        display: 'block', fontSize: 10.5, fontWeight: 600,
        letterSpacing: 1.4, textTransform: 'uppercase', color: '#7A88A6', marginBottom: 6,
      }}>
        {label}
      </label>
      {children}
    </div>
  );
}

function adminInputStyle(theme) {
  return {
    width: '100%', padding: '11px 13px',
    background: theme.raised, border: `1px solid ${theme.rule}`,
    borderRadius: 9, fontSize: 14, color: theme.ink,
    fontFamily: 'inherit', outline: 'none',
  };
}

function LoadingState({ theme, label }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '40px 0' }}>
      <div style={{
        width: 40, height: 40, borderRadius: 99,
        border: `2.5px solid ${theme.rule}`,
        borderTopColor: theme.surface,
        animation: 'spin 0.8s linear infinite',
      }}/>
      <div className="serif" style={{ fontSize: 17, color: theme.ink, fontWeight: 400, marginTop: 22, letterSpacing: -0.2 }}>
        {label}
      </div>
    </div>
  );
}

Object.assign(window, { AdminLogin });
