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

  if (header && navToggle) {
    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: плавное появление элементов при скролле.
  const revealElements = document.querySelectorAll('[data-reveal]');
  const observer = new IntersectionObserver((entries, revealObserver) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.classList.add('is-visible');
        revealObserver.unobserve(entry.target);
      }
    });
  }, { threshold: 0.14, rootMargin: '0px 0px -48px 0px' });

  revealElements.forEach((element, index) => {
    element.style.transitionDelay = `${Math.min((index % 5) * 70, 280)}ms`;
    observer.observe(element);
  });

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

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

    question.addEventListener('click', () => {
      const wasOpen = item.classList.contains('is-open');

      faqItems.forEach((faq) => {
        faq.classList.remove('is-open');
        faq.querySelector('.faq-question').setAttribute('aria-expanded', 'false');
        faq.querySelector('.faq-answer').style.maxHeight = null;
      });

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

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

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

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

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

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