// ContactPage.jsx - TBS design-system site (HubSpot embed v2, same portal as main app)
Object.assign(window, {
  ContactPage: function ContactPage({ onNavigate }) {
    const t = darkTheme;
    const cfgRoot = window.TBS_DESIGN_SYSTEM_HUBSPOT || { portalId: "442473556", region: "ap1", campaigns: {} };
    const defaultKey = "contact";

    const getParam = (name) => {
      try {
        return new URLSearchParams(window.location.search).get(name);
      } catch (e) {
        return null;
      }
    };

    const campaignKey = getParam("campaign") || defaultKey;
    const c = (cfgRoot.campaigns && cfgRoot.campaigns[campaignKey]) || (cfgRoot.campaigns && cfgRoot.campaigns[defaultKey]);
    const portalId = getParam("portalId") || cfgRoot.portalId || "442473556";
    const region = getParam("region") || cfgRoot.region || "ap1";

    const targetId = "hs-ds-" + String(React.useId()).replace(/:/g, "");

    const utmSource = getParam("utm_source") || (c && c.utmSource) || "";
    const utmMedium = getParam("utm_medium") || (c && c.utmMedium) || "";
    const utmCampaign = getParam("utm_campaign") || (c && c.utmCampaign) || "";
    const utmTerm = getParam("utm_term") || "";
    const utmContent = getParam("utm_content") || "";

    React.useEffect(
      function mergeUtmToUrl() {
        const u = new URL(window.location.href);
        var changed = false;
        if (utmSource && !u.searchParams.get("utm_source")) {
          u.searchParams.set("utm_source", utmSource);
          changed = true;
        }
        if (utmMedium && !u.searchParams.get("utm_medium")) {
          u.searchParams.set("utm_medium", utmMedium);
          changed = true;
        }
        if (utmCampaign && !u.searchParams.get("utm_campaign")) {
          u.searchParams.set("utm_campaign", utmCampaign);
          changed = true;
        }
        if (utmTerm && !u.searchParams.get("utm_term")) {
          u.searchParams.set("utm_term", utmTerm);
          changed = true;
        }
        if (utmContent && !u.searchParams.get("utm_content")) {
          u.searchParams.set("utm_content", utmContent);
          changed = true;
        }
        if (changed) window.history.replaceState({}, "", u.toString());
      },
      [utmSource, utmMedium, utmCampaign, utmTerm, utmContent],
    );

    const formId = getParam("formId") || (c && c.hubspotFormId) || "";

    /** HubSpot injects inline styles on inputs/buttons; strip so hubspot-form.css + CSS vars win. Re-run on mount after embed loads. */
    React.useEffect(
      function stripHubSpotInlineStylesWhenReady() {
        if (!formId) return undefined;
        var timeouts = [];
        function stripInRoot(root) {
          if (!root) return;
          root
            .querySelectorAll(
              ".hs-button, button.hs-button, input.hs-button, input[type='submit'], input.hs-input, textarea.hs-input, select.hs-input",
            )
            .forEach(function (node) {
              node.removeAttribute("style");
            });
        }
        function scheduleStrip(root) {
          stripInRoot(root);
          timeouts.push(window.setTimeout(function () {
            stripInRoot(root);
          }, 350));
          timeouts.push(window.setTimeout(function () {
            stripInRoot(root);
          }, 900));
        }
        var rootNow = document.getElementById(targetId);
        if (rootNow && rootNow.querySelector("form.hs-form")) {
          scheduleStrip(rootNow);
          return function () {
            timeouts.forEach(function (id) {
              window.clearTimeout(id);
            });
          };
        }
        var n = 0;
        var tid = window.setInterval(function () {
          n += 1;
          var root = document.getElementById(targetId);
          if (!root) return;
          var form = root.querySelector("form.hs-form");
          if (form) {
            scheduleStrip(root);
            window.clearInterval(tid);
          }
          if (n > 180) window.clearInterval(tid);
        }, 80);
        return function () {
          window.clearInterval(tid);
          timeouts.forEach(function (id) {
            window.clearTimeout(id);
          });
        };
      },
      [formId, targetId],
    );

    React.useEffect(
      function mountHubSpot() {
        if (!formId) return;
        var v2 = "https://js-" + region + ".hsforms.net/forms/embed/v2.js";
        var target = "#" + targetId;
        var created = false;

        function go() {
          if (created) return;
          if (!window.hbspt || !window.hbspt.forms || !window.hbspt.forms.create) return;
          var el = document.getElementById(targetId);
          if (!el || el.getAttribute("data-hs-ds") === "1") return;
          el.setAttribute("data-hs-ds", "1");
          created = true;
          window.hbspt.forms.create({
            region: region,
            portalId: portalId,
            formId: formId,
            target: target,
            css: "",
            cssClass: "tbs-ds-hubspot",
          });
        }

        if (window.hbspt && window.hbspt.forms) {
          go();
          return;
        }
        var existing = document.querySelector('script[src="' + v2 + '"]');
        if (existing) {
          var n = 0;
          var t = setInterval(function () {
            n += 1;
            if (window.hbspt && window.hbspt.forms) {
              clearInterval(t);
              go();
            } else if (n > 200) clearInterval(t);
          }, 50);
          return function () {
            clearInterval(t);
          };
        }
        var s = document.createElement("script");
        s.src = v2;
        s.defer = true;
        s.async = true;
        s.onload = go;
        document.body.appendChild(s);
      },
      [formId, region, portalId, targetId],
    );

    if (!c) {
      return (
        <div style={{ background: t.bg, minHeight: "100svh", padding: "max(120px, var(--ds-header-offset)) var(--ds-page-gutter)", textAlign: "center" }}>
          <p style={{ fontFamily: "'Rethink Sans', sans-serif", color: t.fg2, marginBottom: 16, maxWidth: 420, marginLeft: "auto", marginRight: "auto" }}>This contact link is not valid. Open Contact from the menu or home page.</p>
          <button type="button" className="ds-btn ds-btn--primary" onClick={() => onNavigate("home")} style={{ background: t.a1, color: t.onAccent }}>Back home</button>
        </div>
      );
    }

    if (!formId) {
      return (
        <div style={{ background: t.bg, minHeight: "100svh", padding: "max(120px, var(--ds-header-offset)) var(--ds-page-gutter)", textAlign: "center" }}>
          <p style={{ fontFamily: "'Rethink Sans', sans-serif", color: t.fg2, marginBottom: 16, maxWidth: 440, marginLeft: "auto", marginRight: "auto", lineHeight: 1.65 }}>The booking form is not available yet. Please email hello@tbsdigitallabs.com or try again later.</p>
          <button type="button" className="ds-btn ds-btn--primary" onClick={() => onNavigate("home")} style={{ background: t.a1, color: t.onAccent }}>Back home</button>
        </div>
      );
    }

    return (
      <div style={{ background: t.bg, minHeight: "100svh" }}>
        <DsBackdropSection slug="concrete-stairs" variant="hero" className="ds-page-hero-pad ds-page-hero-fill">
          <div className="ds-content-wrap ds-contact-split">
            <div className="ds-contact-copy">
              <div data-ds-enter style={{ ['--ds-enter-delay']: '40ms', display: "flex", alignItems: "center", gap: 10, marginBottom: 24 }}>
                <div data-ds-rule style={{ width: 24, height: 1, background: t.a2 }} />
                <span style={{ fontFamily: "'Rethink Sans', sans-serif", fontSize: 16, fontWeight: 500, color: t.a2 }}>Contact</span>
              </div>
              <h1 data-ds-enter className="ds-hero-h1" style={{ ['--ds-enter-delay']: '120ms', fontFamily: "'Funnel Display', sans-serif", fontWeight: 300, fontSize: "clamp(28px, 5vw + 10px, 64px)", color: t.fg, lineHeight: 1.08, letterSpacing: "-0.02em", marginBottom: 20 }}>
                {dsHighlight('See if we\u2019re the right fit', 'right fit', t.hl)}
              </h1>
              <p data-ds-enter className="ds-prose-wide" style={{ ['--ds-enter-delay']: '240ms', fontFamily: "'Rethink Sans', sans-serif", color: t.fg2, lineHeight: 1.7, marginBottom: 28 }}>Got a growth challenge, a rebrand on the horizon, or you&apos;re not sure why your marketing isn&apos;t converting? Share what you&apos;re trying to move - pipeline, reputation, launch momentum, a stalled website - and we&apos;ll give you a straight answer on whether we&apos;re the right partner and what we&apos;d do if we were.</p>
              <div data-ds-stagger style={{ display: "flex", flexDirection: "column", gap: 20 }}>
                {[{ label: "Straight first reply", body: "We respond with what we've understood about your needs, what we'd need to know more about, and whether a call makes sense." }, { label: "No forced fit", body: "If the brief needs a different partner or more internal groundwork first, we'll say so." }, { label: "A useful next step either way", body: "You leave the conversation knowing what should happen before money moves." }].map(function (item, i) {
                  return (
                    <div key={i} data-ds-reveal="left" style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
                      <div style={{ width: 6, height: 6, borderRadius: "50%", background: t.a2, marginTop: 6, flexShrink: 0 }} />
                      <div>
                        <div style={{ fontFamily: "'Rethink Sans', sans-serif", fontSize: 16, fontWeight: 600, color: t.fg, marginBottom: 4 }}>{item.label}</div>
                        <div style={{ fontFamily: "'Rethink Sans', sans-serif", fontSize: 16, color: t.fg2, lineHeight: 1.55 }}>{item.body}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            <div
              id={targetId}
              data-ds-enter="scale"
              className="ds-hubspot-form-wrap"
              key={formId + campaignKey + targetId}
              role="region"
              aria-label="Contact form"
              style={{
                ['--ds-enter-delay']: '180ms',
                width: "100%",
                minHeight: "min(520px, max(280px, 62dvh))",
                background: t.bgCard,
                border: "1px solid " + t.border,
                borderRadius: 2,
                overflow: "visible",
                padding: "clamp(20px, 3.5vw, 36px)",
              }}
            />
          </div>
        </DsBackdropSection>
      </div>
    );
  },
});
