/* Veridyne Learning Portal — Access gate: username → 4-digit code.
   Live mode checks both against the team database (via /api/portal → Neon).
   Demo mode (no API reachable): any username + code 2127, local progress only. */
function AccessGate() {
  const store = useStore();
  const [step, setStep] = React.useState("user");      // user | code
  const [username, setUsername] = React.useState("");
  const [checking, setChecking] = React.useState(false);
  const [userError, setUserError] = React.useState("");
  const [entry, setEntry] = React.useState("");
  const [verifying, setVerifying] = React.useState(false);
  const [codeError, setCodeError] = React.useState("");
  const [shake, setShake] = React.useState(false);
  const [pressed, setPressed] = React.useState(null);
  const [unlocking, setUnlocking] = React.useState(false);

  const uname = username.trim().toLowerCase();
  const mode = store.mode;

  const continueUser = async () => {
    if (!uname) { setUserError("Enter your username."); return; }
    setUserError("");
    if (mode === "demo") { setStep("code"); return; }
    setChecking(true);
    try {
      const r = await apiCall("userExists", { username: uname });
      if (r.exists) setStep("code");
      else setUserError("Username not recognised — ask your Veridyne admin.");
    } catch (e) {
      setUserError("Can't reach the team database. Check your connection and try again.");
    }
    setChecking(false);
  };

  const fail = (msg) => {
    setCodeError(msg);
    setShake(true);
    setTimeout(() => { setEntry(""); setShake(false); }, 650);
  };

  const submitCode = async (codeStr) => {
    if (mode === "demo") {
      if (codeStr === "2127") {
        setUnlocking(true);
        setTimeout(() => store.login({ username: uname, demo: true }, null), 750);
      } else fail("Invalid code. Please try again.");
      return;
    }
    setVerifying(true);
    try {
      const r = await apiCall("login", { username: uname, code: codeStr });
      setVerifying(false);
      setUnlocking(true);
      setTimeout(() => store.login({ username: uname, code: codeStr }, r.progress), 750);
    } catch (e) {
      setVerifying(false);
      fail(e.status === 401 ? "Invalid code. Please try again." : "Database unreachable — try again in a moment.");
    }
  };

  const press = (digit) => {
    if (unlocking || verifying) return;
    setCodeError("");
    setPressed(digit);
    setTimeout(() => setPressed(null), 180);
    if (digit === "del") { setEntry((e) => e.slice(0, -1)); return; }
    const next = (entry + digit).slice(0, 4);
    setEntry(next);
    if (next.length === 4) submitCode(next);
  };

  React.useEffect(() => {
    const onKey = (e) => {
      if (step === "user") {
        if (e.key === "Enter") continueUser();
        return;
      }
      if (/^[0-9]$/.test(e.key)) press(e.key);
      else if (e.key === "Backspace") press("del");
      else if (e.key === "Escape") { setStep("user"); setEntry(""); setCodeError(""); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  });

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

  const modeBadge =
    mode === "detecting" ? <span className="badge"><Icon name="refresh" size={11} /> Connecting…</span> :
    mode === "live" ? <span className="badge badge-ok"><Icon name="checkCircle" size={11} /> Team database connected</span> :
    <span className="badge badge-warn"><Icon name="alert" size={11} /> Demo mode — progress stays in this browser</span>;

  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: 20 }}>
      <div className="glass-raised anim-fade-up"
        style={{ width: "min(400px, 100%)", padding: "clamp(28px, 5vw, 44px) clamp(24px, 5vw, 40px)", textAlign: "center", transition: "transform 0.7s cubic-bezier(0.4,0,0.2,1), opacity 0.7s", transform: unlocking ? "scale(1.06)" : "none", opacity: unlocking ? 0 : 1 }}>
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
          <div style={{ padding: 16, borderRadius: 24, background: "rgba(180,99,42,0.12)", border: "1px solid rgba(180,99,42,0.25)" }}>
            <VeridyneMark size={52} />
          </div>
        </div>
        <h1 style={{ fontSize: "1.55em", marginBottom: 6 }}>Veridyne Learning Portal</h1>
        <p style={{ color: "var(--bone-70)", fontSize: "0.92em", marginBottom: 14 }}>
          Identity learning for Okta and Auth0 delivery teams
        </p>
        <div style={{ marginBottom: 22 }}>{modeBadge}</div>

        {step === "user" ? (
          <div className="anim-fade-in">
            <label htmlFor="gate-username" style={{ display: "block", textAlign: "left", fontSize: "0.78em", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--bone-50)", fontWeight: 600, marginBottom: 8 }}>
              Username
            </label>
            <input id="gate-username" value={username} autoFocus autoComplete="username" spellCheck={false}
              onChange={(e) => { setUsername(e.target.value); setUserError(""); }}
              placeholder="e.g. alec"
              style={{ width: "100%", padding: "13px 16px", borderRadius: 14, border: "1px solid " + (userError ? "var(--bad)" : "var(--glass-border)"), background: "rgba(16,23,29,0.5)", color: "var(--bone)", fontSize: "1em", fontFamily: "inherit", outline: "none", minHeight: 48 }} />
            <p aria-live="polite" style={{ minHeight: 20, fontSize: "0.85em", color: "var(--bad)", margin: "8px 0 10px", textAlign: "left" }}>
              {userError || "\u00A0"}
            </p>
            <button className="btn btn-primary" onClick={continueUser} disabled={checking} style={{ width: "100%", opacity: checking ? 0.7 : 1 }}>
              {checking ? "Checking…" : <React.Fragment>Continue <Icon name="arrowRight" size={15} /></React.Fragment>}
            </button>
          </div>
        ) : (
          <div className="anim-fade-in">
            <p style={{ fontSize: "0.92em", color: "var(--bone-70)", marginBottom: 16 }}>
              Hi <strong style={{ color: "var(--ember-bright)" }}>{uname}</strong> — enter your 4-digit code
            </p>
            <div role="status" aria-label={`${entry.length} of 4 digits entered`}
              style={{ display: "flex", justifyContent: "center", gap: 20, marginBottom: 14, animation: shake ? "v-shake 0.5s" : "none" }}>
              {[0, 1, 2, 3].map((i) => (
                <div key={i} style={{
                  width: 14, height: 14, borderRadius: "50%",
                  border: "2px solid " + (shake ? "var(--bad)" : entry.length > i ? "var(--ember-bright)" : "rgba(229,221,208,0.25)"),
                  background: entry.length > i ? (shake ? "var(--bad)" : "var(--ember-bright)") : "transparent",
                  transition: "all 0.15s ease",
                  transform: entry.length === i + 1 ? "scale(1.25)" : "scale(1)",
                  boxShadow: entry.length > i && !shake ? "0 0 10px rgba(208,126,63,0.6)" : "none",
                }} />
              ))}
            </div>
            <p aria-live="polite" style={{ minHeight: 20, fontSize: "0.85em", color: verifying ? "var(--bone-50)" : "var(--bad)", marginBottom: 12 }}>
              {verifying ? "Verifying…" : codeError || "\u00A0"}
            </p>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 72px)", gap: 14, margin: "0 auto", justifyContent: "center" }}>
              {keys.map((k, i) =>
                k === "" ? <div key={i} style={{ width: 72, height: 72 }} /> : (
                  <button key={i} onClick={() => press(k)}
                    aria-label={k === "del" ? "Delete digit" : "Digit " + k}
                    style={{
                      width: 72, height: 72, borderRadius: "50%",
                      border: "1px solid " + (pressed === k ? "rgba(180,99,42,0.6)" : "var(--glass-border)"),
                      background: pressed === k
                        ? "rgba(180,99,42,0.25)"
                        : "rgba(229,221,208,0.06)",
                      boxShadow: pressed === k
                        ? "0 0 0 4px rgba(180,99,42,0.15), inset 0 1px 0 rgba(229,221,208,0.1)"
                        : "inset 0 1px 0 rgba(229,221,208,0.08), 0 2px 8px rgba(0,0,0,0.2)",
                      fontSize: k === "del" ? "1em" : "1.4em", fontWeight: 500, cursor: "pointer",
                      display: "grid", placeItems: "center", flexShrink: 0,
                      color: pressed === k ? "var(--ember-bright)" : "var(--bone)",
                      transform: pressed === k ? "scale(0.91)" : "scale(1)",
                      transition: "transform 0.1s ease, background 0.12s ease, box-shadow 0.12s ease, border-color 0.12s ease, color 0.12s ease",
                      WebkitBackdropFilter: "blur(10px)", backdropFilter: "blur(10px)",
                      opacity: verifying ? 0.55 : 1,
                    }}>
                    {k === "del" ? <Icon name="backspace" size={20} /> : k}
                  </button>
                )
              )}
            </div>
            <button className="btn btn-ghost btn-sm" onClick={() => { setStep("user"); setEntry(""); setCodeError(""); }}
              style={{ marginTop: 18, color: "var(--bone-50)" }}>
              <Icon name="arrowLeft" size={13} /> Not {uname}?
            </button>
          </div>
        )}

        <p style={{ marginTop: 24, fontSize: "0.75em", color: "var(--bone-50)", display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
          <Icon name="lock" size={12} /> Training access gate — not production security
        </p>
      </div>
    </div>
  );
}

window.AccessGate = AccessGate;
