// Login.jsx — Email + password sign-in. After a successful sign-in,
// App.jsx (via firebaseApi.auth.onAuth) maps the email to identity "A"/"B"
// and routes to the main UI. Non-whitelisted accounts are signed out
// immediately here (defense line 1, front-end side).
const { useState } = React;

function LoginScreen({ accent }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  async function handleSubmit(e) {
    if (e) e.preventDefault();
    if (busy) return;
    setError("");
    setBusy(true);
    try {
      const api = window.firebaseApi.auth;
      const cred = await api.signIn(email.trim(), password);
      if (!api.isWhitelisted(cred.user.email)) {
        await api.signOut();
        setError("此 Email 不在白名單,已登出");
      }
      // 成功且為白名單 → App.jsx 的 onAuth 訂閱會接手切到主畫面
    } catch (err) {
      setError(authErrorMessage(err));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="screen login">
      <div className="login-mark">
        <div className="login-dot" />
        <div className="login-dot" style={{ background: accent }} />
      </div>
      <div className="login-title">記帳</div>
      <div className="login-sub">兩個人的帳本</div>
      <form className="login-actions" onSubmit={handleSubmit}>
        <input
          type="email"
          className="form-in"
          placeholder="Email"
          autoComplete="username"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          autoFocus
        />
        <input
          type="password"
          className="form-in"
          placeholder="密碼"
          autoComplete="current-password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        {error && <div className="entry-error">{error}</div>}
        <button
          type="submit"
          className="login-btn"
          style={{ background: accent }}
          disabled={busy || !email || !password}
        >
          {busy ? "登入中…" : "登入"}
        </button>
      </form>
    </div>
  );
}

function authErrorMessage(err) {
  const code = (err && err.code) || "";
  if (code === "auth/invalid-credential" ||
      code === "auth/wrong-password" ||
      code === "auth/user-not-found") return "帳號或密碼錯誤";
  if (code === "auth/invalid-email") return "Email 格式錯誤";
  if (code === "auth/too-many-requests") return "嘗試次數過多,稍後再試";
  if (code === "auth/network-request-failed") return "網路錯誤,請檢查連線";
  if (code === "auth/operation-not-allowed") return "後台尚未啟用 Email/Password 登入";
  if (code) return `登入失敗(${code})`;
  return "登入失敗";
}

window.LoginScreen = LoginScreen;
