/* ============ Login (PIN) ============
 * Now calls POST /api/login instead of matching against a locally-held
 * staff array. The browser never again downloads the staff/PIN list
 * before login — this is the fix for the "chicken-and-egg" PIN leak.
 */

function LoginView({ onLoggedIn, modeLabel }) {
  const [pin, setPin] = useState("");
  const [err, setErr] = useState(false);
  const [errMsg, setErrMsg] = useState("");
  const [busy, setBusy] = useState(false);

  const LOCK_KEY = "giraffe_pin_lock";
  const getLock = () => { try { return JSON.parse(localStorage.getItem(LOCK_KEY) || '{"fails":0,"until":0}'); } catch (e) { return { fails: 0, until: 0 }; } };
  const [, force] = useState(0);
  useEffect(() => { const t = setInterval(() => force(x => x + 1), 1000); return () => clearInterval(t); }, []);
  const lock = getLock();
  const lockedSec = Math.max(0, Math.ceil((lock.until - Date.now()) / 1000));

  const tryLogin = async (fullPin) => {
    setBusy(true);
    try {
      const res = await Backend.apiFetch("/api/login", { method: "POST", body: JSON.stringify({ pin: fullPin }) });
      localStorage.removeItem(LOCK_KEY);
      onLoggedIn(res.token, res.user);
    } catch (e) {
      const l = getLock();
      l.fails = (l.fails || 0) + 1;
      if (l.fails >= 5) { l.until = Date.now() + 60 * 1000 * Math.min(10, l.fails - 4); }
      localStorage.setItem(LOCK_KEY, JSON.stringify(l));
      setErr(true);
      setErrMsg(e.status === 429 ? "入力ミスが続いたため一時的にロックされました" : (l.fails >= 5 ? "入力ミスが続いたため一時的にロックされました" : `PINが正しくありません（あと${5 - l.fails}回で一時ロック）`));
      setTimeout(() => { setPin(""); setErr(false); }, 500);
    } finally {
      setBusy(false);
    }
  };

  const press = (n) => {
    if (lockedSec > 0 || busy) return;
    if (pin.length >= 4) return;
    const np = pin + n;
    setPin(np);
    setErrMsg("");
    if (np.length === 4) {
      // slight delay to let UI paint the 4th dot
      setTimeout(() => tryLogin(np), 100);
    }
  };
  const back = () => setPin(p => p.slice(0, -1));

  const keys = ["1","2","3","4","5","6","7","8","9"];
  return (
    <div className="login-wrap">
      <Setup.Logo size={96} />
      <div style={{height:14}} />
      <h1>Giraffe 在庫管理</h1>
      <p className="lead">ホテル＆サウナの<br/>アメニティ・物販在庫を、写真1枚で。</p>

      <div className={"pin-display " + (err ? "err" : "")}>
        {[0,1,2,3].map(i => <div key={i} className={"dot " + (i < pin.length ? "filled" : "")} />)}
      </div>

      <div className="pin-pad">
        {keys.map(k => (
          <button key={k} className="pin-key" onClick={() => press(k)}>{k}</button>
        ))}
        <button className="pin-key action" onClick={() => setPin("")}>クリア</button>
        <button className="pin-key" onClick={() => press("0")}>0</button>
        <button className="pin-key action" onClick={back}>⌫</button>
      </div>

      <p className="login-note">
        {lockedSec > 0 ? `一時ロック中：あと ${lockedSec} 秒` : (errMsg || (busy ? "確認中…" : "4桁のPINを入力してください"))}
      </p>
      {modeLabel && <p className="login-note" style={{marginTop:4}}>{modeLabel}</p>}
      <p className="login-note ver-tag" style={{marginTop:2, opacity:.6}}>ver 5.0</p>
    </div>
  );
}

window.LoginView = LoginView;
