const revealItems = document.querySelectorAll('.reveal');
const revealObserver = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
      revealObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.15 });

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

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

const burger = document.querySelector('.burger');
const nav = document.querySelector('.nav');
if (burger && nav) {
  burger.addEventListener('click', () => nav.classList.toggle('open'));
}

const form = document.querySelector('.lead-form');
if (form) {
  const message = form.querySelector('.form-message');
  const submit = form.querySelector('button[type="submit"]');
  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    message.textContent = '';
    const originalText = submit.textContent;
    submit.textContent = 'Отправка...';
    submit.disabled = true;

    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 || 'Не удалось отправить заявку.');
      }
      message.textContent = result.message || 'Спасибо! Мы скоро свяжемся с вами.';
      form.reset();
    } catch (error) {
      message.textContent = error.message || 'Ошибка отправки. Позвоните нам напрямую.';
    } finally {
      submit.textContent = originalText;
      submit.disabled = false;
    }
  });
}
