const revealElements = 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 });

revealElements.forEach((el) => revealObserver.observe(el));

document.querySelectorAll('.faq-item').forEach((button) => {
  button.addEventListener('click', () => {
    const panel = button.nextElementSibling;
    const isActive = button.classList.contains('active');

    document.querySelectorAll('.faq-item').forEach((item) => {
      item.classList.remove('active');
      item.nextElementSibling.style.maxHeight = null;
    });

    if (!isActive) {
      button.classList.add('active');
      panel.style.maxHeight = panel.scrollHeight + 'px';
    }
  });
});

const form = document.getElementById('leadForm');
const message = document.getElementById('formMessage');

if (form) {
  form.addEventListener('submit', async (event) => {
    event.preventDefault();

    const submitButton = form.querySelector('button[type="submit"]');
    const defaultText = submitButton.textContent;
    submitButton.textContent = 'Отправка...';
    submitButton.disabled = true;
    message.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 || 'Не удалось отправить заявку.');
      }

      message.textContent = result.message || 'Спасибо! Мы скоро свяжемся с вами.';
      form.reset();
    } catch (error) {
      message.textContent = error.message || 'Ошибка отправки. Попробуйте позже.';
    } finally {
      submitButton.textContent = defaultText;
      submitButton.disabled = false;
    }
  });
}
