// client-login.jsx — Real client sign-in (PRODUCTION)
// Flow: credentials → /api/auth/login → 2FA → /api/auth/verify-otp → home

function SignInScreen({ theme, onLogin, onVerifyOtp, onForgotPassword }) {
  const [step, setStep] = React.useState('credentials'); // 'credentials' | '2fa' | 'forgot'
  const [email, setEmail]       = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPass, setShowPass] = React.useState(false);
  const [remember, setRemember] = React.useState(true);
  const [busy, setBusy]         = React.useState(false);
  const [errMsg, setErrMsg]     = React.useState(null);

  const [otpId, setOtpId]       = React.useState(null);
  const [otp, setOtp]           = React.useState(['', '', '', '', '', '']);
  const [resentAt, setResent]   = React.useState(null);
  const otpRefs = React.useRef([]);

  const submitLogin = async (e) => {
    e?.preventDefault();
    if (busy) return;
    setErrMsg(null);
    if (!email || !password) { setErrMsg('Email and password required.'); return; }
    setBusy(true);
    try {
      const res = await onLogin(email, password);
      setOtpId(res.otp_id);
      setStep('2fa');
      setTimeout(() => otpRefs.current[0]?.focus(), 50);
      // Dev mode helper
      if (res.debug_code) console.info('[dev OTP]', res.debug_code);
    } catch (e) {
      setErrMsg(e.message || 'Sign in failed.');
    } finally {
      setBusy(false);
    }
  };

  const setOtpDigit = async (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)) {
      // Auto-submit when all 6 entered
      setBusy(true);
      setErrMsg(null);
      try {
        await onVerifyOtp(otpId, next.join(''));
      } catch (e) {
        setErrMsg(e.message || 'Invalid code.');
        setOtp(['','','','','','']);
        setTimeout(() => otpRefs.current[0]?.focus(), 30);
      } finally {
        setBusy(false);
      }
    }
  };

  const resendCode = async () => {
    if (busy) return;
    setBusy(true);
    try {
      const res = await onLogin(email, password);
      setOtpId(res.otp_id);
      setResent(Date.now());
      setOtp(['','','','','','']);
      otpRefs.current[0]?.focus();
    } catch (e) {
      setErrMsg(e.message || 'Could not resend.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{
      flex: 1,
      background: `linear-gradient(180deg, ${theme.surface} 0%, ${theme.gradEnd} 100%)`,
      color: theme.onSurface,
      display: 'flex', flexDirection: 'column',
      padding: 'max(env(safe-area-inset-top), 36px) 28px 32px',
      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>

      {/* wordmark */}
      <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>

      {step === 'credentials' && (
        <form onSubmit={submitLogin} style={{ marginTop: 36, 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.5, color: theme.onSurfaceDim, marginTop: 10, lineHeight: 1.5 }}>
            Sign in to your DebtLift member portal.
          </div>

          <label style={{ fontSize: 10, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase', color: theme.onSurfaceMute, marginTop: 28 }}>
            Email
          </label>
          <input
            type="email" value={email} onChange={e => setEmail(e.target.value)}
            autoComplete="email" autoCapitalize="off" autoCorrect="off" spellCheck={false}
            placeholder="you@business.com"
            style={authInputStyle(theme)}
          />

          <label style={{ fontSize: 10, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase', color: theme.onSurfaceMute, marginTop: 18 }}>
            Password
          </label>
          <div style={{ position: 'relative' }}>
            <input
              type={showPass ? 'text' : 'password'}
              value={password} onChange={e => setPassword(e.target.value)}
              autoComplete="current-password"
              placeholder="••••••••"
              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',
              color: theme.onSurfaceDim,
            }}>
              <Icon name={showPass ? 'eyeOff' : 'eye'} size={16} color={theme.onSurfaceDim}/>
            </button>
          </div>

          {errMsg && <ErrorBanner theme={theme} message={errMsg}/>}

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer' }}>
              <input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} style={{ accentColor: theme.accent.solid, width: 14, height: 14 }}/>
              <span style={{ fontSize: 12, color: theme.onSurfaceDim }}>Trust this device</span>
            </label>
            <button type="button" onClick={() => setStep('forgot')} style={{ fontSize: 12, color: theme.onSurfaceDim, fontWeight: 500, textDecoration: 'underline', textDecorationColor: 'rgba(255,255,255,0.4)' }}>
              Forgot password
            </button>
          </div>

          <button type="submit" disabled={busy} style={{
            marginTop: 28, padding: '14px',
            background: theme.onSurface, color: theme.surface,
            borderRadius: 12, fontSize: 14, fontWeight: 600,
            opacity: busy ? 0.6 : 1,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            {busy ? 'Signing in…' : 'Sign in'}
            {!busy && <Icon name="chevR" size={14} color={theme.surface} strokeWidth={2.2}/>}
          </button>

          <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>
      )}

      {step === '2fa' && (
        <div style={{ marginTop: 36, 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 }}>
            Confirm it's you.
          </h1>
          <div style={{ fontSize: 13.5, color: theme.onSurfaceDim, marginTop: 10, lineHeight: 1.5 }}>
            We sent a 6-digit code to your email on file.
          </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}
                disabled={busy}
                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>

          {errMsg && <ErrorBanner theme={theme} message={errMsg}/>}

          <div style={{ marginTop: 22, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <button onClick={() => setStep('credentials')} style={{ fontSize: 13, color: theme.onSurfaceDim, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="chevL" size={13} color={theme.onSurfaceDim}/>
              Back
            </button>
            <button onClick={resendCode} disabled={busy} style={{ fontSize: 12.5, color: theme.onSurfaceDim, fontWeight: 500 }}>
              {resentAt ? 'Code sent' : 'Resend code'}
            </button>
          </div>
        </div>
      )}

      {step === 'forgot' && <ForgotPasswordStep theme={theme} onBack={() => setStep('credentials')} onForgotPassword={onForgotPassword}/>}
    </div>
  );
}

// ─── Forgot password step ────────────────────────────────────
function ForgotPasswordStep({ theme, onBack, onForgotPassword }) {
  const [email, setEmail] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [errMsg, setErrMsg] = React.useState(null);

  const submit = async (e) => {
    e?.preventDefault();
    if (!email) return;
    setBusy(true); setErrMsg(null);
    try {
      await onForgotPassword(email);
      setSubmitted(true);
    } catch (e) {
      setErrMsg(e.message || 'Something went wrong.');
    } finally { setBusy(false); }
  };

  if (submitted) {
    return (
      <div style={{ marginTop: 36, display: 'flex', flexDirection: 'column', flex: 1 }}>
        <h1 className="serif" style={{ fontSize: 28, fontWeight: 400, color: theme.onSurface, margin: 0, letterSpacing: -0.5 }}>
          Check your email.
        </h1>
        <div style={{ fontSize: 13.5, color: theme.onSurfaceDim, marginTop: 12, lineHeight: 1.5 }}>
          If an account exists for <strong style={{ color: theme.onSurface }}>{email}</strong>, you'll receive a password reset code shortly.
        </div>
        <button onClick={onBack} style={{
          marginTop: 28, padding: '14px',
          background: theme.onSurface, color: theme.surface,
          borderRadius: 12, fontSize: 14, fontWeight: 600,
        }}>Back to sign in</button>
      </div>
    );
  }

  return (
    <form onSubmit={submit} style={{ marginTop: 36, display: 'flex', flexDirection: 'column', flex: 1 }}>
      <h1 className="serif" style={{ fontSize: 28, fontWeight: 400, color: theme.onSurface, margin: 0, letterSpacing: -0.5 }}>
        Reset your password.
      </h1>
      <div style={{ fontSize: 13.5, color: theme.onSurfaceDim, marginTop: 10, lineHeight: 1.5 }}>
        Enter your email and we'll send you a reset code.
      </div>

      <label style={{ fontSize: 10, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase', color: theme.onSurfaceMute, marginTop: 28 }}>
        Email
      </label>
      <input
        type="email" value={email} onChange={e => setEmail(e.target.value)}
        autoComplete="email" autoCapitalize="off" autoCorrect="off"
        placeholder="you@business.com" style={authInputStyle(theme)}
      />

      {errMsg && <ErrorBanner theme={theme} message={errMsg}/>}

      <button type="submit" disabled={busy} style={{
        marginTop: 28, padding: '14px',
        background: theme.onSurface, color: theme.surface,
        borderRadius: 12, fontSize: 14, fontWeight: 600, opacity: busy ? 0.6 : 1,
      }}>{busy ? 'Sending…' : 'Send reset code'}</button>

      <button type="button" onClick={onBack} style={{ marginTop: 16, fontSize: 13, color: theme.onSurfaceDim, fontWeight: 500 }}>
        ← Back
      </button>
    </form>
  );
}

function ErrorBanner({ theme, message }) {
  return (
    <div style={{
      marginTop: 14, padding: '10px 12px',
      background: 'rgba(220,80,80,0.16)', border: '1px solid rgba(220,80,80,0.4)',
      borderRadius: 9, color: '#FFCFCF',
      fontSize: 12.5, lineHeight: 1.4,
    }}>{message}</div>
  );
}

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,
  };
}

Object.assign(window, { SignInScreen });
