document.addEventListener('DOMContentLoaded', () => {
  const header = document.querySelector('.site-header');
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav');

  if (burger && nav) {
    burger.addEventListener('click', () => {
      const opened = burger.getAttribute('aria-expanded') === 'true';
      burger.setAttribute('aria-expanded', String(!opened));
      nav.classList.toggle('is-open');
      document.body.classList.toggle('menu-open');
    });

    nav.querySelectorAll('a').forEach((link) => {
      link.addEventListener('click', () => {
        nav.classList.remove('is-open');
        burger.setAttribute('aria-expanded', 'false');
        document.body.classList.remove('menu-open');
      });
    });
  }

  const revealItems = document.querySelectorAll('.reveal');
  const revealObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.classList.add('is-visible');
        revealObserver.unobserve(entry.target);
      }
    });
  }, { threshold: 0.14 });

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

  const faqItems = document.querySelectorAll('.faq-item');
  faqItems.forEach((item) => {
    const question = item.querySelector('.faq-question');
    question.addEventListener('click', () => {
      const isActive = item.classList.contains('active');
      faqItems.forEach((faq) => faq.classList.remove('active'));
      if (!isActive) item.classList.add('active');
    });
  });

  const form = document.querySelector('.contact-form');
  const message = document.querySelector('.form-message');

  if (form && message) {
    form.addEventListener('submit', async (event) => {
      event.preventDefault();

      const button = form.querySelector('button[type="submit"]');
      const originalText = button.textContent;
      const formData = new FormData(form);

      button.disabled = true;
      button.textContent = 'Отправка...';
      message.textContent = '';
      message.className = 'form-message';

      try {
        const response = await fetch(form.action, {
          method: 'POST',
          body: formData,
          headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });

        const data = await response.json();

        if (response.ok && data.success) {
          message.textContent = data.message || 'Заявка отправлена. Мы скоро свяжемся с вами.';
          message.classList.add('success');
          form.reset();
        } else {
          message.textContent = data.message || 'Не получилось отправить заявку. Попробуйте ещё раз.';
          message.classList.add('error');
        }
      } catch (error) {
        message.textContent = 'Ошибка соединения. Проверьте интернет или попробуйте позже.';
        message.classList.add('error');
      } finally {
        button.disabled = false;
        button.textContent = originalText;
      }
    });
  }

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