document.addEventListener('DOMContentLoaded', () => {
  const revealItems = document.querySelectorAll('[data-reveal]');
  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));

  document.querySelectorAll('.faq-question').forEach((button) => {
    button.addEventListener('click', () => {
      const item = button.closest('.faq-item');
      document.querySelectorAll('.faq-item').forEach((el) => {
        if (el !== item) el.classList.remove('open');
      });
      item.classList.toggle('open');
    });
  });

  document.querySelectorAll('a[href^="#"]').forEach((link) => {
    link.addEventListener('click', (e) => {
      const target = document.querySelector(link.getAttribute('href'));
      if (target) {
        e.preventDefault();
        target.scrollIntoView({ behavior: 'smooth' });
      }
    });
  });

  const form = document.querySelector('.lead-form');
  if (form) {
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const button = form.querySelector('button[type="submit"]');
      const message = form.querySelector('.form-message');
      const initialText = button.textContent;
      button.textContent = 'Отправка...';
      button.disabled = true;
      message.textContent = '';
      try {
        const response = await fetch('send.php', { method: 'POST', body: new FormData(form) });
        const result = await response.json();
        message.textContent = result.message || 'Готово';
        message.className = 'form-message ' + (result.ok ? 'success' : 'error');
        if (result.ok) form.reset();
      } catch (error) {
        message.textContent = 'Связь не прошла. Позвоните нам напрямую.';
        message.className = 'form-message error';
      } finally {
        button.textContent = initialText;
        button.disabled = false;
      }
    });
  }
});