/* Orenwell — transparent pricing menu (shared UI).
   Reads window.OW_PRICING[slug] and renders a by-product, by-supply-length menu.
   Used identically on the marketing-site category pages and the conversion landing
   pages, so the same product always shows the same price. Relies on the global
   Badge + Icon primitives (declared in _primitives.jsx, loaded before this file).
   Compliance: provider-personalized framing, ® on brand names, TRT = Coming Soon. */

/* One supply-length chip — duration, total, optional per-month equivalent. */
function OWTier({ dur, total, per, muted }) {
  var isMonthly = per === "/mo";
  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--white)",
      padding: "9px 14px", minWidth: 84, textAlign: "center" }}>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.11em", textTransform: "uppercase",
        color: "var(--gray-500)", marginBottom: 5 }}>{dur}</div>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 19, lineHeight: 1,
        color: muted ? "var(--gray-600)" : "var(--teal-700)" }}>
        {total}{isMonthly ? <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--gray-500)" }}>/mo</span> : null}
      </div>
      {per && !isMonthly
        ? <div style={{ fontSize: 11.5, color: "var(--amber-700)", fontWeight: 600, marginTop: 5 }}>{per}</div>
        : null}
    </div>
  );
}

/* ---- Part A: "Learn More" expandable panel (labeled region) ---- */
function OWLearnContent({ det, panelId, labelId, hidden }) {
  var head = { fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--amber-700)", margin: "0 0 6px" };
  var para = { fontSize: 14, color: "var(--gray-600)", lineHeight: 1.6, margin: 0 };
  var list = { margin: "4px 0 0", padding: "0 0 0 18px", display: "flex", flexDirection: "column", gap: 4 };
  var li = { fontSize: 13.5, color: "var(--ink-800)", lineHeight: 1.5 };
  return (
    <div id={panelId} role="region" aria-labelledby={labelId} hidden={hidden}
      style={{ marginTop: 14, paddingTop: 16, borderTop: "1px solid var(--border)", display: hidden ? "none" : "flex", flexDirection: "column", gap: 15 }}>
      {det.summary ? <p style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 16, color: "var(--teal-700)", lineHeight: 1.4, margin: 0 }}>{det.summary}</p> : null}
      <div>
        <div style={head}>How it works</div>
        <p style={para}>{det.howItWorks}</p>
      </div>
      <div>
        <div style={head}>Benefits</div>
        <ul style={list}>{det.benefits.map(function (b, i) { return <li key={i} style={li}>{b}</li>; })}</ul>
      </div>
      <div>
        <div style={head}>Important considerations</div>
        <ul style={list}>{det.considerations.map(function (b, i) { return <li key={i} style={li}>{b}</li>; })}</ul>
      </div>
    </div>
  );
}

/* ---- Parts A + B: the per-product action row (Learn More toggle + Get Started). ----
   Get Started lives ABOVE the panel, so expanding never pushes it out of reach. The
   button carries the three data-* attributes the capture modal reads (Part B). */
function OWProductActions({ name }) {
  var det = (window.OW_PRODUCT_DETAILS || {})[name];
  var os = React.useState(false); var open = os[0], setOpen = os[1];
  var uid = React.useId();
  if (!det) return null;
  var panelId = "owlm-" + uid.replace(/[:]/g, "");
  var labelId = panelId + "-label";
  function start(e) {
    var d = e.currentTarget.dataset;
    if (window.owOpenCapture) window.owOpenCapture({ intakeUrl: d.intakeUrl, interest: d.interest, product: d.product });
  }
  return (
    <React.Fragment>
      <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: "10px 14px", marginTop: 14 }}>
        <button type="button" id={labelId} onClick={function () { setOpen(!open); }} aria-expanded={open} aria-controls={panelId}
          style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", padding: "4px 0", cursor: "pointer",
            color: "var(--teal-700)", fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 600, textAlign: "left" }}>
          {open ? "Hide details" : "Learn more about this medication"}
          <Icon name={open ? "chevron-up" : "arrow-right"} size={15} color="var(--teal-700)" stroke={2} />
        </button>
        <Button variant="primary" size="sm" data-intake-url={det.intakeUrl} data-interest={det.interest} data-product={name}
          onClick={start} iconRight={<Icon name="arrow-right" size={16} color="#fff" />}>Get Started</Button>
      </div>
      <OWLearnContent det={det} panelId={panelId} labelId={labelId} hidden={!open} />
    </React.Fragment>
  );
}

/* One product row — name (+ optional descriptor) + supply-length chips, then the
   Learn More / Get Started action row and its expandable description panel. */
function OWPriceRow({ item }) {
  var feature = !!item.feature;
  return (
    <div style={{
      border: feature ? "1.5px solid var(--amber-400)" : "1px solid var(--border)",
      background: feature ? "var(--cream)" : "var(--white)",
      borderRadius: "var(--radius-lg)", padding: "16px 18px",
      boxShadow: feature ? "none" : "var(--shadow-card)" }}>
      <div style={{ display: "flex", flexWrap: "wrap", gap: "12px 18px", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ flex: "1 1 200px", minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, flexWrap: "wrap" }}>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 19, color: "var(--ink-800)", lineHeight: 1.15 }}>{item.name}</span>
            {feature ? <Badge variant="amber">Most popular</Badge> : null}
          </div>
          {item.sub ? <div style={{ fontSize: 13, color: "var(--gray-600)", marginTop: 4 }}>{item.sub}</div> : null}
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "flex-start" }}>
          {item.tiers.map(function (t, i) { return <OWTier key={i} dur={t.dur} total={t.total} per={t.per} />; })}
        </div>
      </div>
      <OWProductActions name={item.name} />
    </div>
  );
}

/* A labeled text/email/tel field for the inline TRT waitlist (Part C). */
function OWWaitField({ id, label, type, value, onChange, error, optional, autoComplete, inputMode }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <label htmlFor={id} style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink-800)" }}>
        {label}{optional ? <span style={{ fontWeight: 500, color: "var(--gray-500)" }}>  (optional)</span> : null}
      </label>
      <input id={id} type={type || "text"} value={value} onChange={function (e) { onChange(e.target.value); }}
        required={!optional} aria-required={optional ? undefined : "true"} autoComplete={autoComplete} inputMode={inputMode}
        aria-invalid={error ? "true" : undefined} aria-describedby={error ? 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)", width: "100%", boxSizing: "border-box",
          border: "1.5px solid " + (error ? "var(--danger, #C2483B)" : "var(--border)"), outline: "none" }} />
      {error ? <span id={id + "-err"} style={{ fontSize: 12.5, color: "var(--danger, #C2483B)", fontWeight: 500 }}>{error}</span> : null}
    </div>
  );
}

/* TRT "Coming Soon" — no price. "Notify Me" expands an inline waitlist form that
   POSTs to /api/lead (interest "Men's Health & TRT", landingProduct "TRT Waitlist").
   On success it confirms in place — no redirect (there's no intake yet). */
function OWComingSoon({ data }) {
  var EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
  var os = React.useState(false); var open = os[0], setOpen = os[1];
  var fs = React.useState({ firstName: "", lastName: "", email: "", phone: "", chdConsent: false, company_website: "" });
  var form = fs[0], setForm = fs[1];
  var er = React.useState({}); var errs = er[0], setErrs = er[1];
  var ms = React.useState(null); var msg = ms[0], setMsg = ms[1];
  var sub = React.useState(false); var submitting = sub[0], setSubmitting = sub[1];
  var dn = React.useState(false); var done = dn[0], setDone = dn[1];
  function up(k, v) { setForm(function (p) { var n = Object.assign({}, p); n[k] = v; return n; }); }

  function submit(e) {
    e.preventDefault();
    if (submitting) return;
    if (form.company_website) { setDone(true); return; } // honeypot: bot
    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) { setMsg(null); return; }
    setSubmitting(true); setMsg(null);
    var payload = window.owBuildLead({
      firstName: form.firstName.trim(), lastName: form.lastName.trim(), email: form.email.trim(), phone: form.phone.trim(),
      interest: "Men's Health & TRT", marketingOptIn: false, landingProduct: "TRT Waitlist", company_website: form.company_website,
    });
    window.owSubmitLead(payload).then(function (r) {
      if (r.status === 200) { setDone(true); return; }
      setSubmitting(false);
      if (r.status === 400) { setMsg("Please check your name and email and try again."); return; }
      if (r.status === 429) { setMsg("One moment — please try again in a few seconds."); return; }
      setMsg("Something went wrong — please try again in a few moments.");
    });
  }

  var chdHref = "/consumer-health-data-privacy";

  return (
    <div style={{ border: "1px solid var(--teal-200)", background: "var(--teal-50)",
      borderRadius: "var(--radius-lg)", padding: "22px 22px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 11, flexWrap: "wrap", marginBottom: 10 }}>
        <Badge variant="teal" dot>Coming soon</Badge>
        <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 21, color: "var(--teal-700)" }}>{data.title}</span>
      </div>
      <p style={{ fontSize: 15, color: "var(--gray-600)", lineHeight: 1.55, margin: "0 0 16px", maxWidth: 500 }}>{data.body}</p>

      {done ? (
        <div role="status" style={{ display: "flex", alignItems: "flex-start", gap: 9, fontSize: 15, fontWeight: 600, color: "var(--teal-700)", lineHeight: 1.5 }}>
          <Icon name="check-circle" size={19} color="var(--teal-700)" stroke={2} />
          <span>You&rsquo;re on the list &mdash; we&rsquo;ll email you the moment TRT launches.</span>
        </div>
      ) : !open ? (
        <Button variant="primary" size="md" onClick={function () { setOpen(true); }}
          iconRight={<Icon name="bell" size={16} color="#fff" stroke={1.9} />}>Notify me</Button>
      ) : (
        <form onSubmit={submit} noValidate style={{ display: "flex", flexDirection: "column", gap: 13, maxWidth: 480 }}>
          <p style={{ fontSize: 12, color: "var(--gray-500)", margin: 0 }}>All fields are required unless marked optional.</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <OWWaitField id="ow-trt-firstName" label="First name" value={form.firstName} onChange={function (v) { up("firstName", v); }} error={errs.firstName} autoComplete="given-name" />
            <OWWaitField id="ow-trt-lastName" label="Last name" value={form.lastName} onChange={function (v) { up("lastName", v); }} error={errs.lastName} autoComplete="family-name" />
          </div>
          <OWWaitField id="ow-trt-email" label="Email" type="email" value={form.email} onChange={function (v) { up("email", v); }} error={errs.email} autoComplete="email" inputMode="email" />
          <OWWaitField id="ow-trt-phone" label="Phone" type="tel" value={form.phone} onChange={function (v) { up("phone", v); }} optional autoComplete="tel" inputMode="tel" />

          {/* Honeypot */}
          <div aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, overflow: "hidden" }}>
            <label htmlFor="company_website_trt">Company website</label>
            <input id="company_website_trt" name="company_website" type="text" tabIndex={-1} autoComplete="off" value={form.company_website} onChange={function (e) { up("company_website", e.target.value); }} />
          </div>

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

          {msg ? <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" }}>{msg}</div> : null}

          <div>
            <Button type="submit" variant="primary" size="md" disabled={!form.chdConsent || submitting}
              style={(!form.chdConsent || submitting) ? { opacity: 0.5, cursor: "not-allowed" } : {}}
              iconRight={submitting ? null : <Icon name="bell" size={16} color="#fff" stroke={1.9} />}>
              {submitting ? "Submitting…" : "Join the waitlist"}
            </Button>
          </div>
        </form>
      )}
    </div>
  );
}

/* Brand-name pens block — lower-emphasis, dashed container. Each pen is a row with
   its own Learn More expander + Get Started (routes to the generic weight-loss intake). */
function OWBrandRow({ it }) {
  return (
    <div style={{ padding: "13px 15px", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--white)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
        <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 17, color: "var(--ink-800)" }}>{it.name}</span>
        <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16, color: "var(--gray-600)", whiteSpace: "nowrap" }}>
          {it.tiers[0].total}<span style={{ fontSize: 12, fontWeight: 600 }}>/mo</span>
        </span>
      </div>
      <OWProductActions name={it.name} />
    </div>
  );
}

function OWBrandBlock({ data }) {
  return (
    <div style={{ marginTop: 6, border: "1px dashed var(--gray-300)", borderRadius: "var(--radius-lg)",
      background: "var(--off-white)", padding: "20px 22px" }}>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18, color: "var(--ink-800)", marginBottom: 5 }}>{data.title}</div>
      <p style={{ fontSize: 13.5, color: "var(--gray-600)", lineHeight: 1.55, margin: "0 0 16px", maxWidth: 540 }}>{data.note}</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {data.items.map(function (it, i) { return <OWBrandRow key={i} it={it} />; })}
      </div>
    </div>
  );
}

/* Optional group heading (e.g. "Compounded options", "ED treatments"). */
function OWGroupHead({ title, subtitle }) {
  if (!title) return null;
  return (
    <div style={{ margin: "6px 2px 2px" }}>
      <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 22, color: "var(--teal-700)", margin: 0 }}>{title}</h3>
      {subtitle ? <p style={{ fontSize: 14, color: "var(--gray-600)", lineHeight: 1.5, margin: "6px 0 0", maxWidth: 540 }}>{subtitle}</p> : null}
    </div>
  );
}

/* Full menu for a category slug. */
function PriceMenu({ slug }) {
  var data = (window.OW_PRICING || {})[slug];
  if (!data) return null;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12, textAlign: "left" }}>
      {data.comingSoon ? <OWComingSoon data={data.comingSoon} /> : null}
      {data.groups.map(function (g, gi) {
        return (
          <React.Fragment key={gi}>
            <OWGroupHead title={g.title} subtitle={g.subtitle} />
            {g.items.map(function (it, i) { return <OWPriceRow key={i} item={it} />; })}
          </React.Fragment>
        );
      })}
      {data.brand ? <OWBrandBlock data={data.brand} /> : null}
      <p style={{ fontSize: 12.5, color: "var(--gray-500)", lineHeight: 1.6, margin: "8px 2px 0" }}>
        All plans are prescribed and personalized by a licensed provider; eligibility is determined by your provider.
        You'll see your exact, all-in price before you commit — no hidden fees, cancel anytime.
      </p>
    </div>
  );
}

Object.assign(window, { PriceMenu, OWTier, OWPriceRow, OWComingSoon, OWBrandBlock, OWProductActions, OWLearnContent });
