document.addEventListener('DOMContentLoaded', () => {
  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.14 });

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

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

  document.querySelectorAll('form[data-form]').forEach((form) => {
    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      const button = form.querySelector('button[type="submit"]');
      const message = form.querySelector('.form-message');
      const originalText = button.textContent;

      message.textContent = '';
      message.className = 'form-message';
      button.disabled = true;
      button.textContent = 'Отправка...';

      try {
        const response = await fetch('send.php', {
          method: 'POST',
          body: new FormData(form),
        });
        const result = await response.json();
        message.textContent = result.message || 'Заявка отправлена.';
        message.classList.add(result.success ? 'success' : 'error');
        if (result.success) form.reset();
      } catch (error) {
        message.textContent = 'Не удалось отправить заявку. Попробуйте позже или позвоните.';
        message.classList.add('error');
      } finally {
        button.disabled = false;
        button.textContent = originalText;
      }
    });
  });
});
