document.addEventListener("DOMContentLoaded", () => {
  const revealElements = document.querySelectorAll(".reveal");

  const revealObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach((entry) => {
      if (!entry.isIntersecting) return;
      entry.target.classList.add("is-visible");
      observer.unobserve(entry.target);
    });
  }, {
    threshold: 0.14,
    rootMargin: "0px 0px -60px 0px"
  });

  revealElements.forEach((element, index) => {
    element.style.transitionDelay = `${Math.min(index % 4, 3) * 80}ms`;
    revealObserver.observe(element);
  });

  const faqButtons = document.querySelectorAll(".faq-item");
  faqButtons.forEach((button) => {
    button.addEventListener("click", () => {
      const content = button.nextElementSibling;
      const isOpen = button.classList.contains("active");

      faqButtons.forEach((item) => {
        item.classList.remove("active");
        item.setAttribute("aria-expanded", "false");
        const panel = item.nextElementSibling;
        if (panel) panel.style.maxHeight = null;
      });

      if (!isOpen && content) {
        button.classList.add("active");
        button.setAttribute("aria-expanded", "true");
        content.style.maxHeight = `${content.scrollHeight}px`;
      }
    });
  });

  const forms = document.querySelectorAll("form[data-form]");
  forms.forEach((form) => {
    const submitButton = form.querySelector("button[type='submit']");
    const message = form.querySelector(".form-message");

    form.addEventListener("submit", async (event) => {
      event.preventDefault();

      const defaultText = submitButton.textContent;
      submitButton.disabled = true;
      submitButton.textContent = "Отправка...";
      if (message) {
        message.textContent = "";
        message.classList.remove("error", "success");
      }

      try {
        const response = await fetch(form.action, {
          method: "POST",
          body: new FormData(form),
          headers: { "Accept": "application/json" }
        });

        const result = await response.json();

        if (!response.ok || !result.success) {
          throw new Error(result.message || "Не удалось отправить заявку.");
        }

        if (message) {
          message.textContent = result.message || "Спасибо! Мы свяжемся с вами в ближайшее время.";
          message.classList.add("success");
        }
        form.reset();
      } catch (error) {
        if (message) {
          message.textContent = error.message || "Ошибка отправки. Попробуйте ещё раз.";
          message.classList.add("error");
        }
      } finally {
        submitButton.disabled = false;
        submitButton.textContent = defaultText;
      }
    });
  });
});
