/* ============================================================
   EBTR — Newsletter capture: Stefi-voice popup + inline CTA
   ------------------------------------------------------------
   - EBTRNewsletterPopup: fires on 50% scroll OR exit-intent,
     once per visitor (localStorage), never if already subscribed.
   - EBTRInlineCTA: the article-end band — the hottest lead point.
   Both write to window.EBTR_SAVE_SUBSCRIBER (Firestore subscribers),
   one required field (email) + optional first name, GDPR notice + link.
   ============================================================ */

const EBTR_NL_SEEN_KEY = "ebtr_news_popup_seen";
const EBTR_NL_SUB_KEY = "ebtr_subscribed";

function ebtrNlField(extra) {
  return Object.assign({
    fontFamily: "var(--font-body)", fontSize: 15, color: "var(--white)",
    background: "var(--neutral-900)", border: "1px solid var(--border-strong)",
    borderRadius: "var(--radius-sm)", padding: "13px 14px", outline: "none", width: "100%",
    boxSizing: "border-box",
  }, extra || {});
}

/* Resolve the campaign tag for attribution: explicit prop > ?utm_campaign= > current article id > "site" */
function ebtrCampaign(explicit) {
  if (explicit) return explicit;
  try {
    var qs = new URLSearchParams(window.location.search);
    var utm = qs.get("utm_campaign");
    if (utm) return utm;
    var a = qs.get("a");
    if (a) return a;
    var pm = (window.location.pathname || "").match(/\/a\/([^/?#]+)/);
    if (pm) return decodeURIComponent(pm[1]);
  } catch (e) {}
  return "site";
}

/* Shared form: email (required) + first name (optional) + GDPR notice */
function EBTRNewsletterForm({ source, campaign, onDone, buttonLabel }) {
  const [email, setEmail] = React.useState("");
  const [name, setName] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const submit = () => {
    if (!/.+@.+\..+/.test(email)) { setErr("Enter a valid email."); return; }
    setErr(""); setBusy(true);
    try { localStorage.setItem(EBTR_NL_SUB_KEY, "1"); } catch (e) {}
    const p = window.EBTR_SAVE_SUBSCRIBER
      ? window.EBTR_SAVE_SUBSCRIBER({ email: email, name: name, consent: true, source: source || "review", campaign: ebtrCampaign(campaign) })
      : Promise.resolve();
    p.then(function () { onDone && onDone(); }).catch(function () { onDone && onDone(); });
  };
  const onKey = (e) => { if (e.key === "Enter") submit(); };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} onKeyDown={onKey} placeholder="you@work.com" style={ebtrNlField()} />
      <input type="text" value={name} onChange={(e) => setName(e.target.value)} onKeyDown={onKey} placeholder="First name (optional)" style={ebtrNlField({ fontSize: 14 })} />
      {err && <div style={{ fontFamily: "var(--font-ui)", fontSize: 11, color: "var(--ebt-orange)" }}>{err}</div>}
      <button onClick={submit} disabled={busy} style={{ background: "var(--ebt-orange)", border: "none", borderRadius: "var(--radius-sm)", padding: "13px 16px", cursor: "pointer", fontFamily: "var(--font-ui)", fontSize: 11.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--neutral-1000)", opacity: busy ? 0.6 : 1 }}>
        {busy ? "Sending…" : (buttonLabel || "Get it in my inbox")}
      </button>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, lineHeight: 1.5, color: "var(--text-muted)" }}>
        One email every other week. Unsubscribe anytime. We send a confirmation link first — see our <a href="https://www.ebthub.com/privacy-policy" target="_blank" rel="noopener" style={{ color: "var(--blue-400)" }}>privacy policy</a>.
      </div>
    </div>
  );
}

/* Small AI-disclosure line — Stefi transparency */
function EBTRStefiNote() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 16 }}>
      <span style={{ fontFamily: "var(--font-ui)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--neutral-1000)", background: "var(--ebt-purple)", padding: "3px 8px", flex: "none" }}>AI</span>
      <span style={{ fontFamily: "var(--font-body)", fontSize: 11.5, lineHeight: 1.5, color: "var(--text-muted)" }}>Hosted by Stefi, EBTHub's disclosed AI persona. Edited by humans.</span>
    </div>
  );
}

