/* Template 3 "The Showcase" - part A: nav + hero (form card + floating chips) */
(function () {
  const e = React.createElement;
  const { useState, useEffect } = React;
  const { useCountdown, fmtDate } = window;
  const Icon = window.Icon;
  const datePart = (iso, opt) => { try { return new Date(iso).toLocaleDateString("en-GB", opt); } catch (x) { return ""; } };

  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("img", { className: "t3-brand__logo", src: "assets/logo-full-color.png", alt: cfg.practice }),
          e("span", { className: "t3-loc" }, e(Icon, { name: "pin" }), cfg.location)),
        e("div", { className: "t3-navlinks" },
          ["The offer", "The day", "Results", "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 },
            e(Icon, { name: "phone" }), e("span", null, cfg.phone)),
          e("a", { className: "t3-callbtn", href: "tel:" + cfg.phone, "aria-label": "Call us" }, e(Icon, { name: "phone" })),
          e(Btn, { variant: "ink", href: "#reserve" }, "Reserve your spot"))),
    );

  /* form card ------------------------------------------------------------- */
  const FormCard = ({ cfg }) => {
    const submit = (ev) => { ev.preventDefault(); window.location.href = cfg.thankYou; };

    useEffect(() => {
      // Load the AC embed script only after React has mounted ._form_25 into the DOM.
      // If loaded from static HTML it runs before React renders, so the div isn't found.
      if (document.querySelector('script[src*="embed.php?id=25"]')) return;

      const s = document.createElement("script");
      s.src = "https://de-ientes.activehosted.com/f/embed.php?id=25";
      s.charset = "utf-8";

      s.onload = function () {
        // AC injects the form asynchronously after the script loads — poll until it appears.
        const poll = setInterval(function () {
          const acForm = document.querySelector("._form_25 ._form");
          if (!acForm) return;
          clearInterval(poll);

          const $ = window.$;

          // Hide name / email / phone labels (placeholders do the job)
          document.querySelectorAll("label").forEach(function (lbl) {
            if (lbl.textContent.includes("Name") || lbl.textContent.includes("Email*") || lbl.textContent.includes("Phone*")) {
              lbl.style.display = "none";
            }
          });

          // Fieldset: go inline for short option lists
          document.querySelectorAll("._form-fieldset").forEach(function (fs) {
            if (fs.children.length <= 4) {
              fs.style.cssText += "display:flex;flex-direction:row;gap:2rem;";
            }
          });

          // Floating labels — scoped to ._form_25 so they don't hit the hidden React form
          $("._form_25 input").on("focus", function () {
            // TEMP: disabled to test floating-label rendering
            // $(this).addClass("focused_input").closest("._field-wrapper").siblings("label._form-label").css("display", "block");
          }).on("focusout", function () {
            if ($(this).val() !== "") {
              $(this).removeClass("focused_input").addClass("has_input")
                .closest("._field-wrapper").siblings("label._form-label").css("display", "block");
            } else {
              $(this).removeClass("focused_input has_input")
                .closest("._field-wrapper").siblings("label._form-label").css("display", "none");
            }
          });

          $("._form_25 textarea").on("focus", function () {
            $(this).addClass("focused_input").closest("._field-wrapper").siblings("label._form-label").css("display", "block");
          }).on("focusout", function () {
            if ($(this).val() !== "") {
              $(this).removeClass("focused_input").addClass("has_input")
                .closest("._field-wrapper").siblings("label._form-label").css("display", "block");
            } else {
              $(this).removeClass("focused_input has_input")
                .closest("._field-wrapper").siblings("label._form-label").css("display", "none");
            }
          });

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

          // Hide treatment field + pre-select "Teeth straightening"
          $("legend:contains('treatment type')").closest("._form-fieldset").hide();
          document.querySelectorAll(".crm_form-header").forEach(function (h) {
            if (h.textContent.toLowerCase().includes("treatment")) h.closest("._form_element").style.display = "none";
          });
          $('input:radio[name="field\\[13\\]"]').filter('[value="Teeth straightening"]').prop("checked", true);

          // Hide location field + pre-select from cfg
          $("legend:contains('location')").closest("._form-fieldset").hide();
          document.querySelectorAll(".crm_form-header").forEach(function (h) {
            if (h.textContent.toLowerCase().includes("location")) h.closest("._form_element").style.display = "none";
          });
          $('input:radio[name="field\\[14\\]"]').filter('[value="' + cfg.location + '"]').prop("checked", true);

          // Submit button label
          const btn = document.querySelector("._form_25 ._submit");
          if (btn) btn.textContent = "Reserve my spot";

          // Form redirect on successful submission
          $("._form_25 ._form").on("submit", function () {
            const errors = $(this).find("._error-inner").length;
            if (errors === 0) {
              setTimeout(function () { window.location.href = cfg.thankYou; }, 500);
            }
          });

          // Privacy policy lightbox (only build once)
          const policyLink = document.querySelector("._form_25 .p-disclaimer a");
          if (policyLink && !document.querySelector(".lightbox_overlay")) {
            $("body").append(
              '<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="' + policyLink.href + '"></iframe></div>'
            );
            $(document).on("mouseup.lightbox", function (ev) {
              if (!$(".lightbox_overlay iframe").is(ev.target) && $(".lightbox_overlay iframe").has(ev.target).length === 0) {
                $(".lightbox_overlay").fadeOut(200);
              }
            });
            $(policyLink).on("click", function (ev) {
              ev.preventDefault();
              $(".lightbox_overlay").fadeIn(200);
            });
          }

        }, 100);

        // Give up after 15 s
        setTimeout(function () { clearInterval(poll); }, 15000);
      };

      document.body.appendChild(s);
    }, []);

    return e("div", { className: "t3-formcard", id: "reserve" },
      e("div", { className: "t3-formcard__head" },
        e("div", { className: "t3-formcard__title" }, "Reserve your spot"),
        e("div", { className: "t3-formcard__badge" }, cfg.placesLeft, " spaces left")),
      e("p", { className: "t3-formcard__note" }, "Free to attend. A \u00a320 refundable deposit secures your slot \u2013 we'll take it by phone when we confirm your time."),
      e("div", { className: "_form_25" }),
      e("form", { onSubmit: submit, "aria-hidden": "true", style: { display: "none" } },
        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 number" }),
          e("input", { type: "email", required: true, placeholder: "Email address" })),
        e(Btn, { variant: "gold", block: true, lg: true, type: "submit" }, "Reserve my spot")),
      e("div", { className: "t3-formcard__foot" },
        e(Icon, { name: "lock" }), "Your details are kept private. Implied consent to contact."));
  };

  /* hero ------------------------------------------------------------------ */
  const Hero = ({ cfg }) => {
    const t = useCountdown(cfg.eventISO);
    const cd = [["Days", t.days], ["Hrs", t.hours], ["Min", t.mins], ["Sec", t.secs]];
    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-hero__lead" },
            e("span", { className: "t3-eyebrow" }, e("span", { className: "dot" }),
              "Orthodontic Open Day \u00b7 ", fmtDate(cfg.eventISO)),
            e("h1", { className: "t3-display" }, "Meet your new smile in ", e("span", { className: "alt" }, cfg.location), ". One day only.")),
          e("div", { className: "t3-hero__rest" },
            e("p", { className: "t3-lead" },
              "Join us for our orthodontic open day \u2013 a relaxed day to meet Dr Saroshen Naidoo, have a full 3D assessment, and find out exactly what treatment could do for your smile. Children and adults welcome."),
            e("p", { className: "t3-hero__addr" }, e(Icon, { name: "pin" }), "De-ientes ", cfg.location, " \u00b7 ", cfg.address)),
          e(FormCard, { cfg })),
        e("div", { className: "t3-hero__visual" },
          e("div", { className: "t3-hero__img" },
            e("img", { src: "assets/photo-smile-mirror.jpg", alt: "A patient admiring her new smile" }),
            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)))),
            e("div", { className: "t3-float t3-float--places" },
              e("b", null, cfg.placesLeft), e("span", null, "places left")),
            e("div", { className: "t3-float t3-float--rev" },
              e("img", { src: "assets/photo-patient-2.jpg", alt: "" }),
              e("div", null,
                e("div", { className: "st" }, "\u2605\u2605\u2605\u2605\u2605"),
                e("div", { className: "q" }, "\u201C", cfg.miniReview.text, "\u201D"),
                e("div", { className: "by" }, cfg.miniReview.name, " \u00b7 Google review")))),
          e("div", { className: "t3-hero__pills t3-hero__pills--under" },
            e("span", { className: "t3-pill" }, e(Icon, { name: "calendar" }), fmtDate(cfg.eventISO)),
            e("span", { className: "t3-pill" }, e(Icon, { name: "clock" }), "9am \u2013 3pm"),
            e("span", { className: "t3-pill" }, e(Icon, { name: "check" }), "Free to attend"),
            e("span", { className: "t3-pill" }, e(Icon, { name: "card" }), "\u00a320 refundable deposit")),
          e("ul", { className: "t3-ticks t3-ticks--under" },
            ["Free 3D assessment, worth \u00a3250", "\u00a3500 off when you start treatment", "Free at-home whitening, worth \u00a3425", "Free upper & lower retainers, worth \u00a3250", "Children & adults welcome"].map((tk, i) =>
              e("li", { key: i }, e("span", { className: "t3-ticks__ic" }, e(Icon, { name: "check" })), e("span", null, tk))))),
      ),
    );
  };

  /* 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" }, cfg.rating, e("span", null, "/5")),
          e("div", { className: "t3-hq__by" },
            e("div", { className: "t3-hq__stars" }, "\u2605\u2605\u2605\u2605\u2605"),
            e("span", null, "from ", cfg.reviewCount, " Google reviews"))),
        e("blockquote", { className: "t3-hq__q" },
          "\u201C", cfg.heroQuote.text, "\u201D"),
        e("div", { className: "t3-hq__name" }, cfg.heroQuote.name, " \u00b7 Google review")));

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