// Screen 1: PIN Login
const { useState: useStatePL, useEffect: useEffectPL, useRef: useRefPL } = React;

function PinLogin({ onLogin }) {
  const [pin, setPin] = useStatePL("");
  const [status, setStatus] = useStatePL("idle"); // idle | recognized | error | locked
  const [recognized, setRecognized] = useStatePL(null);
  const [fails, setFails] = useStatePL(0);
  const [lockSeconds, setLockSeconds] = useStatePL(0);
  const advanceRef = useRefPL(null);

  useEffectPL(() => {
    if (status !== "locked") return;
    if (lockSeconds <= 0) { setStatus("idle"); setFails(0); setPin(""); return; }
    const t = setTimeout(() => setLockSeconds((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [status, lockSeconds]);

  async function tryPin(p) {
    try {
      const r = await fetch("/api/auth/pin", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ pin: p }),
      });
      if (r.ok) {
        const { user } = await r.json();
        setRecognized(user);
        setStatus("recognized");
        advanceRef.current = setTimeout(() => onLogin(user), 1100);
      } else {
        const nf = fails + 1;
        setFails(nf);
        if (nf >= 5) { setStatus("locked"); setLockSeconds(30); }
        else { setStatus("error"); setTimeout(() => { setPin(""); setStatus("idle"); }, 900); }
      }
    } catch {
      setStatus("error");
      setTimeout(() => { setPin(""); setStatus("idle"); }, 900);
    }
  }
  function press(d) {
    if (status === "locked" || status === "recognized" || status === "error") return;
    if (pin.length >= 4) return;
    const next = pin + d;
    setPin(next);
    if (next.length === 4) setTimeout(() => tryPin(next), 120);
  }
  function backspace() { if (status === "idle") setPin((p) => p.slice(0, -1)); }
  function clear() { if (status === "idle") setPin(""); }

  // Hardware keyboard support — digits / backspace / esc
  useEffectPL(() => {
    function onKey(e) {
      if (status === "locked" || status === "recognized") return;
      if (e.key >= "0" && e.key <= "9") {
        e.preventDefault();
        press(e.key);
      } else if (e.key === "Backspace") {
        e.preventDefault();
        backspace();
      } else if (e.key === "Escape" || e.key === "Delete") {
        e.preventDefault();
        clear();
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [pin, status, fails]);

  const keys = ["1","2","3","4","5","6","7","8","9","clear","0","back"];

  return (
    <div className="min-h-screen w-full bg-zinc-950 text-zinc-100 flex relative">
      <window.TopStripe />
      {/* Left panel */}
      <div className="w-[42%] border-r border-zinc-800/80 px-14 py-12 flex flex-col justify-between bg-gradient-to-b from-zinc-900/40 to-zinc-950">
        <div className="flex items-center gap-3">
          <window.BrandMark size={48} />
          <window.BrandWordmark />
        </div>

        <div>
          <div className="text-[13px] uppercase tracking-[0.22em] text-zinc-500 mb-3">
            Sign in
          </div>
          <h1 className="font-display text-[88px] leading-[0.88] tracking-tight">
            Enter your<br />4-digit PIN
          </h1>
          <div className="mt-7 space-y-1.5">
            <div className="text-zinc-300 text-[19px]">{window.STATION?.name || "Bay 1 · Table 1"}</div>
            <div className="text-zinc-500 text-[15px]">
              Tomás ended last session yesterday at 22:41
            </div>
          </div>
        </div>

        <div className="space-y-3">
          <div className="font-display italic text-[20px] tracking-[0.22em]" style={{ color: window.GPS_RED }}>
            DRIVING WITH ENDURANCE
          </div>
          <div className="text-[13px] text-zinc-500 flex items-center gap-3">
            <span className="h-2 w-2 rounded-full bg-emerald-500 inline-block" />
            Station online · synced 8s ago · Tue 19 May · 07:14
          </div>
        </div>
      </div>

      {/* Right panel — keypad */}
      <div className="flex-1 flex flex-col items-center justify-center px-12 py-12">
        <div className="mb-10 h-[130px] flex flex-col items-center justify-center">
          {status === "recognized" ? (
            <div className="text-center">
              <div className="text-[14px] uppercase tracking-[0.22em] text-emerald-400 mb-2">
                Welcome back
              </div>
              <div className="font-display text-[72px] leading-[0.9] tracking-tight">
                {recognized.name}
              </div>
              <div className="text-zinc-400 text-[17px] mt-2 flex items-center justify-center gap-2">
                <window.RoleBadge role={recognized.role} />
                <span>· {recognized.shift} shift</span>
              </div>
            </div>
          ) : status === "locked" ? (
            <div className="text-center">
              <div className="text-[14px] uppercase tracking-[0.22em] text-red-400 mb-2">
                Station locked
              </div>
              <div className="font-display text-[48px] tracking-tight text-red-300">
                Too many failed attempts
              </div>
              <div className="text-zinc-400 text-[17px] mt-2 font-mono">
                Try again in {String(lockSeconds).padStart(2,"0")}s · or ask supervisor
              </div>
            </div>
          ) : status === "error" ? (
            <div className="text-center">
              <div className="text-[14px] uppercase tracking-[0.22em] text-red-400 mb-2">
                PIN not recognized
              </div>
              <div className="text-[24px] text-zinc-300">
                {5 - fails} {5 - fails === 1 ? "attempt" : "attempts"} remaining
              </div>
            </div>
          ) : (
            <div className="flex gap-6" style={{ animation: status === "error" ? "shake 0.4s" : undefined }}>
              {[0,1,2,3].map((i) => (
                <div
                  key={i}
                  className={`h-[60px] w-[60px] rounded-full border-2 transition-all ${
                    i < pin.length ? "bg-zinc-100 border-zinc-100" : "border-zinc-800 bg-transparent"
                  }`}
                />
              ))}
            </div>
          )}
        </div>

        <div className="grid grid-cols-3 gap-4 w-[480px]">
          {keys.map((k) => {
            const disabled = status === "locked" || status === "recognized" || status === "error";
            if (k === "clear") return (
              <button key={k} disabled={disabled} onClick={clear}
                className="h-[110px] rounded-xl bg-zinc-900 border border-zinc-800 text-zinc-400 font-display text-[24px] tracking-wider hover:bg-zinc-800 active:scale-[0.97] transition disabled:opacity-40">
                CLEAR
              </button>
            );
            if (k === "back") return (
              <button key={k} disabled={disabled} onClick={backspace}
                className="h-[110px] rounded-xl bg-zinc-900 border border-zinc-800 text-zinc-400 hover:bg-zinc-800 active:scale-[0.97] transition flex items-center justify-center disabled:opacity-40"
                aria-label="Backspace">
                <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M21 4H8l-7 8 7 8h13a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z" />
                  <line x1="18" y1="9" x2="12" y2="15" /><line x1="12" y1="9" x2="18" y2="15" />
                </svg>
              </button>
            );
            return (
              <button key={k} disabled={disabled} onClick={() => press(k)}
                className="h-[110px] rounded-xl bg-zinc-900 border border-zinc-800 text-zinc-100 font-display text-[48px] tabular-nums hover:bg-zinc-800 active:scale-[0.97] active:bg-zinc-700 transition disabled:opacity-40">
                {k}
              </button>
            );
          })}
        </div>

        <div className="mt-10 text-[13px] text-zinc-600 font-mono">
          demo · 5531 Cole · 3819 Markus (mgr) · 8472 Tobias (admin)
          <span className="block mt-1 text-zinc-700">tap keypad or type · backspace deletes · esc clears</span>
        </div>
      </div>

      <style>{`
        @keyframes shake { 10%, 90% { transform: translateX(-2px); } 20%, 80% { transform: translateX(4px); } 30%, 50%, 70% { transform: translateX(-8px); } 40%, 60% { transform: translateX(8px); } }
      `}</style>
    </div>
  );
}

window.PinLogin = PinLogin;
