// public/email-gate.jsx
// Soft email gate: fades the matrix on first visit and asks for an email.
// Dismissable via "Skip for now" or Escape. Fail-silent on backend errors —
// soft gate means we never block the visitor on a network hiccup.

function EmailGate({ t, dark }) {
  const STORAGE_KEY = "r-gate-state";

  const initialState = (() => {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (raw) return JSON.parse(raw);
    } catch (_) {}
    return null;
  })();

  const state = initialState;
  const [phase, setPhase] = React.useState("visible"); // visible | thanks | fading | done
  const [email, setEmail] = React.useState("");
  const inputRef = React.useRef(null);
  const previouslyFocused = React.useRef(null);
  const headingId = "r-gate-heading";

  React.useEffect(() => {
    if (state || phase === "done") return;
    previouslyFocused.current = document.activeElement;
    inputRef.current?.focus();
    return () => { try { previouslyFocused.current?.focus(); } catch (_) {} };
  }, [state, phase]);

  React.useEffect(() => {
    if (state || phase === "done") return;
    const onKey = (e) => { if (e.key === "Escape") { e.preventDefault(); skip(); } };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state, phase]);

  if (state || phase === "done") return null;
  if (!t) return null;

  const persist = (status, emailValue) => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify({
        status, email: emailValue || undefined, ts: Date.now(),
      }));
    } catch (_) {}
  };

  const skip = () => {
    persist("skipped", null);
    setPhase("fading");
    setTimeout(() => setPhase("done"), 300);
  };

  const submit = (e) => {
    e.preventDefault();
    const value = email.trim();
    if (!value) { inputRef.current?.focus(); return; }
    persist("submitted", value);
    // Fire-and-forget; never block visitor on the network.
    fetch("/api/capture-email", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: value, ts: Date.now() }),
    }).catch(() => {});
    setPhase("thanks");
    setTimeout(() => setPhase("fading"), 900);
    setTimeout(() => setPhase("done"), 1200);
  };

  const onTabKeydown = (e) => {
    if (e.key !== "Tab") return;
    const focusables = e.currentTarget.querySelectorAll(
      "input, button, [href], [tabindex]:not([tabindex='-1'])"
    );
    if (focusables.length === 0) return;
    const first = focusables[0];
    const last = focusables[focusables.length - 1];
    if (e.shiftKey && document.activeElement === first) {
      e.preventDefault(); last.focus();
    } else if (!e.shiftKey && document.activeElement === last) {
      e.preventDefault(); first.focus();
    }
  };

  const opacity = phase === "fading" ? 0 : 1;

  return (
    <div className="r-gate-backdrop" style={{
      position: "fixed", inset: 0, zIndex: 300,
      background: "rgba(250,247,243,0.7)",
      backdropFilter: "blur(6px)",
      WebkitBackdropFilter: "blur(6px)",
      opacity, transition: "opacity 300ms ease",
      display: "flex", alignItems: "center", justifyContent: "center",
      padding: 24,
    }}>
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby={headingId}
        onKeyDown={onTabKeydown}
        style={{
          width: "100%", maxWidth: 420,
          background: "#FFFFFF", border: "1px solid #E2E0DF",
          padding: "28px 24px",
          fontFamily: "var(--font-body)", color: "#393433",
        }}
      >
        {phase === "thanks" ? (
          <div aria-live="polite" style={{
            fontFamily: "var(--font-display)", fontSize: 18, color: "#4866B2",
            textAlign: "center", padding: "16px 0",
          }}>
            {t.gateThanks || "Thanks."}
          </div>
        ) : (
          <form onSubmit={submit}>
            <div id={headingId} style={{
              fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 400,
              letterSpacing: "-0.01em", marginBottom: 8,
            }}>
              {t.gateHeading}
            </div>
            <p style={{ fontSize: 13, lineHeight: 1.45, color: "#6B6361", marginTop: 0, marginBottom: 16 }}>
              {t.gateBody}
            </p>
            <input
              ref={inputRef}
              type="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={t.gateEmailPlaceholder}
              style={{
                width: "100%", boxSizing: "border-box",
                height: 40, padding: "0 12px",
                border: "1px solid #C7C2BD", background: "#FAF7F3",
                fontFamily: "var(--font-body)", fontSize: 14, color: "#393433",
                marginBottom: 14,
              }}
            />
            <button type="submit" style={{
              width: "100%", height: 40,
              background: "#4866B2", color: "#FAF7F3",
              border: "none", cursor: "pointer",
              fontFamily: "var(--font-mono)", fontSize: 11,
              letterSpacing: "0.16em", textTransform: "uppercase",
            }}>
              {t.gateContinue}
            </button>
            <div style={{ textAlign: "center", marginTop: 12 }}>
              <button type="button" onClick={skip} style={{
                background: "transparent", border: "none",
                color: "#6B6361", textDecoration: "underline",
                fontFamily: "var(--font-body)", fontSize: 12, cursor: "pointer",
              }}>
                {t.gateSkip}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

window.EmailGate = EmailGate;