/* ---- The exit/scroll popup ---- */
function EBTRNewsletterPopup() {
  const [open, setOpen] = React.useState(false);
  const [done, setDone] = React.useState(false);

  const dismiss = React.useCallback(function () {
    setOpen(false);
    try { localStorage.setItem(EBTR_NL_SEEN_KEY, "1"); } catch (e) {}
  }, []);

  React.useEffect(function () {
    let seen = false, subbed = false;
    try { seen = !!localStorage.getItem(EBTR_NL_SEEN_KEY); subbed = !!localStorage.getItem(EBTR_NL_SUB_KEY); } catch (e) {}
    if (seen || subbed) return;

    let fired = false;
    const fire = function () {
      if (fired) return; fired = true;
      setOpen(true);
      cleanup();
    };
    const onScroll = function () {
      const h = document.documentElement;
      const scrolled = (h.scrollTop || document.body.scrollTop);
      const height = (h.scrollHeight - h.clientHeight) || 1;
      if (scrolled / height >= 0.5) fire();
    };
    const onExit = function (e) {
      if (e.clientY <= 0) fire();
    };
    const t = setTimeout(function () { document.addEventListener("mouseout", onExit); }, 8000); // arm exit-intent after 8s
    window.addEventListener("scroll", onScroll, { passive: true });
    function cleanup() {
      clearTimeout(t);
      window.removeEventListener("scroll", onScroll);
      document.removeEventListener("mouseout", onExit);
    }
    return cleanup;
  }, []);

  React.useEffect(function () {
    const onKey = function (e) { if (e.key === "Escape") dismiss(); };
    if (open) window.addEventListener("keydown", onKey);
    return function () { window.removeEventListener("keydown", onKey); };
  }, [open, dismiss]);

  if (!open) return null;
  return (
    <div onClick={dismiss} style={{ position: "fixed", inset: 0, zIndex: 90, background: "rgba(10,9,9,0.72)", backdropFilter: "blur(3px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ position: "relative", width: "100%", maxWidth: 460, background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderTop: "3px solid var(--ebt-purple)", padding: "clamp(26px,5vw,40px)", boxShadow: "0 30px 80px rgba(0,0,0,0.5)" }}>
        <button onClick={dismiss} aria-label="Close" style={{ position: "absolute", top: 14, right: 14, width: 30, height: 30, borderRadius: "50%", border: "1px solid var(--border-strong)", background: "none", color: "var(--text-muted)", cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12" /></svg>
        </button>
        {done ? (
          <div style={{ textAlign: "center", padding: "10px 0" }}>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ebt-purple)", marginBottom: 12 }}>Almost there</div>
            <h3 style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 23, color: "var(--white)", margin: "0 0 12px" }}>Check your inbox.</h3>
            <p style={{ fontFamily: "var(--font-body)", fontSize: 15, lineHeight: 1.6, color: "var(--text-secondary)", margin: 0 }}>I've sent a confirmation link. Click it, and you're in. — Stefi</p>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ebt-purple)", marginBottom: 14 }}>The Review Newsletter</div>
            <h3 style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: "clamp(22px,3vw,27px)", lineHeight: 1.15, color: "var(--white)", margin: "0 0 12px", textWrap: "balance" }}>I don't exist.<br />This newsletter does.</h3>
            <p style={{ fontFamily: "var(--font-body)", fontSize: 15.5, lineHeight: 1.6, color: "var(--text-secondary)", margin: "0 0 20px" }}>Every other week: the research — and the part the careful people leave out. No fluff, no schedule-filler.</p>
            <EBTRNewsletterForm source="review-popup" buttonLabel="Get it in my inbox" onDone={() => setDone(true)} />
            <EBTRStefiNote />
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

/* ---- Article-end inline CTA — the hottest lead point ---- */
function EBTRInlineCTA({ campaign }) {
  const [done, setDone] = React.useState(false);
  return (
    <div style={{ margin: "8px 0 40px", border: "1px solid var(--border-hairline)", borderLeft: "3px solid var(--ebt-purple)", background: "var(--surface-raised)", padding: "clamp(24px,4vw,34px)" }}>
      {done ? (
        <div>
          <h3 style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 21, color: "var(--white)", margin: "0 0 8px" }}>You're on the list.</h3>
          <p style={{ fontFamily: "var(--font-body)", fontSize: 14.5, lineHeight: 1.6, color: "var(--text-secondary)", margin: 0 }}>Confirmation link sent — click it and I'll start sending. — Stefi</p>
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 32, alignItems: "center" }} className="ebtr-inlinecta">
          <div>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ebt-purple)", marginBottom: 12 }}>Before you go</div>
            <h3 style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: "clamp(20px,2.4vw,25px)", lineHeight: 1.18, color: "var(--white)", margin: "0 0 10px", textWrap: "balance" }}>Subscribe, and I'll put the part they missed in your inbox.</h3>
            <p style={{ fontFamily: "var(--font-body)", fontSize: 14.5, lineHeight: 1.6, color: "var(--text-secondary)", margin: 0 }}>You read to the end — you're exactly who this is for. Every other week, the evidence and the uncomfortable bit. — Stefi</p>
          </div>
          <EBTRNewsletterForm source="review-inline" campaign={campaign} buttonLabel="Get it in my inbox" onDone={() => setDone(true)} />
        </div>
      )}
    </div>
  );
}

Object.assign(window, { EBTRNewsletterPopup, EBTRInlineCTA, EBTRNewsletterForm });
