// admin-login.jsx — Operations console sign-in + activation (PRODUCTION)

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 [activateOtp, setActOtp]= React.useState(['', '', '', '', '', '']);
  const [newPass, setNewPass]   = React.useState('');
  const [showNew, setShowNew]   = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState('');
  const [successMsg, setSuccessMsg] = React.useState('');
  const [loading, setLoading]   = React.useState(false);
  const otpRefs    = React.useRef([]);
  const actOtpRefs = React.useRef([]);

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

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

  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.');
    } finally {
      setLoading(false);
    }
  };

  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(''));
  };

  const setActDigit = (i, v) => {
    const next = [...activateOtp]; next[i] = v.replace(/\D/g, '').slice(0, 1);
    setActOtp(next);
    if (next[i] && i < 5) actOtpRefs.current[i + 1]?.focus();
    if (next.every(d => d)) setStep('activate-pass');
  };

  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.');
      resetToLogin();
    } catch (err) {
      setErrorMsg(err.message || 'Activation failed. Check your code and try again.');
      setStep('activate');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      width: '100vw', height: '100vh', overflow: 'hidden',
      display: 'grid', gridTemplateColumns: window.innerWidth < 768 ? '1fr' : '1.05fr 1fr',
      fontFamily: 'Inter, sans-serif',
    }}>
      <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>

      <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%)' }}>
          {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>}

          {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', background: 'none', border: 'none', cursor: 'pointer' }}>
                    <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 <strong style={{ color: theme.ink }}>{inferredRole === 'admin' ? 'Admin' : 'Referral Partner (read-only)'}</strong> based on your email.</span>
              </div>
              <div style={{ marginTop: 18, textAlign: 'center' }}>
                <button type="button" onClick={() => { setErrorMsg(''); setSuccessMsg(''); setStep('activate'); }} style={{ fontSize: 12.5, color: theme.inkDim, background: 'none', border: 'none', cursor: 'pointer' }}>
                  First time here? <span style={{ color: theme.surface, fontWeight: 600 }}>Activate your account</span>
                </button>
              </div>
              <div style={{ marginTop: 20, 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, background: 'none', border: 'none', cursor: 'pointer' }}>
                <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 its 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>.</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', opacity: loading ? 0.6 : 1 }}/>
                ))}
              </div>
              {loading && <div style={{ marginTop: 16, fontSize: 13, color: theme.inkMute }}>Verifying...</div>}
              <div style={{ marginTop: 18 }}><button type="button" onClick={submit} style={{ fontSize: 12.5, color: theme.surface, fontWeight: 600, background: 'none', border: 'none', cursor: 'pointer' }}>Resend code</button></div>
            </div>
          )}

          {step === 'activate' && (
            <div>
              <button onClick={resetToLogin} style={{ fontSize: 12.5, color: theme.inkDim, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18, background: 'none', border: 'none', cursor: 'pointer' }}>
                <Icon name="chevL" size={13} color={theme.inkDim}/>Back to sign in
              </button>
              <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>Account activation</div>
              <h2 className="serif" style={{ fontSize: 30, fontWeight: 500, color: theme.ink, margin: '8px 0 8px', letterSpacing: -0.4, lineHeight: 1.1 }}>Activate your account.</h2>
              <div style={{ fontSize: 13.5, color: theme.inkDim, marginBottom: 24, lineHeight: 1.5 }}>Enter your email and the 6-digit code from your invitation email.</div>
              <AdminField label="Email"><input type="email" value={email} onChange={e => setEmail(e.target.value)} autoComplete="email" style={adminInputStyle(theme)}/></AdminField>
              <AdminField label="Activation code">
                <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
                  {activateOtp.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: theme.ink, background: theme.raised, border: '1.5px solid ' + (d ? theme.surface : theme.rule), borderRadius: 10, outline: 'none', fontFamily: 'Newsreader, serif' }}/>
                  ))}
                </div>
              </AdminField>
            </div>
          )}

          {step === 'activate-pass' && (
            <form onSubmit={submitActivate}>
              <button type="button" onClick={() => { setStep('activate'); setErrorMsg(''); }} style={{ fontSize: 12.5, color: theme.inkDim, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18, background: 'none', border: 'none', cursor: 'pointer' }}>
                <Icon name="chevL" size={13} color={theme.inkDim}/>Back
              </button>
              <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>Set password</div>
              <h2 className="serif" style={{ fontSize: 30, fontWeight: 500, color: theme.ink, margin: '8px 0 8px', letterSpacing: -0.4, lineHeight: 1.1 }}>Choose a password.</h2>
              <div style={{ fontSize: 13.5, color: theme.inkDim, marginBottom: 24 }}>Must be at least 12 characters.</div>
              <AdminField label="New password">
                <div style={{ position: 'relative' }}>
                  <input type={showNew ? 'text' : 'password'} value={newPass} onChange={e => setNewPass(e.target.value)} placeholder="12+ characters" required minLength={12} style={{ ...adminInputStyle(theme), 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={theme.inkMute}/>
                  </button>
                </div>
              </AdminField>
              <button type="submit" disabled={loading} style={{ width: '100%', padding: '13px', marginTop: 8, 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 ? 'Activating...' : 'Activate account'}
              </button>
            </form>
          )}

        </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' };
}

Object.assign(window, { AdminLogin });
