(function () {
  const modal = document.querySelector("[data-contact-form]");
  if (!modal) return;

  const form = modal.querySelector("[data-contact-form-body]");
  const result = modal.querySelector("[data-contact-result]");
  const categoryInput = modal.querySelector("#contact-form-category");
  const closeTargets = modal.querySelectorAll("[data-contact-close]");
  const triggers = document.querySelectorAll("[data-contact-trigger]");
  let lastActive = null;

  const setOpen = (open) => {
    modal.hidden = !open;
    document.body.style.overflow = open ? "hidden" : "";
    if (!open && lastActive) {
      lastActive.focus();
    }
  };

  triggers.forEach((el) => {
    el.addEventListener("click", (event) => {
      event.preventDefault();
      lastActive = el;
      const preset = el.getAttribute("data-contact-category");
      if (preset && categoryInput) {
        categoryInput.value = preset;
      }
      if (result) result.textContent = "";
      setOpen(true);
    });
  });

  closeTargets.forEach((el) => {
    el.addEventListener("click", () => setOpen(false));
  });

  document.addEventListener("keydown", (event) => {
    if (event.key === "Escape" && !modal.hidden) {
      setOpen(false);
    }
  });

  if (form) {
    form.addEventListener("submit", async (event) => {
      event.preventDefault();
      const data = new FormData(form);

      try {
        const response = await fetch(form.action, {
          method: "POST",
          body: data,
          headers: {
            "X-Requested-With": "XMLHttpRequest",
          },
        });

        const payload = await response.json();
        if (!response.ok || !payload.success) {
          if (result) result.textContent = "送出失敗，請確認欄位後再試一次。";
          return;
        }

        if (result) result.textContent = "已送出，我們會盡快與您聯繫。";
        form.reset();
      } catch (_) {
        if (result) result.textContent = "送出失敗，請稍後再試。";
      }
    });
  }
})();
