/* global React */
const { useState, useEffect, useRef } = React;

const PIN_KEY = "mai_pin";

function AuthGate({ onAuth }) {
  const stored = localStorage.getItem(PIN_KEY);
  const [mode, setMode] = useState(stored ? "enter" : "create");
  const [pin, setPin] = useState("");
  const [confirm, setConfirm] = useState("");
  const [step, setStep] = useState("pin"); // "pin" | "confirm"
  const [shake, setShake] = useState(false);
  const [hint, setHint] = useState("");

  const doShake = (msg) => {
    setHint(msg);
    setShake(true);
    setTimeout(() => setShake(false), 500);
  };

  const press = (d) => {
    if (mode === "create") {
      if (step === "pin") {
        const next = pin + d;
        setPin(next);
        if (next.length === 4) {
          setTimeout(() => { setStep("confirm"); setPin(""); }, 200);
        }
      } else {
        const next = confirm + d;
        setConfirm(next);
        if (next.length === 4) {
          if (next === pin || (pin === "" && next === next)) {
            // We stored pin in step "pin" already — need ref
          }
          setTimeout(() => {
            const storedPin = document.getElementById("__pin_store")?.dataset.pin;
            if (next === storedPin) {
              localStorage.setItem(PIN_KEY, next);
              onAuth();
            } else {
              doShake("הקודים לא תואמים");
              setConfirm("");
              setStep("pin");
              setPin("");
            }
          }, 200);
        }
      }
    } else {
      const next = pin + d;
      setPin(next);
      if (next.length === 4) {
        setTimeout(() => {
          if (next === localStorage.getItem(PIN_KEY)) {
            onAuth();
          } else {
            doShake("קוד שגוי");
            setPin("");
          }
        }, 200);
      }
    }
  };

  const del = () => {
    if (step === "pin" || mode === "enter") setPin(p => p.slice(0, -1));
    else setConfirm(c => c.slice(0, -1));
  };

  const current = (mode === "create" && step === "confirm") ? confirm : pin;

  // Store pin for confirm step comparison
  const [storedPin, setStoredPin] = useState("");
  useEffect(() => {
    if (mode === "create" && step === "confirm") setStoredPin(pin);
  }, [step]);

  const pressCreate = (d) => {
    if (step === "pin") {
      const next = pin + d;
      setPin(next);
      if (next.length === 4) {
        setTimeout(() => {
          setStoredPin(next);
          setStep("confirm");
          setPin("");
        }, 250);
      }
    } else {
      const next = confirm + d;
      setConfirm(next);
      if (next.length === 4) {
        setTimeout(() => {
          if (next === storedPin) {
            localStorage.setItem(PIN_KEY, next);
            onAuth();
          } else {
            doShake("הקודים לא תואמים, נסי שוב");
            setConfirm("");
            setStep("pin");
            setPin("");
            setStoredPin("");
          }
        }, 200);
      }
    }
  };

  const handlePress = mode === "create" ? pressCreate : press;

  const title = mode === "enter" ? "הספרייה של מאי" :
    step === "pin" ? "בחרי קוד PIN" : "אמתי את הקוד";
  const sub = mode === "enter" ? "הכנסי את קוד הגישה" :
    step === "pin" ? "4 ספרות לנעילת הספרייה" : "הכנסי שוב לאישור";

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 999,
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      background: "linear-gradient(160deg, #1a0e07 0%, #3a2412 60%, #5c3820 100%)",
      padding: 24,
    }}>
      {/* Background texture */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "url(assets/library-bg.png)",
        backgroundSize: "cover", backgroundPosition: "center",
        opacity: 0.18,
      }} />

      <div style={{ position: "relative", width: "100%", maxWidth: 340, textAlign: "center" }}>
        {/* Logo */}
        <div style={{
          width: 72, height: 72, borderRadius: 22,
          background: "rgba(180,138,58,.15)",
          border: "1.5px solid rgba(180,138,58,.35)",
          display: "grid", placeItems: "center",
          margin: "0 auto 20px",
          fontSize: 32,
          backdropFilter: "blur(8px)",
        }}>📚</div>

        <h1 style={{ fontFamily: '"Frank Ruhl Libre", serif', fontSize: 28, fontWeight: 900, color: "#fff8e8", margin: "0 0 6px" }}>{title}</h1>
        <p style={{ color: "rgba(255,248,232,.55)", fontSize: 14, margin: "0 0 36px" }}>{sub}</p>

        {/* Dots */}
        <div style={{ display: "flex", justifyContent: "center", gap: 16, marginBottom: 40 }}
          className={shake ? "shake" : ""}>
          {[0,1,2,3].map(i => (
            <div key={i} style={{
              width: 16, height: 16, borderRadius: "50%",
              background: i < current.length ? "#b48a3a" : "transparent",
              border: "2px solid",
              borderColor: i < current.length ? "#b48a3a" : "rgba(255,248,232,.3)",
              transition: "all .15s",
              transform: i < current.length ? "scale(1.15)" : "scale(1)",
            }} />
          ))}
        </div>

        {hint && <div style={{ color: "#e07060", fontSize: 13, marginBottom: 16, marginTop: -28 }}>{hint}</div>}

        {/* Keypad */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
          {[1,2,3,4,5,6,7,8,9,"",0,"⌫"].map((k, i) => (
            k === "" ? <div key={i} /> :
            <button
              key={i}
              onClick={() => k === "⌫" ? del() : handlePress(String(k))}
              style={{
                height: 64, borderRadius: 16,
                background: k === "⌫" ? "rgba(255,255,255,.06)" : "rgba(255,248,232,.08)",
                border: "1px solid rgba(255,248,232,.12)",
                color: "#fff8e8",
                fontSize: k === "⌫" ? 20 : 24,
                fontFamily: '"Heebo", sans-serif',
                fontWeight: 600,
                cursor: "pointer",
                backdropFilter: "blur(6px)",
                transition: "background .1s",
              }}
              onMouseDown={e => e.currentTarget.style.background = "rgba(180,138,58,.25)"}
              onMouseUp={e => e.currentTarget.style.background = k === "⌫" ? "rgba(255,255,255,.06)" : "rgba(255,248,232,.08)"}
              onTouchStart={e => e.currentTarget.style.background = "rgba(180,138,58,.25)"}
              onTouchEnd={e => e.currentTarget.style.background = k === "⌫" ? "rgba(255,255,255,.06)" : "rgba(255,248,232,.08)"}
            >{k}</button>
          ))}
        </div>

        {mode === "enter" && (
          <button
            onClick={() => { setMode("create"); setPin(""); setStep("pin"); setHint(""); }}
            style={{ marginTop: 24, color: "rgba(255,248,232,.4)", fontSize: 13, background: "none", border: "none", cursor: "pointer" }}
          >שכחת קוד? אפסי</button>
        )}
      </div>

      <style>{`
        @keyframes shake {
          0%,100%{transform:translateX(0)}
          20%{transform:translateX(-8px)}
          40%{transform:translateX(8px)}
          60%{transform:translateX(-6px)}
          80%{transform:translateX(6px)}
        }
        .shake { animation: shake .45s ease; }
      `}</style>
    </div>
  );
}

Object.assign(window, { AuthGate, AUTH_PIN_KEY: PIN_KEY });
