document.addEventListener('DOMContentLoaded', () => {
  const header = document.querySelector('.site-header');
  const navToggle = document.querySelector('.nav-toggle');
  const navLinks = document.querySelectorAll('.main-nav a');

  if (navToggle && header) {
    navToggle.addEventListener('click', () => {
      const isOpen = header.classList.toggle('is-open');
      navToggle.setAttribute('aria-expanded', String(isOpen));
    });
    navLinks.forEach((link) => link.addEventListener('click', () => {
      header.classList.remove('is-open');
      navToggle.setAttribute('aria-expanded', 'false');
    }));
  }

  // ScrollReveal: fade-in + translate при появлении секций в зоне видимости.
  const revealItems = document.querySelectorAll('[data-reveal]');
  const revealObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.classList.add('is-visible');
        observer.unobserve(entry.target);
      }
    });
  }, { threshold: 0.16, rootMargin: '0px 0px -40px 0px' });

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

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

    if (item.classList.contains('is-open')) {
      answer.style.maxHeight = `${answer.scrollHeight}px`;
    }

    button.addEventListener('click', () => {
      const isOpen = item.classList.contains('is-open');
      faqItems.forEach((otherItem) => {
        otherItem.classList.remove('is-open');
        otherItem.querySelector('.faq-question').setAttribute('aria-expanded', 'false');
        otherItem.querySelector('.faq-answer').style.maxHeight = null;
      });

      if (!isOpen) {
        item.classList.add('is-open');
        button.setAttribute('aria-expanded', 'true');
        answer.style.maxHeight = `${answer.scrollHeight}px`;
      }
    });
  });

  const forms = document.querySelectorAll('.lead-form');
  forms.forEach((form) => {
    const button = form.querySelector('.form-submit');
    const message = form.querySelector('.form-message');
    const defaultButtonText = button.textContent;

    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      message.textContent = '';
      message.className = 'form-message';
      button.disabled = true;
      button.textContent = 'Отправка...';

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

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

        message.textContent = data.message || 'Заявка отправлена. Мы скоро свяжемся с вами.';
        message.classList.add('is-success');
        form.reset();
      } catch (error) {
        message.textContent = error.message || 'Ошибка отправки. Попробуйте позже.';
        message.classList.add('is-error');
      } finally {
        button.disabled = false;
        button.textContent = defaultButtonText;
      }
    });
  });
});
