document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("[data-scroll]").forEach((link) =>
    link.addEventListener("click", (e) => {
      const target = document.querySelector(link.getAttribute("href"));
      if (target) {
        e.preventDefault();
        target.scrollIntoView({ behavior: "smooth" });
      }
    }),
  );

  const menuToggle = document.querySelector("[data-menu-toggle]");
  const mobileMenu = document.querySelector("[data-mobile-menu]");
  if (menuToggle && mobileMenu) {
    const closeMenu = () => {
      mobileMenu.classList.remove("is-open");
      menuToggle.classList.remove("is-open");
      menuToggle.setAttribute("aria-expanded", "false");
      menuToggle.setAttribute("aria-label", "Open navigation menu");
    };
    menuToggle.addEventListener("click", () => {
      const opening = !mobileMenu.classList.contains("is-open");
      mobileMenu.classList.toggle("is-open", opening);
      menuToggle.classList.toggle("is-open", opening);
      menuToggle.setAttribute("aria-expanded", String(opening));
      menuToggle.setAttribute(
        "aria-label",
        opening ? "Close navigation menu" : "Open navigation menu",
      );
    });
    mobileMenu
      .querySelectorAll("a, [data-enquiry-open]")
      .forEach((link) => link.addEventListener("click", closeMenu));
    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape") closeMenu();
    });
    document.addEventListener("click", (event) => {
      if (
        !menuToggle.contains(event.target) &&
        !mobileMenu.contains(event.target)
      )
        closeMenu();
    });
  }

  const enquiryModal = document.querySelector("[data-enquiry-modal]");
  const enquiryForm = enquiryModal?.querySelector("[data-enquiry-form]");
  const enquiryOpeners = document.querySelectorAll("[data-enquiry-open]");
  let enquiryTrigger = null;

  const closeEnquiry = () => {
    if (!enquiryModal || enquiryModal.hidden) return;
    enquiryModal.hidden = true;
    document.body.classList.remove("modal-open");
    enquiryTrigger?.focus();
  };

  const openEnquiry = (trigger) => {
    if (!enquiryModal) return;
    enquiryTrigger = trigger;
    enquiryModal.hidden = false;
    document.body.classList.add("modal-open");
    enquiryModal.querySelector('input[name="name"]')?.focus();
  };

  enquiryOpeners.forEach((button) =>
    button.addEventListener("click", () => openEnquiry(button)),
  );
  enquiryModal
    ?.querySelectorAll("[data-enquiry-close]")
    .forEach((button) => button.addEventListener("click", closeEnquiry));
  document.addEventListener("keydown", (event) => {
    if (event.key === "Escape") closeEnquiry();
  });

  document.querySelectorAll("[data-multistep]").forEach((form) => {
    const steps = [...form.querySelectorAll("[data-step]")];
    const label = form.querySelector("[data-step-label]");
    const progress = form.querySelector("[data-progress]");
    let current = 0;

    const showStep = (index, shouldScroll = true) => {
      current = Math.max(0, Math.min(index, steps.length - 1));
      steps.forEach((step, i) => (step.hidden = i !== current));
      if (label) label.textContent = `Step ${current + 1} of ${steps.length}`;
      if (progress)
        progress.style.width = `${((current + 1) / steps.length) * 100}%`;
      if (shouldScroll) {
        form
          .querySelector(".form-head")
          ?.scrollIntoView({ behavior: "smooth", block: "nearest" });
      }
    };

    const stepIsValid = () => {
      const invalid = [...steps[current].querySelectorAll("[required]")].find(
        (field) => !field.checkValidity(),
      );
      if (invalid) {
        invalid.reportValidity();
        return false;
      }
      return true;
    };

    form.querySelectorAll(".next-step").forEach((button) =>
      button.addEventListener("click", () => {
        if (stepIsValid()) showStep(current + 1);
      }),
    );
    form
      .querySelectorAll(".prev-step")
      .forEach((button) =>
        button.addEventListener("click", () => showStep(current - 1)),
      );
    form._showFirstStep = () => showStep(0);
    showStep(0, false);
  });

  document.querySelectorAll(".lead-form").forEach((form) =>
    form.addEventListener("submit", async (event) => {
      event.preventDefault();
      const requiredFields = form.hasAttribute("data-multistep")
        ? form.querySelectorAll("[data-step]:not([hidden]) [required]")
        : form.querySelectorAll("[required]");
      const invalid = [...requiredFields].find(
        (field) => !field.checkValidity(),
      );
      if (invalid) {
        invalid.reportValidity();
        return;
      }

      const button = form.querySelector('button[type="submit"]');
      const message = form.querySelector(".form-message");
      const original = button.textContent;

      if (form.hasAttribute("data-endpoint")) {
        button.textContent =
          button.dataset.sendingLabel || "Sending your brief...";
        button.disabled = true;
        if (message) {
          message.textContent = "";
          message.className = "form-message";
        }

        try {
          const response = await fetch(form.action, {
            method: "POST",
            body: new FormData(form),
            headers: { Accept: "application/json" },
            credentials: "same-origin",
          });
          const data = await response.json();
          if (!response.ok || !data.success) {
            throw new Error(data.message || "We could not send your brief.");
          }

          button.textContent =
            button.dataset.successLabel || "Brief received ✓";
          form.classList.add("submitted");
          if (message) {
            message.textContent = data.message;
            message.classList.add("success");
          }
          if (form === enquiryForm) {
            setTimeout(closeEnquiry, 1700);
          }
          setTimeout(() => {
            button.textContent = original;
            button.disabled = false;
            form.reset();
            form.classList.remove("submitted");
            if (message) {
              message.textContent = "";
              message.className = "form-message";
            }
            if (form._showFirstStep) form._showFirstStep();
          }, 4500);
        } catch (error) {
          button.textContent = original;
          button.disabled = false;
          if (message) {
            message.textContent = error.message;
            message.classList.add("error");
          }
        }
        return;
      }

      button.textContent = "Thanks! We'll be in touch ✓";
      button.disabled = true;
      form.classList.add("submitted");
      setTimeout(() => {
        button.textContent = original;
        button.disabled = false;
        form.reset();
        form.classList.remove("submitted");
        if (form._showFirstStep) form._showFirstStep();
      }, 4500);
    }),
  );

  const observer = new IntersectionObserver(
    (entries) =>
      entries.forEach((entry) => {
        if (entry.isIntersecting) entry.target.classList.add("visible");
      }),
    { threshold: 0.12 },
  );
  document.querySelectorAll(".reveal").forEach((el) => observer.observe(el));
});
