document.addEventListener('DOMContentLoaded', () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav');

  burger?.addEventListener('click', () => {
    nav.classList.toggle('open');
  });

  document.querySelectorAll('.nav a').forEach((link) => {
    link.addEventListener('click', () => nav.classList.remove('open'));
  });

  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.14 });

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

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

  const form = document.querySelector('#leadForm');
  const message = document.querySelector('.form-message');
  const submitButton = document.querySelector('.form-submit');

  form?.addEventListener('submit', async (event) => {
    event.preventDefault();
    const originalText = submitButton.textContent;
    submitButton.textContent = 'Отправка...';
    submitButton.disabled = true;
    message.textContent = '';

    try {
      const response = await fetch(form.action, {
        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 {
      submitButton.textContent = originalText;
      submitButton.disabled = false;
    }
  });
});
