document.addEventListener('DOMContentLoaded', () => {
  const header = document.querySelector('.site-header');
  const revealItems = document.querySelectorAll('[data-reveal]');
  const faqItems = document.querySelectorAll('.faq-item');
  const forms = document.querySelectorAll('form[data-ajax-form]');

  function updateHeader() {
    header.classList.toggle('scrolled', window.scrollY > 24);
  }
  updateHeader();
  window.addEventListener('scroll', updateHeader, { passive: true });

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

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

  forms.forEach((form) => {
    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      const button = form.querySelector('button[type="submit"]');
      const status = form.querySelector('.form-status');
      const originalText = button.textContent;
      button.disabled = true;
      button.textContent = 'Отправка...';
      status.textContent = '';
      status.className = 'form-status';
      try {
        const response = await fetch('send.php', { method: 'POST', body: new FormData(form) });
        const result = await response.json();
        status.textContent = result.message || 'Заявка отправлена.';
        status.classList.add(result.success ? 'success' : 'error');
        if (result.success) form.reset();
      } catch (error) {
        status.textContent = 'Ошибка соединения. Попробуйте еще раз.';
        status.classList.add('error');
      } finally {
        button.disabled = false;
        button.textContent = originalText;
      }
    });
  });
});
