// Free-guide lead capture popup, triggered on first scroll. SPEC §10.5.
// Posts to the real backend via window.apiFetch. Deduplicated responses
// (HTTP 200 with {deduplicated: true}) are shown to the user as success —
// "Check your inbox" — without exposing the dedupe status.
const { useState: useStateL, useEffect: useEffectL } = React;

function LeadPopup() {
  const [open, setOpen] = useStateL(false);
  const [shown, setShown] = useStateL(false);
  const [email, setEmail] = useStateL("");
  const [msg, setMsg] = useStateL({ kind: "", text: "" });
  const [busy, setBusy] = useStateL(false);
  const [done, setDone] = useStateL(false);

  useEffectL(() => {
    const openNow = () => { setShown(true); setOpen(true); };
    if (window.location.hash === "#get-guide") {
      history.replaceState(null, "", window.location.pathname + window.location.search);
      openNow();
      return;
    }
    const dismissed = sessionStorage.getItem("gf_lead_dismissed");
    if (dismissed) { setShown(true); }
    const onScroll = () => {
      if (shown) return;
      if (window.scrollY > 200) {
        setShown(true);
        setTimeout(() => setOpen(true), 400);
        window.removeEventListener("scroll", onScroll);
      }
    };
    const onHash = () => { if (window.location.hash === "#get-guide") { history.replaceState(null, "", window.location.pathname + window.location.search); openNow(); } };
    if (!dismissed) window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("gf:openLead", openNow);
    window.addEventListener("hashchange", onHash);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("gf:openLead", openNow);
      window.removeEventListener("hashchange", onHash);
    };
  }, [shown]);

  const close = () => {
    setOpen(false);
    sessionStorage.setItem("gf_lead_dismissed", "1");
  };

  const submit = async (e) => {
    e.preventDefault();
    const v = email.trim();
    if (!v) return setMsg({ kind: "err", text: "Please enter an email address." });
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return setMsg({ kind: "err", text: "That email doesn't look right." });
    setBusy(true);
    try {
      await window.apiFetch("/leads/guide", {
        method: "POST",
        body: { email: v, source_path: window.location.pathname },
      });
      setBusy(false);
      setDone(true);
      setMsg({ kind: "ok", text: "Check your inbox — your guide is on the way." });
      sessionStorage.setItem("gf_lead_dismissed", "1");
      setTimeout(() => setOpen(false), 2400);
    } catch (err) {
      setBusy(false);
      if (err && err.status === 429) {
        setMsg({ kind: "err", text: "Something went wrong. Please try again in a moment." });
      } else {
        setMsg({ kind: "err", text: "We couldn't record that right now. Please try again later." });
      }
    }
  };

  if (!open) return null;

  return (
    <>
      <div onClick={close} style={{
        position: "fixed", inset: 0, zIndex: 120, background: "rgba(5,6,10,.72)",
        backdropFilter: "blur(6px)", WebkitBackdropFilter: "blur(6px)",
        animation: "gfFade .35s ease",
      }} />
      <div role="dialog" aria-modal="true"
        style={{
          position: "fixed", zIndex: 130, left: "50%", top: "50%", transform: "translate(-50%,-50%)",
          width: "min(920px, 94vw)", maxHeight: "90vh", overflow: "hidden",
          display: "grid", gridTemplateColumns: "0.9fr 1.1fr",
          background: "#0a0b10", border: "1px solid var(--line-strong)",
          boxShadow: "0 40px 100px rgba(0,0,0,.7)",
          animation: "gfPop .35s cubic-bezier(.2,.8,.2,1)",
        }}
        className="gf-lead"
      >
        <div style={{
          position: "relative", overflow: "hidden",
          background: "linear-gradient(180deg,#141010 0%,#241812 55%,#3a2818 100%)",
        }}>
          <div aria-hidden style={{ position: "absolute", inset: 0, background: "repeating-linear-gradient(135deg, rgba(201,169,97,.06) 0 14px, rgba(201,169,97,0) 14px 28px)" }} />
          <div aria-hidden style={{ position: "absolute", inset: 0, background: "radial-gradient(500px 340px at 30% 20%, rgba(201,169,97,.18), transparent 60%)" }} />
          <div style={{ position: "relative", padding: 28, height: "100%", display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
            <span className="mono" style={{ fontSize: 10, letterSpacing: ".3em", color: "var(--gold-2)" }}>FREE GUIDE · PDF</span>
            <div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: ".22em", color: "rgba(242,238,228,.65)" }}>[ 32 PAGES · INSTANT ]</div>
              <div className="serif" style={{ fontSize: 28, lineHeight: 1.08, marginTop: 12, fontWeight: 400, color: "var(--bone)" }}>
                The Off-Season Playbook
              </div>
            </div>
          </div>
        </div>
        <div style={{ padding: "36px 36px 32px", position: "relative", display: "flex", flexDirection: "column", gap: 16 }}>
          <button onClick={close} aria-label="Close"
            style={{ position: "absolute", right: 14, top: 14, width: 36, height: 36, display: "grid", placeItems: "center" }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2l10 10M12 2L2 12" stroke="#f2eee4" strokeWidth="1.4" strokeLinecap="round"/></svg>
          </button>
          <span className="mono" style={{ fontSize: 11, letterSpacing: ".28em", color: "var(--gold)" }}>WAIT — BEFORE YOU SCROLL</span>
          <h3 className="serif" style={{ fontSize: 30, lineHeight: 1.08, fontWeight: 400, margin: "4px 0 6px", letterSpacing: "-0.01em", color: "var(--bone)" }}>
            Get the free <em style={{ fontStyle: "italic", color: "var(--gold-2)", fontWeight: 300 }}>Off-Season Playbook</em>.
          </h3>
          <p style={{ fontSize: 14, lineHeight: 1.6, color: "var(--soft)", margin: 0 }}>
            The 32-page guide George gives every new athlete — training splits, macros, the bloodwork panel,
            and the twelve rules he wishes every lifter had at twenty-five.
          </p>
          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 8 }}>
            <input type="email" value={email}
              onChange={(e) => { setEmail(e.target.value); if (msg.kind === "err") setMsg({ kind: "", text: "" }); }}
              placeholder="you@domain.com"
              disabled={done || busy}
              style={{
                background: "transparent", border: 0, borderBottom: "1px solid var(--line-strong)",
                padding: "14px 0", fontSize: 18, color: "var(--bone)", outline: "none",
                fontFamily: "Fraunces, serif",
              }} />
            <button type="submit" disabled={done || busy}
              style={{
                marginTop: 6, padding: "16px 22px", letterSpacing: ".18em", fontSize: 12, textTransform: "uppercase",
                background: done ? "var(--gold-3)" : "var(--gold)", color: "#0b0b0d", fontWeight: 600,
                display: "inline-flex", alignItems: "center", gap: 10, justifyContent: "center",
                opacity: busy ? 0.7 : 1, cursor: busy ? "wait" : "pointer",
              }}>
              {done ? "Sent — check your inbox" : busy ? "Sending…" : "Send me the guide"}
              {!done && !busy && <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h12M9 3l4 4-4 4" stroke="#0b0b0d" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
            </button>
            <div aria-live="polite" style={{ minHeight: 20, fontSize: 12, color: msg.kind === "err" ? "#e9a58c" : "var(--gold-2)" }}>{msg.text}</div>
          </form>
          <button onClick={close}
            style={{ alignSelf: "flex-start", fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--muted)", marginTop: -6 }}>
            No thanks, I'll keep scrolling
          </button>
        </div>
      </div>
      <style>{`
        @keyframes gfFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes gfPop { from { opacity: 0; transform: translate(-50%,-46%) scale(.97); } to { opacity: 1; transform: translate(-50%,-50%) scale(1); } }
        @media (max-width: 760px) {
          .gf-lead { grid-template-columns: 1fr !important; }
          .gf-lead > *:first-child { min-height: 140px; }
        }
      `}</style>
    </>
  );
}

Object.assign(window, { LeadPopup });
