// ===== Login view: 兩步驟 email 驗證碼登入 =====
// Step 1: 輸入 email → 呼叫 /api/auth/request-code
// Step 2: 輸入 6 位驗證碼 → 呼叫 /api/auth/verify-code → session cookie 已寫入
// 成功後 onLogin(email) callback, 由 App 重新查 /api/auth/me 或直接切到主畫面

function LoginView({ onLogin }) {
  const [step, setStep] = React.useState('email');   // 'email' | 'code'
  const [email, setEmail] = React.useState('');
  const [code, setCode] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [msg, setMsg] = React.useState(null);        // {text, err, devCode}
  const emailRef = React.useRef();
  const codeRef = React.useRef();

  React.useEffect(() => {
    if (step === 'email' && emailRef.current) emailRef.current.focus();
    if (step === 'code' && codeRef.current) codeRef.current.focus();
  }, [step]);

  const requestCode = async () => {
    if (loading) return;
    const em = email.trim().toLowerCase();
    if (!em.includes('@')) { setMsg({ text: '請輸入有效的 Email', err: true }); return; }
    setLoading(true);
    setMsg(null);
    const r = await API.requestCode(em);
    setLoading(false);
    if (!r.ok) {
      setMsg({ text: r.data.error || '寄送失敗', err: true });
      return;
    }
    // 白名單外會回 ok:true, delivered:false — 一律往下走, 讓 UI 一致
    setStep('code');
    setMsg({
      text: r.data.delivered
        ? `驗證碼已寄至 ${em}，請於 10 分鐘內完成驗證`
        : (r.data._dev_code
            ? `[本機模式] 驗證碼：${r.data._dev_code}（未設 RESEND_API_KEY，模擬直接顯示）`
            : `若此信箱屬於白名單，將收到驗證碼`),
      err: false,
      devCode: r.data._dev_code,
    });
  };

  const verifyCode = async () => {
    if (loading) return;
    const c = code.trim();
    if (!/^\d{6}$/.test(c)) { setMsg({ text: '請輸入 6 位數驗證碼', err: true }); return; }
    setLoading(true);
    setMsg(null);
    const r = await API.verifyCode(email.trim().toLowerCase(), c);
    setLoading(false);
    if (!r.ok) {
      setMsg({ text: r.data.error || '驗證失敗', err: true });
      return;
    }
    onLogin && onLogin(r.data.email);
  };

  const back = () => { setStep('email'); setCode(''); setMsg(null); };

  return (
    <div className="login-wrap">
      <div className="login-card">
        <div className="login-brand">
          <img src="/static/recon/assets/logo-full.png" alt="JDi 脈動傳媒" />
        </div>
        <h1 className="login-title">對帳中心登入</h1>
        <p className="login-sub muted">
          {step === 'email' ? '請輸入你的 Email，我們會寄送 6 位數驗證碼' : `驗證碼已寄至 ${email}`}
        </p>

        {step === 'email' && (
          <div className="login-form">
            <label className="login-label">Email</label>
            <input ref={emailRef}
              type="email"
              autoComplete="email"
              inputMode="email"
              className="login-input"
              placeholder="you@example.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && requestCode()}
              disabled={loading} />
            <button className="btn primary login-btn" onClick={requestCode} disabled={loading}>
              {loading ? '寄送中…' : '寄送驗證碼'}
            </button>
          </div>
        )}

        {step === 'code' && (
          <div className="login-form">
            <label className="login-label">6 位數驗證碼</label>
            <input ref={codeRef}
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={6}
              className="login-input login-code-input num"
              placeholder="123456"
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
              onKeyDown={(e) => e.key === 'Enter' && verifyCode()}
              disabled={loading} />
            <div className="login-actions">
              <button className="btn login-back" onClick={back} disabled={loading}>返回</button>
              <button className="btn primary login-btn" onClick={verifyCode} disabled={loading}>
                {loading ? '驗證中…' : '登入'}
              </button>
            </div>
          </div>
        )}

        {msg && (
          <div className={'login-msg' + (msg.err ? ' err' : '')}>
            {msg.text}
          </div>
        )}

        <div className="login-footer muted">
          © JDi 脈動傳媒 · 對帳中心
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginView });
