document.addEventListener("DOMContentLoaded", () => {
  const body = document.body;
  const header = document.querySelector(".site-header");
  const hamburger = document.querySelector(".hamburger");
  const mobileMenu = document.querySelector(".mobile-menu");

  const setHeaderState = () => {
    if (!header) return;
    header.classList.toggle("is-scrolled", window.scrollY > 18);
  };
  setHeaderState();
  window.addEventListener("scroll", setHeaderState, { passive: true });

  if (hamburger && mobileMenu) {
    const closeMenu = () => {
      hamburger.classList.remove("is-active");
      hamburger.setAttribute("aria-expanded", "false");
      mobileMenu.classList.remove("is-open");
      mobileMenu.setAttribute("aria-hidden", "true");
      body.classList.remove("menu-open");
    };

    hamburger.addEventListener("click", () => {
      const isOpen = hamburger.classList.toggle("is-active");
      hamburger.setAttribute("aria-expanded", String(isOpen));
      mobileMenu.classList.toggle("is-open", isOpen);
      mobileMenu.setAttribute("aria-hidden", String(!isOpen));
      body.classList.toggle("menu-open", isOpen);
    });

    mobileMenu.querySelectorAll("a").forEach((link) => {
      link.addEventListener("click", closeMenu);
    });

    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape") closeMenu();
    });
  }

  const revealElements = [
    ...document.querySelectorAll(".reveal"),
    ...document.querySelectorAll(".reveal-group > *")
  ];

  if ("IntersectionObserver" in window) {
    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.16, rootMargin: "0px 0px -40px 0px" });

    revealElements.forEach((element) => revealObserver.observe(element));
  } else {
    revealElements.forEach((element) => element.classList.add("is-visible"));
  }

  const faqItems = document.querySelectorAll(".faq-item");
  faqItems.forEach((item) => {
    const button = item.querySelector("button");
    const answer = item.querySelector(".faq-answer");
    if (!button || !answer) return;

    button.addEventListener("click", () => {
      const isOpen = item.classList.contains("is-open");

      faqItems.forEach((otherItem) => {
        const otherAnswer = otherItem.querySelector(".faq-answer");
        otherItem.classList.remove("is-open");
        if (otherAnswer) otherAnswer.style.maxHeight = null;
      });

      if (!isOpen) {
        item.classList.add("is-open");
        answer.style.maxHeight = `${answer.scrollHeight}px`;
      }
    });
  });

  const lightbox = document.querySelector(".lightbox");
  const lightboxImg = lightbox?.querySelector("img");
  const closeButton = lightbox?.querySelector(".lightbox-close");
  const prevButton = lightbox?.querySelector(".lightbox-prev");
  const nextButton = lightbox?.querySelector(".lightbox-next");

  const galleryItems = [...document.querySelectorAll("[data-lightbox]")].map((card) => {
    const image = card.querySelector("img");
    return {
      trigger: card,
      src: image?.getAttribute("data-full") || image?.getAttribute("src"),
      alt: image?.getAttribute("alt") || ""
    };
  }).filter((item) => item.src);

  let currentIndex = 0;

  const showImage = (index) => {
    if (!lightbox || !lightboxImg || galleryItems.length === 0) return;
    currentIndex = (index + galleryItems.length) % galleryItems.length;
    lightboxImg.src = galleryItems[currentIndex].src;
    lightboxImg.alt = galleryItems[currentIndex].alt;
  };

  const openLightbox = (index) => {
    if (!lightbox || !lightboxImg) return;
    showImage(index);
    lightbox.classList.add("is-open");
    lightbox.setAttribute("aria-hidden", "false");
    body.classList.add("lightbox-open");
    closeButton?.focus();
  };

  const closeLightbox = () => {
    if (!lightbox || !lightboxImg) return;
    lightbox.classList.remove("is-open");
    lightbox.setAttribute("aria-hidden", "true");
    body.classList.remove("lightbox-open");
    lightboxImg.src = "";
  };

  galleryItems.forEach((item, index) => {
    item.trigger.addEventListener("click", () => openLightbox(index));
  });

  closeButton?.addEventListener("click", closeLightbox);
  prevButton?.addEventListener("click", () => showImage(currentIndex - 1));
  nextButton?.addEventListener("click", () => showImage(currentIndex + 1));

  lightbox?.addEventListener("click", (event) => {
    if (event.target === lightbox) closeLightbox();
  });

  document.addEventListener("keydown", (event) => {
    if (!lightbox?.classList.contains("is-open")) return;

    if (event.key === "Escape") closeLightbox();
    if (event.key === "ArrowLeft") showImage(currentIndex - 1);
    if (event.key === "ArrowRight") showImage(currentIndex + 1);
  });

  document.querySelectorAll(".lead-form").forEach((form) => {
    const submitButton = form.querySelector("button[type='submit']");
    const status = form.querySelector(".form-status");
    const originalText = submitButton?.textContent || "Отправить";

    form.addEventListener("submit", async (event) => {
      event.preventDefault();
      if (!submitButton || !status) return;

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

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

        const data = await response.json().catch(() => ({
          success: false,
          message: "Не удалось обработать ответ сервера."
        }));

        if (!response.ok || !data.success) {
          throw new Error(data.message || "Заявка не отправлена. Попробуйте позже.");
        }

        status.textContent = data.message || "Спасибо! Заявка отправлена.";
        form.reset();
      } catch (error) {
        status.textContent = error.message || "Ошибка отправки. Напишите нам напрямую по телефону.";
      } finally {
        submitButton.disabled = false;
        submitButton.textContent = originalText;
      }
    });
  });
});
