const body = document.body;
const burger = document.querySelector(".burger");
const navLinks = document.querySelectorAll(".nav a");

if (burger) {
  burger.addEventListener("click", () => {
    body.classList.toggle("menu-open");
  });
}

navLinks.forEach((link) => {
  link.addEventListener("click", () => body.classList.remove("menu-open"));
});

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

reveals.forEach((el, index) => {
  el.style.transitionDelay = `${Math.min(index % 3, 2) * 100}ms`;
  observer.observe(el);
});

document.querySelectorAll(".faq-question").forEach((button) => {
  button.addEventListener("click", () => {
    const current = button.closest(".faq-item");
    const answer = current.querySelector(".faq-answer");
    const wasActive = current.classList.contains("active");

    document.querySelectorAll(".faq-item").forEach((item) => {
      item.classList.remove("active");
      item.querySelector(".faq-answer").style.maxHeight = null;
    });

    if (!wasActive) {
      current.classList.add("active");
      answer.style.maxHeight = `${answer.scrollHeight}px`;
    }
  });
});

document.querySelectorAll(".lead-form").forEach((form) => {
  form.addEventListener("submit", async (event) => {
    event.preventDefault();

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

    button.disabled = true;
    button.textContent = "Отправка...";
    status.textContent = "";

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

      const result = await response.json();

      if (!response.ok || !result.success) {
        throw new Error(result.message || "Заявка не отправлена.");
      }

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