/* TargiApp — ekran logowania kodem PIN (4 cyfry) */
function LoginScreen() {
  const store = useStore();
  const [pin, setPin] = useState("");
  const [err, setErr] = useState(false);

  function press(d) {
    if (err) setErr(false);
    if (pin.length >= 4) return;
    const next = pin + d;
    setPin(next);
    if (next.length === 4) {
      setTimeout(() => {
        Promise.resolve(store.login(next)).then((ok) => {
          if (!ok) { setErr(true); setPin(""); }
        });
      }, 120);
    }
  }
  function back() { setErr(false); setPin((p) => p.slice(0, -1)); }

  useEffect(() => {
    function onKey(e) {
      if (e.key >= "0" && e.key <= "9") press(e.key);
      else if (e.key === "Backspace") back();
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  });

  return (
    <div className="login-wrap">
      <div className="login-card">
        <div className="login-brand">
          <div className="eps-mark">EPS</div>
          <div className="brand-name">Targi<span className="accent">App</span></div>
        </div>
        <div className="login-title">Harmonogram targowy</div>
        <div className="login-sub">Zaloguj się swoim kodem PIN</div>

        <div className="pin-dots">
          {[0, 1, 2, 3].map((i) => (
            <div key={i} className={"pin-dot" + (i < pin.length ? " on" : "") + (err ? " err" : "")}></div>
          ))}
        </div>
        <div className="login-err">{err ? "Nieprawidłowy kod PIN" : ""}</div>

        <div className="keypad">
          {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => (
            <button key={n} className="key" onClick={() => press(String(n))}>{n}</button>
          ))}
          <button className="key ghost" onClick={back}>← Usuń</button>
          <button className="key" onClick={() => press("0")}>0</button>
          <button className="key ghost" onClick={() => setPin("")}>Wyczyść</button>
        </div>

        <div className="login-hint">
          Demo: zaloguj się jako administrator PIN-em <b>1111</b><br />
          pozostałe kody PIN są w panelu „Użytkownicy".
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { LoginScreen });
