(() => {
  function initFaqItem(item) {
    const summary = item.querySelector("summary");
    const answer = item.querySelector(".faq-answer");
    if (!summary || !answer) {
      return;
    }

    let isAnimating = false;

    summary.addEventListener("click", (event) => {
      event.preventDefault();
      if (isAnimating) {
        return;
      }

      if (!item.open) {
        item.open = true;
        item.classList.remove("is-closing");
        item.classList.add("is-opening");
        const finishOpen = () => {
          item.classList.remove("is-opening");
          isAnimating = false;
        };
        isAnimating = true;
        answer.addEventListener("animationend", finishOpen, { once: true });
        window.setTimeout(
          finishOpen,
          window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 360,
        );
        return;
      }

      isAnimating = true;
      item.classList.remove("is-opening");
      item.classList.add("is-closing");
      const finishClose = () => {
        item.classList.remove("is-closing");
        item.open = false;
        isAnimating = false;
      };
      answer.addEventListener("animationend", finishClose, { once: true });
      window.setTimeout(
        finishClose,
        window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 360,
      );
    });
  }

  document.addEventListener("DOMContentLoaded", () => {
    document.querySelectorAll(".faq-item").forEach(initFaqItem);
  });
})();
