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

  const onScroll = () => {
    header?.classList.toggle('is-scrolled', window.scrollY > 18);
  };
  onScroll();
  window.addEventListener('scroll', onScroll, { passive: true });

  navToggle?.addEventListener('click', () => {
    nav?.classList.toggle('is-open');
    navToggle.classList.toggle('is-active');
  });

  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', e => {
      const target = document.querySelector(anchor.getAttribute('href'));
      if (!target) return;
      e.preventDefault();
      nav?.classList.remove('is-open');
      navToggle?.classList.remove('is-active');
      target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  });

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

  document.querySelectorAll('.faq-item').forEach(item => {
    const button = item.querySelector('.faq-question');
    button?.addEventListener('click', () => {
      const isOpen = item.classList.contains('is-open');
      document.querySelectorAll('.faq-item').forEach(el => el.classList.remove('is-open'));
      if (!isOpen) item.classList.add('is-open');
    });
  });

  document.querySelectorAll('form[data-lead-form]').forEach(form => {
    const note = form.querySelector('.form-note');
    const submit = form.querySelector('button[type="submit"]');
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const originalText = submit.textContent;
      submit.disabled = true;
      submit.textContent = 'Отправка...';
      note.textContent = '';
      try {
        const response = await fetch('send.php', { method: 'POST', body: new FormData(form) });
        const result = await response.json();
        if (!response.ok || !result.success) throw new Error(result.message || 'Ошибка отправки');
        note.textContent = 'Спасибо! Мы свяжемся с вами в течение 10 минут.';
        form.reset();
      } catch (error) {
        note.textContent = 'Не удалось отправить заявку. Позвоните нам или попробуйте ещё раз.';
      } finally {
        submit.disabled = false;
        submit.textContent = originalText;
      }
    });
  });
});