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');
      const opened = item.classList.contains('faq__item--open');
      document.querySelectorAll('.faq__item').forEach((el) => el.classList.remove('faq__item--open'));
      if (!opened) item.classList.add('faq__item--open');
    });
  });

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

  const form = document.querySelector('.lead-form');
  const status = document.querySelector('.form-status');
  if (form) {
    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      const button = form.querySelector('button[type="submit"]');
      const oldText = button.textContent;
      button.textContent = 'Отправка...';
      button.disabled = true;
      status.textContent = '';
      try {
        const response = await fetch('send.php', { method: 'POST', body: new FormData(form) });
        const data = await response.json();
        status.textContent = data.message || 'Спасибо! Мы свяжемся с вами.';
        status.className = 'form-status form-status--success';
        if (data.success) form.reset();
      } catch (error) {
        status.textContent = 'Не удалось отправить форму. Позвоните нам напрямую.';
        status.className = 'form-status form-status--error';
      } finally {
        button.textContent = oldText;
        button.disabled = false;
      }
    });
  }
});
