/* Orenwell — lead capture (Parts B & C).
   Loaded on every product/category page and every landing page, AFTER React +
   ReactDOM + _primitives.jsx (for the shared Button/Icon) and pricing-ui.jsx.

   Exposes:
     window.owOpenCapture({ intakeUrl, interest, product })
        Part B trigger. If the visitor already converted this session
        (sessionStorage.orenwell_lead_captured === "true"), skips the modal and
        routes straight to intakeUrl + &email=<stored email>. Otherwise opens the
        capture modal (focus-trapped, Esc-closable, WCAG AA).
     window.owSubmitLead(payload)  -> { status, networkError }   (used by Part C too)
     window.owBuildLead, owGetUtms, owMarkCaptured, owRedirectIntake, owDocHref

   UTM capture: on load, utm_source/medium/campaign/term/content are read from the
   URL query and stored in sessionStorage so they survive in-session navigation.
   The form always reads from sessionStorage (fallback to the current URL), sending
   empty strings when absent. Backend: POST /api/lead, application/json, exact field
   names (UTMs snake_case). 200 => proceed; 400/429 => inline message; network/
   timeout (~6s) => still route to intake so the path to care is never blocked. */

(function () {
  var CONSENT_VERSION = "v1-2026-06-22";
  var UTM_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];

  /* ---- UTM capture / retrieval ---- */
  function owCaptureUtms() {
    try {
      var q = new URLSearchParams(window.location.search);
      UTM_KEYS.forEach(function (k) {
        var v = q.get(k);
        if (v !== null) { try { sessionStorage.setItem("ow_" + k, v); } catch (e) {} }
      });
    } catch (e) {}
  }
  function owGetUtms() {
    var q = null;
    try { q = new URLSearchParams(window.location.search); } catch (e) {}
    var out = {};
    UTM_KEYS.forEach(function (k) {
      var v = null;
      try { v = sessionStorage.getItem("ow_" + k); } catch (e) {}
      if (v === null && q) v = q.get(k);
      out[k] = v || "";
    });
    return out;
  }

  /* ---- session conversion state ---- */
  function owIsCaptured() {
    try { return sessionStorage.getItem("orenwell_lead_captured") === "true"; } catch (e) { return false; }
  }
  function owStoredEmail() {
    try { return sessionStorage.getItem("orenwell_lead_email") || ""; } catch (e) { return ""; }
  }
  function owMarkCaptured(email) {
    try {
      sessionStorage.setItem("orenwell_lead_captured", "true");
      if (email) sessionStorage.setItem("orenwell_lead_email", email);
    } catch (e) {}
  }

  /* ---- intake handoff ---- */
  function owRedirectIntake(intakeUrl, email) {
    if (!intakeUrl) return;
    var sep = intakeUrl.indexOf("?") === -1 ? "?" : "&";
    window.location.href = intakeUrl + sep + "email=" + encodeURIComponent(email || "");
  }

  /* ---- relative doc href (works from root LPs and ui_kits/marketing-site) ---- */
  function owDocHref(file) {
    return (window.location.pathname.indexOf("/ui_kits/marketing-site/") !== -1 ? "../../" : "") + file;
  }

  /* ---- payload + POST ---- */
  function owBuildLead(f) {
    var utm = owGetUtms();
    return {
      firstName: f.firstName, lastName: f.lastName, email: f.email, phone: f.phone || "",
      interest: f.interest,
      marketingOptIn: !!f.marketingOptIn,
      chdConsent: true,
      consentVersion: CONSENT_VERSION,
      sourceUrl: window.location.href,
      utm_source: utm.utm_source, utm_medium: utm.utm_medium, utm_campaign: utm.utm_campaign,
      utm_term: utm.utm_term, utm_content: utm.utm_content,
      landingProduct: f.landingProduct,
      company_website: f.company_website || "",
    };
  }
  function owSubmitLead(payload) {
    var ctrl = (typeof AbortController !== "undefined") ? new AbortController() : null;
    var timer = setTimeout(function () { if (ctrl) ctrl.abort(); }, 6000);
    return fetch("/api/lead", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
      signal: ctrl ? ctrl.signal : undefined,
    }).then(function (res) {
      clearTimeout(timer);
      return { status: res.status, networkError: false };
    }).catch(function () {
      clearTimeout(timer);
      return { status: 0, networkError: true };
    });
  }

  var EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

  /* ============================ Capture modal (Part B) ============================ */
  function LeadField(props) {
    var id = props.id, err = props.error;
    return (
      React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
        React.createElement("label", { htmlFor: id, style: { fontSize: 13.5, fontWeight: 600, color: "var(--ink-800)" } },
          props.label,
          props.optional ? React.createElement("span", { style: { fontWeight: 500, color: "var(--gray-500)" } }, "  (optional)") : null
        ),
        React.createElement("input", {
          id: id, type: props.type || "text", value: props.value,
          onChange: function (e) { props.onChange(e.target.value); },
          required: !props.optional, "aria-required": props.optional ? undefined : "true", autoComplete: props.autoComplete,
          inputMode: props.inputMode,
          "aria-invalid": err ? "true" : undefined,
          "aria-describedby": err ? id + "-err" : undefined,
          style: {
            padding: "11px 13px", borderRadius: "var(--radius-md)", fontFamily: "var(--font-body)",
            fontSize: 15.5, color: "var(--ink-800)", background: "var(--white)",
            border: "1.5px solid " + (err ? "var(--danger, #C2483B)" : "var(--border)"), outline: "none", width: "100%", boxSizing: "border-box",
          },
        }),
        err ? React.createElement("span", { id: id + "-err", style: { fontSize: 12.5, color: "var(--danger, #C2483B)", fontWeight: 500 } }, err) : null
      )
    );
  }

  function LeadCaptureModal(props) {
    var opts = props.opts, onClose = props.onClose;
    var s = React.useState({ firstName: "", lastName: "", email: "", phone: "", marketingOptIn: false, chdConsent: false, company_website: "" });
    var form = s[0], setForm = s[1];
    var es = React.useState({}); var errs = es[0], setErrs = es[1];
    var ms = React.useState(null); var formMsg = ms[0], setFormMsg = ms[1];
    var ss = React.useState(false); var submitting = ss[0], setSubmitting = ss[1];
    var dialogRef = React.useRef(null);
    var firstRef = React.useRef(null);
    var titleId = React.useId();
    var descId = React.useId();

    function up(k, v) { setForm(function (p) { var n = Object.assign({}, p); n[k] = v; return n; }); }

    // Focus first field on open; restore focus to the trigger on close.
    React.useEffect(function () {
      var prev = document.activeElement;
      if (firstRef.current) firstRef.current.focus();
      var html = document.documentElement;
      var prevOverflow = html.style.overflow;
      html.style.overflow = "hidden";
      // Make the rest of the page inert while the dialog is open (background not interactive / hidden from AT).
      var appRoot = document.getElementById("root");
      if (appRoot) { appRoot.setAttribute("inert", ""); appRoot.setAttribute("aria-hidden", "true"); }
      return function () {
        html.style.overflow = prevOverflow;
        if (appRoot) { appRoot.removeAttribute("inert"); appRoot.removeAttribute("aria-hidden"); }
        if (prev && prev.focus) { try { prev.focus(); } catch (e) {} }
      };
    }, []);

    function onKeyDown(e) {
      if (e.key === "Escape") { e.stopPropagation(); onClose(); return; }
      if (e.key !== "Tab") return;
      var root = dialogRef.current; if (!root) return;
      var f = root.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), [tabindex]:not([tabindex="-1"])');
      var list = Array.prototype.filter.call(f, function (el) { return el.offsetParent !== null || el === document.activeElement; });
      if (!list.length) return;
      var first = list[0], last = list[list.length - 1];
      if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
      else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
    }

    function submit(e) {
      e.preventDefault();
      if (submitting) return;
      // Honeypot — a filled hidden field means a bot; quietly succeed without posting.
      if (form.company_website) { onClose(); return; }
      var ne = {};
      if (!form.firstName.trim()) ne.firstName = "Please enter your first name.";
      if (!form.lastName.trim()) ne.lastName = "Please enter your last name.";
      if (!form.email.trim() || !EMAIL_RE.test(form.email.trim())) ne.email = "Please enter a valid email address.";
      setErrs(ne);
      if (Object.keys(ne).length) {
        setFormMsg(null);
        var fid = ne.firstName ? "ow-cap-firstName" : ne.lastName ? "ow-cap-lastName" : "ow-cap-email";
        var el = document.getElementById(fid); if (el) el.focus();
        return;
      }
      setSubmitting(true); setFormMsg(null);
      var email = form.email.trim();
      var payload = owBuildLead({
        firstName: form.firstName.trim(), lastName: form.lastName.trim(), email: email, phone: form.phone.trim(),
        interest: opts.interest, marketingOptIn: form.marketingOptIn, landingProduct: opts.product, company_website: form.company_website,
      });
      owSubmitLead(payload).then(function (r) {
        if (r.status === 200) { owMarkCaptured(email); owRedirectIntake(opts.intakeUrl, email); return; }
        if (r.status === 400) { setSubmitting(false); setFormMsg("Please check your name and email and try again."); return; }
        if (r.status === 429) { setSubmitting(false); setFormMsg("One moment — please try again in a few seconds."); return; }
        // Network error / timeout / other — never block the path to care.
        owRedirectIntake(opts.intakeUrl, email);
      });
    }

    var chdHref = "/consumer-health-data-privacy";
    var canSubmit = form.chdConsent && !submitting;

    return (
      React.createElement("div", {
        onMouseDown: function (e) { if (e.target === e.currentTarget) onClose(); },
        onKeyDown: onKeyDown,
        style: {
          position: "fixed", inset: 0, zIndex: 1000, background: "rgba(20,32,30,.55)",
          backdropFilter: "blur(3px)", WebkitBackdropFilter: "blur(3px)",
          display: "flex", alignItems: "flex-start", justifyContent: "center",
          padding: "max(16px, 4vh) 16px", overflowY: "auto",
        },
      },
        React.createElement("div", {
          ref: dialogRef, role: "dialog", "aria-modal": "true", "aria-labelledby": titleId, "aria-describedby": descId,
          style: {
            width: "100%", maxWidth: 460, background: "var(--white)", borderRadius: "var(--radius-lg)",
            boxShadow: "var(--shadow-lg)", padding: "26px 24px 24px", boxSizing: "border-box", position: "relative",
            fontFamily: "var(--font-body)",
          },
        },
          /* Close */
          React.createElement("button", {
            type: "button", onClick: onClose, "aria-label": "Close",
            style: {
              position: "absolute", top: 14, right: 14, width: 34, height: 34, borderRadius: "var(--radius-md)",
              border: "1px solid var(--border)", background: "var(--white)", color: "var(--gray-600)",
              display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
            },
          }, React.createElement(window.Icon, { name: "x", size: 18, color: "var(--gray-600)", stroke: 1.9 })),

          React.createElement("div", { style: { fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 600, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--amber-700)", marginBottom: 8 } }, "Get started"),
          React.createElement("h2", { id: titleId, style: { fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 25, lineHeight: 1.12, color: "var(--teal-700)", margin: "0 0 6px", paddingRight: 30 } }, "Let’s see if you qualify"),
          React.createElement("p", { id: descId, style: { fontSize: 14, color: "var(--gray-600)", lineHeight: 1.55, margin: "0 0 16px" } }, "A few details and we’ll connect you with a licensed provider. Eligibility is determined by your provider."),

          /* Read-only product line */
          React.createElement("div", {
            style: {
              display: "flex", alignItems: "center", gap: 9, padding: "10px 13px", marginBottom: 16,
              background: "var(--teal-50)", border: "1px solid var(--teal-200)", borderRadius: "var(--radius-md)",
            },
          },
            React.createElement(window.Icon, { name: "pill", size: 16, color: "var(--teal-700)", stroke: 1.7 }),
            React.createElement("span", { style: { fontSize: 14, color: "var(--gray-600)" } }, "Selected: ",
              React.createElement("span", { style: { fontWeight: 600, color: "var(--ink-800)" } }, opts.product))
          ),

          React.createElement("form", { onSubmit: submit, noValidate: true, style: { display: "flex", flexDirection: "column", gap: 14 } },
            React.createElement("p", { style: { fontSize: 12, color: "var(--gray-500)", margin: 0 } }, "All fields are required unless marked optional."),
            React.createElement("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 } },
              React.createElement("div", { ref: function (n) { if (n) firstRef.current = n.querySelector("input"); } },
                React.createElement(LeadField, { id: "ow-cap-firstName", label: "First name", value: form.firstName, onChange: function (v) { up("firstName", v); }, error: errs.firstName, autoComplete: "given-name" })
              ),
              React.createElement(LeadField, { id: "ow-cap-lastName", label: "Last name", value: form.lastName, onChange: function (v) { up("lastName", v); }, error: errs.lastName, autoComplete: "family-name" })
            ),
            React.createElement(LeadField, { id: "ow-cap-email", label: "Email", type: "email", value: form.email, onChange: function (v) { up("email", v); }, error: errs.email, autoComplete: "email", inputMode: "email" }),
            React.createElement(LeadField, { id: "ow-cap-phone", label: "Phone", type: "tel", value: form.phone, onChange: function (v) { up("phone", v); }, optional: true, autoComplete: "tel", inputMode: "tel" }),

            /* Honeypot — off-screen, not announced, not tabbable */
            React.createElement("div", { "aria-hidden": "true", style: { position: "absolute", left: "-9999px", top: "auto", width: 1, height: 1, overflow: "hidden" } },
              React.createElement("label", { htmlFor: "company_website" }, "Company website"),
              React.createElement("input", { id: "company_website", name: "company_website", type: "text", tabIndex: -1, autoComplete: "off", value: form.company_website, onChange: function (e) { up("company_website", e.target.value); } })
            ),

            /* Marketing opt-in */
            React.createElement("label", { style: { display: "flex", gap: 10, alignItems: "flex-start", cursor: "pointer", fontSize: 13.5, color: "var(--gray-600)", lineHeight: 1.5 } },
              React.createElement("input", { type: "checkbox", checked: form.marketingOptIn, onChange: function (e) { up("marketingOptIn", e.target.checked); }, style: { marginTop: 2, width: 17, height: 17, flexShrink: 0, accentColor: "var(--teal-700)" } }),
              React.createElement("span", null, "Keep me posted with occasional tips and offers from Orenwell.")
            ),

            /* CHD consent (required) */
            React.createElement("label", { htmlFor: "ow-cap-chd", style: { display: "flex", gap: 10, alignItems: "flex-start", cursor: "pointer", fontSize: 13, color: "var(--ink-800)", lineHeight: 1.5, background: "var(--off-white)", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", padding: "12px 13px" } },
              React.createElement("input", { id: "ow-cap-chd", type: "checkbox", checked: form.chdConsent, onChange: function (e) { up("chdConsent", e.target.checked); }, required: true, style: { marginTop: 2, width: 17, height: 17, flexShrink: 0, accentColor: "var(--teal-700)" } }),
              React.createElement("span", null,
                "I have read and agree to the ",
                React.createElement("a", { href: chdHref, target: "_blank", rel: "noopener noreferrer", style: { color: "var(--teal-700)", fontWeight: 600 } }, "Consumer Health Data Privacy Policy", React.createElement("span", { className: "ow-vh" }, " (opens in new tab)")),
                " and ",
                React.createElement("a", { href: "#", style: { color: "var(--teal-700)", fontWeight: 600 } }, "Privacy Policy"),
                ", and consent to Orenwell processing my health-related information to connect me with a licensed provider."
              )
            ),

            formMsg ? React.createElement("div", { role: "alert", style: { fontSize: 13.5, fontWeight: 500, color: "var(--danger, #C2483B)", background: "var(--danger-bg, #FBEEEC)", border: "1px solid var(--danger, #C2483B)", borderRadius: "var(--radius-md)", padding: "10px 12px" } }, formMsg) : null,

            React.createElement(window.Button, {
              type: "submit", variant: "primary", size: "lg", fullWidth: true, disabled: !canSubmit,
              style: canSubmit ? {} : { opacity: 0.5, cursor: "not-allowed" },
              iconRight: submitting ? null : React.createElement(window.Icon, { name: "arrow-right", size: 18, color: "#fff" }),
            }, submitting ? "Submitting…" : "Continue"),

            React.createElement("p", { style: { fontSize: 11.5, color: "var(--gray-500)", lineHeight: 1.55, margin: 0, textAlign: "center" } }, "Your information is kept private. You’ll continue to a secure online visit.")
          )
        )
      )
    );
  }

  /* ---- controller: one root, opened via window.owOpenCapture ---- */
  var _open = null;
  function LeadCaptureController() {
    var st = React.useState(null); var opts = st[0], setOpts = st[1];
    React.useEffect(function () { _open = setOpts; return function () { _open = null; }; }, []);
    if (!opts) return null;
    return React.createElement(LeadCaptureModal, { opts: opts, onClose: function () { setOpts(null); } });
  }

  window.owOpenCapture = function (opts) {
    if (!opts || !opts.intakeUrl) return;
    // Returning visitor this session — skip the modal, go straight to intake.
    if (owIsCaptured()) { owRedirectIntake(opts.intakeUrl, owStoredEmail()); return; }
    if (_open) _open(opts);
  };

  // expose shared helpers (Part C reuses these)
  Object.assign(window, { owBuildLead: owBuildLead, owSubmitLead: owSubmitLead, owGetUtms: owGetUtms, owMarkCaptured: owMarkCaptured, owRedirectIntake: owRedirectIntake, owDocHref: owDocHref, OW_CONSENT_VERSION: CONSENT_VERSION });

  function mount() {
    owCaptureUtms();
    var c = document.getElementById("ow-capture-root");
    if (!c) { c = document.createElement("div"); c.id = "ow-capture-root"; document.body.appendChild(c); }
    ReactDOM.createRoot(c).render(React.createElement(LeadCaptureController));
  }
  if (document.body) mount(); else document.addEventListener("DOMContentLoaded", mount);
})();
