/* ============================================================
   login.jsx — Login by 6-digit PIN. The PIN is verified by the API
   server (PIN → JWT); this screen only collects it.
   ============================================================ */
const PIN_LEN = 6;

// demo PIN hints (the server is the real authority; these just autofill)
const DEMO_PINS = [
  { role: "Admin", pin: "100001" },
  { role: "HQ Manager", pin: "200010" },
  { role: "Manager", pin: "310101" },
  { role: "Staff", pin: "410102" },
];

function LoginScreen({ onSubmit, error, loading }) {
  const [pin, setPin] = useState("");
  const [localErr, setLocalErr] = useState("");
  const busy = useRef(false);
  const err = error || localErr;

  async function submit(code) {
    if (busy.current) return;
    busy.current = true;
    try {
      await onSubmit(code);            // resolves on success, throws on failure
    } catch (e) {
      setLocalErr(e.message || "เข้าสู่ระบบไม่สำเร็จ");
      setPin("");
    } finally {
      busy.current = false;
    }
  }
  function press(d) {
    if (loading || busy.current) return;
    setLocalErr("");
    setPin((p) => {
      if (p.length >= PIN_LEN) return p;
      const np = p + d;
      if (np.length === PIN_LEN) setTimeout(() => submit(np), 120);
      return np;
    });
  }

  return (
    <div className="login-root">
      <div className="login-bg" />
      <div className="login-card">
        <div className="login-brand">
          <span className="login-logo">◐</span>
          <div>
            <div className="login-name">POS Coffee</div>
            <div className="login-tag">ระบบขายหน้าร้าน · หลายสาขา</div>
          </div>
        </div>

        <div className="login-h">เข้าสู่ระบบด้วย PIN</div>
        <div className="login-sub">ใส่รหัส PIN 6 หลักของคุณ</div>

        <div className={"pin-dots six" + (err ? " shake" : "")}>
          {Array.from({ length: PIN_LEN }).map((_, i) => <span key={i} className={"pin-dot" + (pin.length > i ? " on" : "")} />)}
        </div>
        <div className="pin-err-slot">{err ? <span className="pin-err">{err}</span> : (loading ? <span className="pin-err" style={{ color: "var(--d-soft)" }}>กำลังตรวจสอบ…</span> : null)}</div>

        <div className="pin-pad">
          {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => <button key={n} className="pin-key" onClick={() => press(String(n))}>{n}</button>)}
          <button className="pin-key pin-clear" onClick={() => { setPin(""); setLocalErr(""); }}>ล้าง</button>
          <button className="pin-key" onClick={() => press("0")}>0</button>
          <button className="pin-key pin-del" onClick={() => { setLocalErr(""); setPin((p) => p.slice(0, -1)); }}>⌫</button>
        </div>

        <div className="login-demo">
          <div className="ld-l">PIN สำหรับทดลอง (เดโม)</div>
          <div className="ld-grid">
            {DEMO_PINS.map((u) => (
              <button key={u.pin} className="ld-chip" onClick={() => { setLocalErr(""); setPin(u.pin); setTimeout(() => submit(u.pin), 150); }}>
                <span className="ld-role">{u.role}</span>
                <span className="ld-pin">{u.pin}</span>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen });
