/* global React */
const { useState, useMemo } = React;

function nsoEmailOk(v) {
  if (window.NSOForm && typeof window.NSOForm.isValidEmail === "function") return window.NSOForm.isValidEmail(v);
  return typeof v === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim());
}

function nsoEndpointOk(ep) {
  if (window.NSOForm && typeof window.NSOForm.isConfiguredEndpoint === "function") return window.NSOForm.isConfiguredEndpoint(ep);
  return typeof ep === "string" && ep.length > 0 && ep.indexOf("REPLACE") === -1;
}

function nsoSubmitFormspreeJson(endpoint, obj) {
  if (window.NSOForm && typeof window.NSOForm.submitFormspreeJson === "function") return window.NSOForm.submitFormspreeJson(endpoint, obj);
  return fetch(endpoint, {
    method: "POST",
    headers: { Accept: "application/json", "Content-Type": "application/json" },
    body: JSON.stringify(obj || {}),
  }).then(function (res) {
    return { ok: res.ok, status: res.status };
  });
}

// ─── Brand mark ────────────────────────────────────────────────
function Brandmark({ href = "index.html" }) {
  return (
    <a className="brandmark plain" href={href} aria-label="NeuroSecondOpinion home">
      <span className="dot" aria-hidden="true"></span>
      <span>NeuroSecondOpinion</span>
    </a>
  );
}

// ─── Header ────────────────────────────────────────────────────
function Header({ active }) {
  const N = window.NSO;
  const [open, setOpen] = useState(false);
  const links = N.nav.map(l => (
    <a key={l.label} href={l.href} className={active === l.label ? "active" : ""} onClick={() => setOpen(false)}>{l.label}</a>
  ));
  return (
    <header className="header">
      <div className="container header-inner">
        <Brandmark />
        <nav className="nav-links" aria-label="Primary">
          {links}
          <a href="submit.html" className="btn btn-ghost" style={{padding:"8px 14px"}}>Submit a case</a>
        </nav>
        <button
          type="button"
          className="nav-toggle"
          aria-expanded={open}
          aria-controls="mobile-nav"
          aria-label={open ? "Close menu" : "Open menu"}
          onClick={() => setOpen(o => !o)}
        >
          <span aria-hidden="true">{open ? "Close" : "Menu"}</span>
        </button>
      </div>
      {open && (
        <nav id="mobile-nav" className="nav-mobile" aria-label="Primary mobile">
          {links}
          <a href="submit.html" className="btn btn-primary" onClick={() => setOpen(false)}>Submit a case</a>
        </nav>
      )}
    </header>
  );
}

// ─── Footer ────────────────────────────────────────────────────
function Footer() {
  const N = window.NSO;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Brandmark />
            <p style={{marginTop: 18, color: "var(--ink-2)", fontSize: 14, maxWidth: 42 + "ch", lineHeight: 1.55}}>
              A virtual neurology second-opinion platform. Academic-grade cognitive assessments delivered to families.
            </p>
            <p className="geo" style={{marginTop: 24}}>{N.brand.geography}</p>
          </div>
          <div>
            <h4>Services</h4>
            <ul>
              <li><a href="submit.html">Panel review</a></li>
              <li><a href="specialists.html">Specialists directory</a></li>
              <li><a href="specialists.html">Direct consult</a></li>
              <li><a href="pricing.html">Pricing</a></li>
              <li><a href="pathway.html">Care pathway</a></li>
              <li><a href="sample.html">Sample opinion</a></li>
            </ul>
          </div>
          <div>
            <h4>Conditions</h4>
            <ul>
              <li><a href="alzheimers.html">Alzheimer's disease</a></li>
              <li><a href="dementia.html">Dementia</a></li>
              <li><span className="link-soon">Mild cognitive impairment</span></li>
              <li><span className="link-soon">Frontotemporal degeneration</span></li>
              <li><span className="link-soon">Lewy body disease</span></li>
            </ul>
          </div>
          <div>
            <h4>About</h4>
            <ul>
              <li><a href="protocol.html">Our protocol</a></li>
              <li><a href="our-standard.html">Our standard</a></li>
              <li><a href="team.html">Team</a></li>
              <li><a href="index.html#panel">Clinical leadership</a></li>
              <li><a href="faq.html">FAQ</a></li>
              <li><a href="privacy.html">Privacy &amp; HIPAA</a></li>
              <li><a href="terms.html">Terms</a></li>
              <li><a href="contact.html">Contact</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-legal">
          <small>© 2026 NeuroSecondOpinion, PBC. All rights reserved.</small>
          <small style={{maxWidth: 60 + "ch"}}>{N.brand.legal}</small>
        </div>
      </div>
    </footer>
  );
}

// ─── Specialist card (v2) ──────────────────────────────────────
// Three variants:
//   compact   — homepage clinical leadership grid (Phase 6.1)
//   directory — /specialists listing
//   hero      — top of /specialists/[slug] (Phase 4)
//
// Reads from the v2 specialist shape: slug, name, credentials, role, title,
// affiliation, focus, specialties[], conditionFocus[], statesLicensed[],
// statesPending[], languages[], insurance, services[], pricing{}, nextAvailable,
// photo, photoStatus.
//
// [PENDING] string fields render as muted "Full profile coming" microcopy
// rather than the literal string, so directory copy stays clean.

function isPending(v) {
  return typeof v === "string" && v.indexOf("[PENDING") === 0;
}

function specialistHref(s) {
  return "specialist.html?slug=" + encodeURIComponent(s.slug);
}

/** Lookup across clinicalLeadership + networkSpecialists. Returns null if unknown slug. */
function findSpecialistBySlug(slug) {
  if (!slug || typeof slug !== "string") return null;
  var N = window.NSO || {};
  var all = [].concat(N.clinicalLeadership || [], N.networkSpecialists || []);
  var hit = all.find(function (x) { return x.slug === slug; });
  return hit || null;
}

function specialtyLabel(id) {
  var N = window.NSO || {};
  var t = (N.specialtyTaxonomy || []).find(function (x) { return x.id === id; });
  return t ? t.label : id;
}

function conditionLabel(id) {
  var N = window.NSO || {};
  var t = (N.conditionTaxonomy || []).find(function (x) { return x.id === id; });
  return t ? t.label : id;
}

function SpecialistMonogram({ s, size = 64 }) {
  var style = { width: size, height: size, fontSize: Math.round(size * 0.32) };
  if (s.photo) {
    return (
      <div className="sp-monogram sp-monogram-photo" style={style}>
        <img src={s.photo} alt="" width={size} height={size} loading="lazy" decoding="async" />
      </div>
    );
  }
  return (
    <div
      className="sp-monogram"
      aria-hidden="true"
      style={style}
    >
      {s.initials || (s.name || "?").split(" ").map(function (w) { return w[0]; }).join("").slice(0, 2)}
    </div>
  );
}

function StatesLine({ s }) {
  var licensed = s.statesLicensed || [];
  var pending = s.statesPending || [];
  if (!licensed.length && !pending.length) return null;
  return (
    <div className="sp-states">
      {licensed.length > 0 && (
        <span>Licensed in {licensed.join(", ")}</span>
      )}
      {pending.length > 0 && (
        <span className="sp-states-pending">{licensed.length ? "; " : ""}{pending.join(", ")} pending</span>
      )}
    </div>
  );
}

function ServiceBadges({ s }) {
  var services = s.services || [];
  if (!services.length) return null;
  var labels = {
    "panel-lead": "Panel reviewer",
    "direct-consult": "Direct consult",
    "panel-member": "Panel member",
  };
  return (
    <div className="sp-badges">
      {services.map(function (id) {
        return <span key={id} className="sp-badge">{labels[id] || id}</span>;
      })}
    </div>
  );
}

function fmtUSD(n) {
  if (n == null) return "";
  return "$" + n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function PricingLine({ s }) {
  var p = s.pricing || {};
  var parts = [];
  if (p.directConsult) parts.push("Direct consult " + fmtUSD(p.directConsult));
  if (p.panelLead) parts.push("Panel review " + fmtUSD(p.panelLead));
  if (!parts.length) return null;
  return <div className="sp-pricing tabular">{parts.join(" · ")}</div>;
}

function NextAvailableLine({ s }) {
  if (!s.nextAvailable) {
    return <div className="sp-next sp-next-pending">Availability listed when scheduling opens.</div>;
  }
  return <div className="sp-next">Next: {s.nextAvailable}</div>;
}

function SpecialistCard({ s, variant = "compact" }) {
  if (variant === "directory") {
    return (
      <article className="sp-card sp-card-directory">
        <a className="sp-card-link" href={specialistHref(s)} aria-label={"View " + s.name + " profile"}>
          <header className="sp-card-head">
            <SpecialistMonogram s={s} size={72} />
            <div className="sp-card-id">
              <div className="sp-name">{s.name}</div>
              {s.credentials && <div className="sp-creds">{s.credentials}</div>}
              <div className="sp-role">
                {s.role}{s.title ? " · " + s.title : ""}
              </div>
            </div>
            {s.tier === "leadership" && <span className="sp-tier-tag">Clinical leadership</span>}
          </header>

          {s.affiliation && !isPending(s.affiliation) && (
            <div className="sp-affiliation">{s.affiliation}</div>
          )}
          {s.affiliation && isPending(s.affiliation) && (
            <div className="sp-affiliation sp-pending">Institutional affiliation pending approval.</div>
          )}

          {s.conditionFocus && s.conditionFocus.length > 0 && (
            <div className="sp-conditions">
              {s.conditionFocus.slice(0, 3).map(function (id) {
                return <span key={id} className="sp-condition-chip">{conditionLabel(id)}</span>;
              })}
              {s.conditionFocus.length > 3 && (
                <span className="sp-condition-more">+{s.conditionFocus.length - 3} more</span>
              )}
            </div>
          )}

          <StatesLine s={s} />

          {s.languages && s.languages.length > 1 && (
            <div className="sp-languages">Languages: {s.languages.join(", ")}</div>
          )}

          {s.insurance && !isPending(s.insurance) && (
            <div className="sp-insurance">{s.insurance}</div>
          )}

          <NextAvailableLine s={s} />

          <footer className="sp-card-foot">
            <ServiceBadges s={s} />
            <PricingLine s={s} />
          </footer>

          <div className="sp-cta">View profile &amp; book →</div>
        </a>
      </article>
    );
  }

  if (variant === "hero") {
    return (
      <header className="sp-hero">
        <div className="sp-hero-portrait">
          <SpecialistMonogram s={s} size={140} />
          {s.photoStatus && <div className="sp-photo-status">{s.photoStatus}</div>}
        </div>
        <div className="sp-hero-id">
          <div className="sp-hero-eyebrow-row">
            <div className="eyebrow">{s.role}</div>
            {s.tier === "leadership" && <span className="sp-tier-tag">Clinical leadership</span>}
          </div>
          <h1 className="sp-hero-name">{s.name}</h1>
          {s.credentials && <div className="sp-creds">{s.credentials}</div>}
          {s.affiliation && !isPending(s.affiliation) && (
            <div className="sp-affiliation">{s.affiliation}</div>
          )}
          {s.affiliation && isPending(s.affiliation) && (
            <div className="sp-affiliation sp-pending">Institutional affiliation pending approval.</div>
          )}
          {s.practice && <div className="sp-practice">{s.practice}</div>}
          <div className="sp-hero-meta">
            <ServiceBadges s={s} />
            <PricingLine s={s} />
          </div>
        </div>
      </header>
    );
  }

  // compact (default — homepage)
  return (
    <a className="sp-card sp-card-compact" href={specialistHref(s)}>
      <SpecialistMonogram s={s} size={56} />
      <div className="sp-card-id">
        <div className="sp-name">{s.name}</div>
        {s.credentials && <div className="sp-creds">{s.credentials}</div>}
        <div className="sp-role">{s.role}{s.title ? " · " + s.title : ""}</div>
        {s.focus && <div className="sp-focus">{s.focus}</div>}
      </div>
    </a>
  );
}

// ─── Booking widget (Phase 4) ───────────────────────────────────
// Calendly inline embed when specialist.calendlyUrl is an https URL; otherwise a
// Formspree-backed request form (consultEndpoint). Live card payments are v2.5+.
//
// Migration path: add calendlyUrl to each specialist record in data.js; once all
// URLs are live, you can simplify the fallback branch or keep it as backup.
function BookingWidget({ specialist }) {
  const { useEffect, useRef, useState } = React;
  const hostRef = useRef(null);
  const [status, setStatus] = useState("idle");
  const [form, setForm] = useState({ name: "", email: "", preferredDates: "", description: "" });
  const [errors, setErrors] = useState({});

  const rawUrl = specialist.calendlyUrl && String(specialist.calendlyUrl).trim();
  const hasCalendly = !!rawUrl && /^https?:\/\//i.test(rawUrl);

  useEffect(function () {
    if (!hasCalendly || !hostRef.current) return;
    function init() {
      if (!window.Calendly || !hostRef.current) return;
      hostRef.current.innerHTML = "";
      window.Calendly.initInlineWidget({
        url: rawUrl,
        parentElement: hostRef.current,
        prefill: {},
        utm: {},
      });
    }
    if (window.Calendly) {
      init();
      return;
    }
    var existing = document.querySelector("script[data-ns-calendly]");
    if (existing) {
      existing.addEventListener("load", init);
      return function () { existing.removeEventListener("load", init); };
    }
    var script = document.createElement("script");
    script.src = "https://assets.calendly.com/assets/external/widget.js";
    script.async = true;
    script.setAttribute("data-ns-calendly", "1");
    script.onload = init;
    document.body.appendChild(script);
  }, [hasCalendly, rawUrl]);

  var directOk = (specialist.services || []).indexOf("direct-consult") !== -1;
  var price = specialist.pricing && specialist.pricing.directConsult;

  function validate(d) {
    var e = {};
    if (!d.name || !d.name.trim()) e.name = "Required.";
    if (!nsoEmailOk(d.email || "")) e.email = "Valid email required.";
    if (!d.preferredDates || d.preferredDates.trim().length < 3) e.preferredDates = "Share a few windows that work.";
    if (!d.description || d.description.trim().length < 20) e.description = "A brief description helps the coordinator prepare.";
    return e;
  }

  async function onSubmit(ev) {
    ev.preventDefault();
    var v = validate(form);
    setErrors(v);
    if (Object.keys(v).length) return;
    setStatus("submitting");
    var endpoint = (window.NSO_FORMS && window.NSO_FORMS.consultEndpoint) || "";
    if (!nsoEndpointOk(endpoint)) {
      setStatus("error");
      return;
    }
    try {
      var res = await nsoSubmitFormspreeJson(endpoint, {
        _subject: "Consult request · " + specialist.name + " · " + specialist.slug,
        specialistSlug: specialist.slug,
        specialistName: specialist.name,
        ...form,
      });
      if (!res.ok) throw new Error("bad status");
      if (typeof window.track === "function") {
        window.track("Form Completed", { form: "booking-request", specialist: specialist.slug });
      }
      setStatus("sent");
    } catch (_e) {
      setStatus("error");
    }
  }

  if (!directOk) {
    return (
      <div className="booking-widget booking-widget-muted">
        <div className="eyebrow">Direct consult</div>
        <p style={{ margin: 0, fontSize: 15, color: "var(--ink-2)", lineHeight: 1.55 }}>
          This clinician is not currently listed for self-serve direct consults. Write to{" "}
          <a href={"mailto:" + ((window.NSO_FORMS && window.NSO_FORMS.fallbackEmail) || "contact@neurosecondopinion.org")}>{(window.NSO_FORMS && window.NSO_FORMS.fallbackEmail) || "contact@neurosecondopinion.org"}</a>
          {" "}or use the <a href="specialists.html">directory routing form</a>.
        </p>
      </div>
    );
  }

  return (
    <div className="booking-widget" id="booking">
      <div className="booking-head">
        <div className="eyebrow">Schedule</div>
        <h2 className="booking-title">Book a consult</h2>
        <p className="booking-deck">
          {price ? fmtUSD(price) + " · " : ""}45-minute video. Records optional — sending them ahead of time helps the conversation stay substantive.
        </p>
      </div>

      {hasCalendly ? (
        <div className="calendly-host" ref={hostRef} aria-label="Calendly scheduling embed" />
      ) : (
        <>
          <p className="booking-fallback-note">
            Live scheduling is being configured. Request a slot below — we&apos;ll confirm within 24 hours.
          </p>
          {status === "sent" ? (
            <p className="booking-sent" role="status">Thanks. We&apos;ll confirm your slot within 24 hours.</p>
          ) : (
            <form data-form-name="booking-request" onSubmit={onSubmit} noValidate className="booking-form">
              <div className="field">
                <label htmlFor="bk-name">Your name <span className="req">*</span></label>
                <input id="bk-name" value={form.name} onChange={e=>setForm({...form, name: e.target.value})} aria-invalid={!!errors.name} aria-describedby={errors.name ? "err-bk-name" : undefined} />
                {errors.name && <span id="err-bk-name" className="form-err">{errors.name}</span>}
              </div>
              <div className="field">
                <label htmlFor="bk-email">Email <span className="req">*</span></label>
                <input id="bk-email" type="email" value={form.email} onChange={e=>setForm({...form, email: e.target.value})} aria-invalid={!!errors.email} aria-describedby={errors.email ? "err-bk-email" : undefined} />
                {errors.email && <span id="err-bk-email" className="form-err">{errors.email}</span>}
              </div>
              <div className="field">
                <label htmlFor="bk-dates">Preferred dates / times <span className="req">*</span></label>
                <textarea id="bk-dates" rows="3" value={form.preferredDates} onChange={e=>setForm({...form, preferredDates: e.target.value})} placeholder="e.g. weekday mornings PT, or June 10–14" aria-invalid={!!errors.preferredDates} aria-describedby={errors.preferredDates ? "err-bk-dates" : undefined} />
                {errors.preferredDates && <span id="err-bk-dates" className="form-err">{errors.preferredDates}</span>}
              </div>
              <div className="field">
                <label htmlFor="bk-desc">What do you want to discuss? <span className="req">*</span></label>
                <textarea id="bk-desc" rows="5" value={form.description} onChange={e=>setForm({...form, description: e.target.value})} aria-invalid={!!errors.description} aria-describedby={errors.description ? "err-bk-desc" : undefined} />
                {errors.description && <span id="err-bk-desc" className="form-err">{errors.description}</span>}
              </div>
              <button type="submit" className="btn btn-primary" style={{ width: "100%" }} disabled={status === "submitting"}>
                {status === "submitting" ? "Sending…" : "Request consult →"}
              </button>
              {status === "error" && (
                <p className="form-err" role="alert" style={{ marginTop: 12 }}>
                  Could not send right now. Email <a href={"mailto:" + ((window.NSO_FORMS && window.NSO_FORMS.fallbackEmail) || "contact@neurosecondopinion.org")}>{(window.NSO_FORMS && window.NSO_FORMS.fallbackEmail) || "contact@neurosecondopinion.org"}</a>.
                </p>
              )}
            </form>
          )}
        </>
      )}
    </div>
  );
}

// ─── Routing helper ─────────────────────────────────────────────
// Sidebar / footer block on /specialists. Three-question form posted to the
// contact Formspree endpoint with a routing hint. Built on the same pattern
// as contact.html so it shares Phase 5.3's form-utils once that lands.
function RoutingHelper() {
  const { useState } = React;
  const [form, setForm] = useState({ about: "", description: "", email: "", state: "" });
  const [status, setStatus] = useState("idle"); // idle | submitting | sent | error
  const [errors, setErrors] = useState({});

  function validate(d) {
    var e = {};
    if (!d.about) e.about = "Required.";
    if (!d.description || d.description.trim().length < 10) e.description = "A sentence or two helps a coordinator route.";
    if (!nsoEmailOk(d.email || "")) e.email = "Valid email required.";
    if (!d.state) e.state = "Required.";
    return e;
  }

  async function onSubmit(ev) {
    ev.preventDefault();
    var v = validate(form);
    setErrors(v);
    if (Object.keys(v).length) return;
    setStatus("submitting");
    var endpoint = (window.NSO_FORMS && window.NSO_FORMS.contactEndpoint) || "";
    if (!nsoEndpointOk(endpoint)) {
      setStatus("error");
      return;
    }
    try {
      var res = await nsoSubmitFormspreeJson(endpoint, {
        _subject: "Routing helper · " + form.state,
        source: "specialists routing helper",
        ...form,
      });
      if (!res.ok) throw new Error("status " + res.status);
      if (typeof window.track === "function") {
        window.track("Form Completed", { form: "routing-helper" });
      }
      setStatus("sent");
    } catch (_e) {
      setStatus("error");
    }
  }

  if (status === "sent") {
    return (
      <aside className="routing-helper routing-sent">
        <div className="eyebrow">Thanks</div>
        <p>A coordinator will reach out within 24 hours to route the consult.</p>
      </aside>
    );
  }

  return (
    <aside className="routing-helper">
      <div className="eyebrow">Not sure who fits?</div>
      <h3 className="routing-title">Tell us about the situation.</h3>
      <p className="routing-sub">A coordinator will route within 24 hours.</p>
      <form data-form-name="routing-helper" onSubmit={onSubmit} noValidate>
        <div className="field">
          <label htmlFor="rh-about">Who is the consult about? <span className="req">*</span></label>
          <select id="rh-about" value={form.about} onChange={e=>setForm({...form, about: e.target.value})} aria-invalid={!!errors.about} aria-describedby={errors.about ? "err-rh-about" : undefined}>
            <option value="">Select…</option>
            <option>A parent</option>
            <option>A spouse / partner</option>
            <option>Another family member</option>
            <option>Myself</option>
          </select>
          {errors.about && <span id="err-rh-about" className="form-err">{errors.about}</span>}
        </div>
        <div className="field">
          <label htmlFor="rh-desc">What's been happening? <span className="req">*</span></label>
          <textarea id="rh-desc" rows="4" value={form.description} onChange={e=>setForm({...form, description: e.target.value})} placeholder="A sentence or two." aria-invalid={!!errors.description} aria-describedby={errors.description ? "err-rh-desc" : undefined} />
          {errors.description && <span id="err-rh-desc" className="form-err">{errors.description}</span>}
        </div>
        <div className="field">
          <label htmlFor="rh-email">Email <span className="req">*</span></label>
          <input id="rh-email" type="email" value={form.email} onChange={e=>setForm({...form, email: e.target.value})} placeholder="you@example.com" aria-invalid={!!errors.email} aria-describedby={errors.email ? "err-rh-email" : undefined} />
          {errors.email && <span id="err-rh-email" className="form-err">{errors.email}</span>}
        </div>
        <div className="field">
          <label htmlFor="rh-state">State <span className="req">*</span></label>
          <select id="rh-state" value={form.state} onChange={e=>setForm({...form, state: e.target.value})} aria-invalid={!!errors.state} aria-describedby={errors.state ? "err-rh-state" : undefined}>
            <option value="">Select…</option>
            <option>CA</option><option>NJ</option><option>PA</option><option>AZ</option><option>DC</option>
            <option disabled>──────</option>
            <option>Other</option>
          </select>
          {errors.state && <span id="err-rh-state" className="form-err">{errors.state}</span>}
        </div>
        <button type="submit" className="btn btn-primary" disabled={status === "submitting"} style={{ width: "100%" }}>
          {status === "submitting" ? "Sending…" : "Request routing →"}
        </button>
        {status === "error" && (
          <p className="form-err" role="alert" style={{ marginTop: 12 }}>
            Could not send right now. Email <a href={"mailto:" + ((window.NSO_FORMS && window.NSO_FORMS.fallbackEmail) || "contact@neurosecondopinion.org")}>{(window.NSO_FORMS && window.NSO_FORMS.fallbackEmail) || "contact@neurosecondopinion.org"}</a> with the same details.
          </p>
        )}
      </form>
    </aside>
  );
}

// ─── Consultant card (legacy) ──────────────────────────────────
function ConsultantCard({ s, compact = false }) {
  if (s.tbd) {
    return (
      <article className="cc cc-tbd" style={compact ? {padding: "18px 0"} : null}>
        <div className="cc-monogram cc-monogram-tbd" aria-hidden="true">{s.initials || "TBD"}</div>
        <div>
          <div className="cc-name cc-name-tbd">Specialist joining the panel</div>
          <div className="cc-role">{s.role}</div>
          <div className="cc-inst"><span className="recruiting-tag">{s.note || "Recruiting now"}</span></div>
          <div className="cc-focus">A board-certified sub-specialist with senior clinical experience in this area.</div>
        </div>
      </article>
    );
  }
  return (
    <article className="cc" style={compact ? {padding: "18px 0"} : null}>
      <div className="cc-monogram" aria-hidden="true">{s.initials}</div>
      <div>
        <div className="cc-name">{s.name}</div>
        <div className="cc-role">{s.role}</div>
        <div className="cc-inst">{s.inst}</div>
        <div className="cc-focus">{s.focus}</div>
      </div>
    </article>
  );
}

// ─── Door (situational entry point) ────────────────────────────
function Door({ d }) {
  return (
    <a
      className={"door" + (d.featured ? " featured" : "")}
      href={d.route.href}
      data-plausible="Door Click"
      data-plausible-props={JSON.stringify({ door: d.kicker, route: d.route.label })}
    >
      <div className="door-kicker">{d.kicker}</div>
      <h3 className="door-title">{d.title}</h3>
      <p className="door-body">{d.body}</p>
      <div className="door-route">
        <span className="door-route-label">{d.route.label}</span>
        <span className="door-route-price tabular">{d.route.price}</span>
        <span className="door-route-note">{d.route.note}</span>
      </div>
    </a>
  );
}

// ─── Geo strip / legal strip ───────────────────────────────────
function LegalStrip() {
  const N = window.NSO;
  return (
    <div className="container" style={{padding: "32px var(--gutter)", borderTop: "1px solid var(--rule-2)", borderBottom: "1px solid var(--rule-2)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32}}>
      <div className="geo">{N.brand.geography}</div>
      <div className="side-note" style={{borderLeftColor: "var(--rule)", color: "var(--ink-3)", fontStyle: "normal", fontFamily: "var(--sans)", fontSize: 13}}>
        {N.brand.legal}
      </div>
    </div>
  );
}

// ─── Section helper ────────────────────────────────────────────
function Section({ id, eyebrow, title, lead, children, tight }) {
  return (
    <section id={id} className={tight ? "section section-tight" : "section"}>
      <div className="container">
        {(eyebrow || title || lead) && (
          <div className="section-head">
            <div>
              {eyebrow && <div className="eyebrow" style={{marginBottom: 16}}>{eyebrow}</div>}
              {title && <h2>{title}</h2>}
            </div>
            {lead && <p className="lead">{lead}</p>}
          </div>
        )}
        {children}
      </div>
    </section>
  );
}

Object.assign(window, {
  Brandmark, Header, Footer, ConsultantCard, Door, LegalStrip, Section,
  SpecialistCard, SpecialistMonogram, RoutingHelper, BookingWidget,
  specialistHref, findSpecialistBySlug, specialtyLabel, conditionLabel, isPending, fmtUSD,
  StatesLine,
});
