/* Template 3 "The Showcase" - Re-Ignite · part A: nav + hero (form-forward) */
(function () {
  const e = React.createElement;
  const { useCountdown, fmtDate } = window;
  const Icon = window.Icon;

  const Word = () => e("img", { className: "rid-logo", src: "assets/logo.svg", alt: "Re-Ignite Dental" });
  window.T3Word = Word;

  const Btn = ({ variant = "ink", lg, block, href, onClick, type, children }) => {
    const cls = ["t3-btn", "t3-btn--" + variant, lg && "t3-btn--lg", block && "t3-btn--block"].filter(Boolean).join(" ");
    const inner = [children, e("span", { className: "arw", key: "a" }, e(Icon, { name: "chevR" }))];
    return href ? e("a", { className: cls, href, onClick }, inner) : e("button", { className: cls, onClick, type: type || "button" }, inner);
  };
  window.T3Btn = Btn;

  /* nav ------------------------------------------------------------------- */
  const Nav = ({ cfg }) =>
    e("div", { className: "t3-navwrap" },
      e("nav", { className: "t3-nav" },
        e("a", { className: "t3-brand", href: "#top" }, e(Word, null)),
        e("div", { className: "t3-navlinks" },
          ["The package", "The day", "Reviews", "FAQs"].map((l, i) =>
            e("a", { key: i, href: ["#offer", "#day", "#results", "#faq"][i] }, l))),
        e("div", { className: "t3-navend" },
          e("a", { className: "t3-navphone", href: "tel:" + cfg.phone.replace(/\s/g, "") },
            e(Icon, { name: "phone" }), e("span", null, cfg.phone)),
          e("a", { className: "t3-callbtn", href: "tel:" + cfg.phone.replace(/\s/g, ""), "aria-label": "Call us" }, e(Icon, { name: "phone" })),
          e(Btn, { variant: "gold", href: "#reserve" }, "Reserve your spot"))),
    );

  /* form card (minimal: name · phone · email) ----------------------------- */
  const FormCard = ({ cfg }) => {
    const submit = (ev) => { ev.preventDefault(); window.location.href = "/thank-you"; };
    return e("form", { className: "t3-formcard", id: "reserve-legacy", onSubmit: submit },
      e("div", { className: "t3-formcard__head" },
        e("div", { className: "t3-formcard__title" }, "Reserve your spot"),
        e("div", { className: "t3-formcard__badge" }, cfg.slots, " places left")),
      e("p", { className: "t3-formcard__note" }, "Secure your place with a £10 deposit. We’ll call to confirm your time."),
      e("div", { className: "t3-fld" }, e("input", { type: "text", required: true, placeholder: "Full name" })),
      e("div", { className: "t3-fld t3-fld--row" },
        e("input", { type: "tel", required: true, placeholder: "Phone" }),
        e("input", { type: "email", required: true, placeholder: "Email" })),
      e(Btn, { variant: "gold", block: true, lg: true, type: "submit" }, "Reserve your spot"),
      e("div", { className: "t3-formcard__foot" },
        e(Icon, { name: "lock" }), "Your details are kept private. £10 deposit, fully refundable if you cancel."));
  };

  /* ActiveCampaign embed (form id 25) ------------------------------------- *
   * The page is React-via-Babel, so the AC <script> + jQuery init can't run
   * inline. This component renders the ._form_25 mount point, injects the
   * embed script once, then runs the supplied init once the form appears. */
  const AC_EMBED_ID = 25;
  const AC_EMBED_SRC = "https://reignitedental.activehosted.com/f/embed.php?id=" + AC_EMBED_ID;

  /* --- UTM / click-id tracker (supplied verbatim, wrapped one-shot) ------- */
  function bootUtmTracker() {
    if (window.__utmTrackerBooted) return;
    window.__utmTrackerBooted = true;
    (function () {
      const TRACK_KEYS = ["gclid", "fbclid", "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "utm_id"];
      const STORAGE_KEY = "tracking_params_v1";
      const LANDING_URL_KEY = "landing_url_v1";
      function getCurrentUrl() { return new URL(window.location.href); }
      function getTrackingParamsFromUrl(url) {
        const params = {};
        TRACK_KEYS.forEach(function (key) { var value = url.searchParams.get(key); if (value) params[key] = value; });
        return params;
      }
      function getStoredParams() { try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}"); } catch (e) { return {}; } }
      function setStoredParams(params) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(params)); } catch (e) {} }
      function getStoredLandingUrl() { try { return localStorage.getItem(LANDING_URL_KEY) || ""; } catch (e) { return ""; } }
      function setStoredLandingUrl(url) { try { if (!localStorage.getItem(LANDING_URL_KEY)) localStorage.setItem(LANDING_URL_KEY, url); } catch (e) {} }
      function buildSubmissionUrl(currentUrl, storedParams) {
        var url = new URL(currentUrl.href);
        Object.entries(storedParams).forEach(function (pair) { var key = pair[0], value = pair[1]; if (value && !url.searchParams.get(key)) url.searchParams.set(key, value); });
        return url.toString();
      }
      function ensureHiddenField(form, name) {
        var input = form.querySelector('input[name="' + name + '"]');
        if (!input) { input = document.createElement("input"); input.type = "hidden"; input.name = name; form.appendChild(input); }
        return input;
      }
      function populateFormFields(form) {
        var currentUrl = getCurrentUrl();
        var currentParams = getTrackingParamsFromUrl(currentUrl);
        var storedParams = Object.assign({}, getStoredParams(), currentParams);
        if (Object.keys(currentParams).length > 0) { setStoredParams(storedParams); setStoredLandingUrl(currentUrl.toString()); }
        var finalStoredParams = getStoredParams();
        var landingUrl = getStoredLandingUrl() || currentUrl.toString();
        var submissionUrl = buildSubmissionUrl(currentUrl, finalStoredParams);
        ensureHiddenField(form, "submission_url").value = submissionUrl;
        ensureHiddenField(form, "landing_url").value = landingUrl;
        ensureHiddenField(form, "tracking_params_json").value = JSON.stringify(finalStoredParams);
        TRACK_KEYS.forEach(function (key) { ensureHiddenField(form, key).value = finalStoredParams[key] || ""; });
      }
      function populateAllForms() { document.querySelectorAll("form").forEach(function (form) { populateFormFields(form); }); }
      document.addEventListener("DOMContentLoaded", function () { populateAllForms(); });
      window.addEventListener("pageshow", function () { populateAllForms(); });
      document.addEventListener("submit", function (event) {
        var form = event.target;
        if (form && form.tagName === "FORM") populateFormFields(form);
      }, true);
      populateAllForms(); // document is already ready under React, so run an immediate pass
    })();
  }

  /* --- supplied jQuery init, run once the AC form is in the DOM ----------- */
  function runAcInit() {
    if (window.__acInitDone) return;
    var $ = window.jQuery;
    if (!$) return;
    window.__acInitDone = true;

    /* 1 - layout + floating labels + privacy lightbox */
    $('#free').attr("style", "display:flex;");

    var labels = document.querySelectorAll('label');
    labels.forEach(function (label) {
      if (label.textContent.includes('Name') || label.textContent.includes('Email*') || label.textContent.includes('Phone*')) {
        label.style.display = 'none';
      }
    });

    document.querySelectorAll("._form-fieldset").forEach(function (fieldset) {
      if (fieldset.children.length <= 4) {
        fieldset.style.display = "flex";
        fieldset.style.flexDirection = "row";
        fieldset.style.gap = "2rem";
      }
    });

    $('input').focus(function () {
      $(this).addClass('focused_input').parents('._field-wrapper').siblings('label._form-label').attr("style", "display: block !important;");
    });
    $('input').focusout(function () {
      if ($(this).val() != '') {
        $(this).removeClass('focused_input').parents('._field-wrapper').siblings('label._form-label').attr("style", "display: block !important;");
        $(this).addClass('has_input');
      } else {
        $(this).removeClass('focused_input').parents('._field-wrapper').siblings('label._form-label').attr("style", "display: none !important;");
        $(this).removeClass('has_input');
      }
    });
    $('textarea').focus(function () {
      $(this).addClass('focused_input').parents('._field-wrapper').siblings('label._form-label').attr("style", "display: block !important;");
    });
    $('textarea').focusout(function () {
      if ($(this).val() != '') {
        $(this).removeClass('focused_input').parents('._field-wrapper').siblings('label._form-label').attr("style", "display: block !important;");
        $(this).addClass('has_input');
      } else {
        $(this).removeClass('focused_input').parents('._field-wrapper').siblings('label._form-label').attr("style", "display: none !important;");
        $(this).removeClass('has_input');
      }
    });

    $('input[name="fullname"]').attr("autocomplete", "name");
    $('input[name="email"]').attr("autocomplete", "email");
    $('input[name="phone"]').attr("autocomplete", "tel");

    if (!document.querySelector('.lightbox_overlay')) {
      var lightbox_load = $('.p-disclaimer a').attr('href');
      var lightbox_iframe = '<div class="lightbox_overlay"><img src="https://assets.website-files.com/5f4f9ca89e421f59d554ddb5/5f7739bf59180314c3777de6_cancel-white.svg" loading="lazy" width="15" height="15" alt="" class="close-policy"><iframe src="' + lightbox_load + '"></iframe></div>';
      $('body').append(lightbox_iframe);
      $(document).mouseup(function (e) {
        var container = $(".lightbox_overlay iframe");
        if (!container.is(e.target) && container.has(e.target).length === 0) {
          $('.lightbox_overlay').fadeOut(200);
          $('.container-large.form-inner').removeClass("active");
        }
      });
      $('.p-disclaimer a').click(function (e) {
        e.preventDefault();
        $('.lightbox_overlay').fadeIn(200);
        $('.container-large.form-inner').addClass("active");
      });
    }

    /* 2 - hide all treatment options */
    $("legend:contains('treatment type')").closest('._form-fieldset').css("display", "none");
    document.querySelectorAll(".crm_form-header").forEach(function (header) {
      if (header.textContent.toLowerCase().includes("treatment")) {
        var owner = header.closest("._form_element");
        if (owner) owner.style.display = "none";
      }
    });

    /* 3 - pre-select Invisalign */
    $('input:radio[name="field\\[13\\]"]').filter('[value="Invisalign"]').attr('checked', true).prop('checked', true);

    /* 4 - form redirect to /thank-you */
    $('._form').click(function (e) {
      $('input[name="fullname"]').attr('type', 'text');
      $('input[name="email"]').attr('type', 'text');
      $('input[name="phone"]').attr('type', 'text');
    });
    $('._form').submit(function (e) {
      $('input[name="fullname"]').attr('type', 'text');
      $('input[name="email"]').attr('type', 'email');
      $('input[name="phone"]').attr('type', 'tel');
      var errors = $(this).find("._error-inner").length;
      if (errors == 0) {
        setTimeout(function () { window.location.href = '/thank-you'; }, 500);
      }
    });

    /* 5 - submit button label */
    var button = document.querySelector("._form_" + AC_EMBED_ID + " ._submit") || document.querySelector("._submit");
    if (button) {
      if (button.tagName === "BUTTON") button.textContent = "Reserve your spot";
      else button.value = "Reserve your spot";
    }
  }

  const ACForm = ({ cfg }) => {
    const hostRef = React.useRef(null);

    React.useEffect(function () {
      if (window.__acFormBooted) return;
      window.__acFormBooted = true;

      bootUtmTracker();

      var host = hostRef.current;
      var mo = null;
      var cancelled = false;

      // inject the AC embed once
      if (!document.querySelector('script[data-ac-embed="' + AC_EMBED_ID + '"]')) {
        var s = document.createElement("script");
        s.src = AC_EMBED_SRC;
        s.charset = "utf-8";
        s.async = true;
        s.setAttribute("data-ac-embed", String(AC_EMBED_ID));
        document.body.appendChild(s);
      }

      // wait for embed.php to inject the <form>, then run the supplied init
      var tryInit = function () {
        if (cancelled || !host) return false;
        if (host.querySelector("form")) { runAcInit(); return true; }
        return false;
      };
      if (!tryInit()) {
        mo = new MutationObserver(function () {
          if (tryInit() && mo) { mo.disconnect(); mo = null; }
        });
        mo.observe(host, { childList: true, subtree: true });
      }

      return function () { cancelled = true; if (mo) mo.disconnect(); };
    }, []);

    return e("div", { className: "t3-formcard t3-acform", id: "reserve" },
      e("div", { className: "t3-formcard__head" },
        e("div", { className: "t3-formcard__title" }, "Reserve your spot"),
        e("div", { className: "t3-formcard__badge" }, cfg.slots, " places left")),
      e("p", { className: "t3-formcard__note" }, "Secure your place with a £10 deposit. We’ll call to confirm your time."),
      e("div", { className: "_form_" + AC_EMBED_ID, ref: hostRef }));
  };

  /* hero ------------------------------------------------------------------ */
  const Hero = ({ cfg }) => {
    const t = useCountdown(cfg.eventISO);
    const cd = [["Days", t.days], ["Hrs", t.hours], ["Min", t.mins], ["Sec", t.secs]];
    const dShort = (() => { try { return new Date(cfg.eventISO).toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "long" }); } catch (x) { return "Sat 11 July"; } })();
    return e("section", { className: "t3-hero", id: "top" },
      e("div", { className: "t3-cont t3-hero__grid" },
        e("div", { className: "t3-hero__copy" },
          e("div", { className: "t3-announce" },
            e("span", { className: "t3-announce__ic" }, e(Icon, { name: "calendar" })),
            e("div", { className: "t3-announce__txt" },
              e("span", { className: "t3-announce__kick" }, "One day only · limited places"),
              e("span", { className: "t3-announce__ttl" }, "Invisalign Open Day")),
            e("span", { className: "t3-announce__date" }, dShort, e("em", null, "10:00am–2:30pm"))),
          e("h1", { className: "t3-display", style: { margin: "24px 0 0" } }, cfg.headline),
          e("p", { className: "t3-lead", style: { margin: "22px 0 0", maxWidth: 520 } },
            "One relaxed morning, your future smile mapped out on the iTero Lumina, and up to £955 off your Invisalign treatment - with whitening and retainers included."),
          e("ul", { className: "t3-ticks" },
            ["Total value package worth up to £2,990", "Whitening & retainers included", "5-star rated by 368 patients"].map((tk, i) =>
              e("li", { key: i }, e("span", { className: "t3-ticks__ic" }, e(Icon, { name: "check" })), e("span", null, tk)))),
          e("div", { className: "t3-hero__trustline" },
            e("span", { className: "st" }, "★★★★★"),
            e("b", null, "5.0"),
            e("span", null, "from 368 Google reviews"))),
        e("div", { className: "t3-hero__visual" },
          e("div", { className: "t3-formcard-legacy", style: { display: "none" }, "aria-hidden": "true" },
            e(FormCard, { cfg })),
          e(ACForm, { cfg }),
          e("div", { className: "t3-hero__img" },
            e("img", { src: "assets/rid-hero.jpg", alt: "A patient admiring her new smile at Re-Ignite Dental" }),
            cfg.showCountdown && e("div", { className: "t3-float t3-float--cd" },
              cd.map(([l, v], i) => e("div", { className: "u", key: i },
                e("b", null, String(v).padStart(2, "0")), e("span", null, l)))))),
      ),
    );
  };

  /* centred testimonial directly below the hero --------------------------- */
  const HeroQuote = ({ cfg }) =>
    e("section", { className: "t3-sec t3-cont", style: { paddingTop: 0 } },
      e("div", { className: "t3-hq t3-reveal" },
        e("div", { className: "t3-hq__score" },
          e("div", { className: "t3-hq__num" }, "5.0", e("span", null, "/5")),
          e("div", { className: "t3-hq__by" },
            e("div", { className: "t3-hq__stars" }, "★★★★★"),
            e("span", null, "from 368 Google reviews"))),
        e("blockquote", { className: "t3-hq__q" },
          "“Everyone at the practice is so lovely and welcoming, and Dr Imran is really professional. I can’t wait to see my final result from Invisalign.”"),
        e("div", { className: "t3-hq__name" }, "Beth Southcott · Invisalign patient, ", cfg.city)));

  window.T3A = { Nav, Hero, HeroQuote };
})();
