document.addEventListener("DOMContentLoaded", () => {
  const body = document.body;
  const header = document.querySelector(".site-header");
  const hamburger = document.querySelector(".hamburger");
  const nav = document.querySelector(".main-nav");
  const navLinks = document.querySelectorAll(".main-nav a");

  const syncHeader = () => {
    if (window.scrollY > 16) {
      header.classList.add("scrolled");
    } else {
      header.classList.remove("scrolled");
    }
  };

  syncHeader();
  window.addEventListener("scroll", syncHeader, { passive: true });

  if (hamburger && nav) {
    hamburger.addEventListener("click", () => {
      const isOpen = body.classList.toggle("menu-open");
      hamburger.setAttribute("aria-expanded", String(isOpen));
      hamburger.setAttribute("aria-label", isOpen ? "Закрыть меню" : "Открыть меню");
    });

    navLinks.forEach((link) => {
      link.addEventListener("click", () => {
        body.classList.remove("menu-open");
        hamburger.setAttribute("aria-expanded", "false");
        hamburger.setAttribute("aria-label", "Открыть меню");
      });
    });
  }

  const revealElements = document.querySelectorAll(".reveal");
  if ("IntersectionObserver" in window) {
    const revealObserver = new IntersectionObserver(
      (entries, observer) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            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) * 0.08}s`;
      revealObserver.observe(element);
    });
  } else {
    revealElements.forEach((element) => element.classList.add("is-visible"));
  }

  const faqItems = document.querySelectorAll(".faq-item");
  faqItems.forEach((item) => {
    const question = item.querySelector(".faq-question");
    const answer = item.querySelector(".faq-answer");

    question.addEventListener("click", () => {
      const shouldOpen = !item.classList.contains("active");

      faqItems.forEach((otherItem) => {
        otherItem.classList.remove("active");
        otherItem.querySelector(".faq-question").setAttribute("aria-expanded", "false");
        const otherAnswer = otherItem.querySelector(".faq-answer");
        if (otherAnswer) {
          otherAnswer.style.maxHeight = null;
        }
      });

      if (shouldOpen) {
        item.classList.add("active");
        question.setAttribute("aria-expanded", "true");
        if (answer) {
          answer.style.maxHeight = `${answer.scrollHeight}px`;
        }
      }
    });

    if (item.classList.contains("active") && answer) {
      answer.style.maxHeight = `${answer.scrollHeight}px`;
    }
  });

  const galleryCards = Array.from(document.querySelectorAll("[data-gallery]"));
  const lightbox = document.querySelector("#lightbox");
  const lightboxImg = document.querySelector(".lightbox-img");
  const lightboxCaption = document.querySelector(".lightbox-caption");
  const closeBtn = document.querySelector(".lightbox-close");
  const prevBtn = document.querySelector(".lightbox-prev");
  const nextBtn = document.querySelector(".lightbox-next");

  let currentIndex = 0;

  const galleryItems = galleryCards.map((card) => {
    const img = card.querySelector("img");
    const title = card.querySelector("h3")?.textContent?.trim() || img.alt || "Изображение";
    const description = card.querySelector("p")?.textContent?.trim() || "";
    return {
      src: img.src,
      alt: img.alt || title,
      caption: description ? `${title} — ${description}` : title,
    };
  });

  const renderLightbox = () => {
    const item = galleryItems[currentIndex];
    if (!item || !lightboxImg || !lightboxCaption) return;
    lightboxImg.src = item.src;
    lightboxImg.alt = item.alt;
    lightboxCaption.textContent = item.caption;
  };

  const openLightbox = (index) => {
    if (!lightbox || !galleryItems.length) return;
    currentIndex = index;
    renderLightbox();
    lightbox.classList.add("open");
    lightbox.setAttribute("aria-hidden", "false");
    body.classList.add("lightbox-open");
    closeBtn?.focus();
  };

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

  const showPrev = () => {
    currentIndex = (currentIndex - 1 + galleryItems.length) % galleryItems.length;
    renderLightbox();
  };

  const showNext = () => {
    currentIndex = (currentIndex + 1) % galleryItems.length;
    renderLightbox();
  };

  galleryCards.forEach((card, index) => {
    card.addEventListener("click", () => openLightbox(index));
    card.addEventListener("keydown", (event) => {
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        openLightbox(index);
      }
    });
  });

  closeBtn?.addEventListener("click", closeLightbox);
  prevBtn?.addEventListener("click", showPrev);
  nextBtn?.addEventListener("click", showNext);

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

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

    if (event.key === "Escape") {
      closeLightbox();
    }

    if (event.key === "ArrowLeft") {
      showPrev();
    }

    if (event.key === "ArrowRight") {
      showNext();
    }
  });

  const form = document.querySelector("#lead-form");
  const status = document.querySelector(".form-status");
  const submitBtn = document.querySelector(".form-submit");

  if (form && status && submitBtn) {
    form.addEventListener("submit", async (event) => {
      event.preventDefault();

      const phoneInput = form.querySelector("#phone");
      const nameInput = form.querySelector("#name");
      const phoneDigits = phoneInput.value.replace(/\D/g, "");

      status.classList.remove("error");
      status.textContent = "";

      if (nameInput.value.trim().length < 2) {
        status.classList.add("error");
        status.textContent = "Пожалуйста, укажите имя.";
        nameInput.focus();
        return;
      }

      if (phoneDigits.length < 10) {
        status.classList.add("error");
        status.textContent = "Пожалуйста, укажите корректный телефон.";
        phoneInput.focus();
        return;
      }

      const originalText = submitBtn.textContent;
      submitBtn.disabled = true;
      submitBtn.textContent = "Отправка...";

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

        const data = await response.json().catch(() => ({}));

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

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