document.addEventListener('DOMContentLoaded', () => {
  const revealItems = document.querySelectorAll('[data-reveal]');
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.classList.add('revealed');
        observer.unobserve(entry.target);
      }
    });
  }, { threshold: 0.12, rootMargin: '0px 0px -50px 0px' });

  revealItems.forEach((item) => observer.observe(item));

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

    button.addEventListener('click', () => {
      const isOpen = item.classList.contains('active');
      faqItems.forEach((faqItem) => {
        faqItem.classList.remove('active');
        faqItem.querySelector('.faq-answer').style.maxHeight = null;
      });

      if (!isOpen) {
        item.classList.add('active');
        answer.style.maxHeight = `${answer.scrollHeight}px`;
      }
    });
  });

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

  if (form) {
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const submitButton = form.querySelector('button[type="submit"]');
      const defaultText = submitButton.textContent;
      submitButton.disabled = true;
      submitButton.textContent = 'Отправка...';
      formMessage.textContent = '';
      formMessage.className = 'form-message';

      try {
        const response = await fetch('send.php', {
          method: 'POST',
          body: new FormData(form)
        });
        const result = await response.json();

        if (response.ok && result.success) {
          formMessage.textContent = result.message || 'Заявка отправлена.';
          formMessage.classList.add('success');
          form.reset();
        } else {
          throw new Error(result.message || 'Ошибка отправки формы.');
        }
      } catch (error) {
        formMessage.textContent = error.message || 'Попробуйте отправить заявку ещё раз.';
        formMessage.classList.add('error');
      } finally {
        submitButton.disabled = false;
        submitButton.textContent = defaultText;
      }
    });
  }

  const menuToggle = document.querySelector('.menu-toggle');
  const nav = document.querySelector('.nav');
  if (menuToggle && nav) {
    menuToggle.addEventListener('click', () => nav.classList.toggle('is-open'));
    nav.querySelectorAll('a').forEach((link) => {
      link.addEventListener('click', () => nav.classList.remove('is-open'));
    });
  }
});
