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 icon = button.querySelector('i');
    const isOpen = panel.style.maxHeight;

    document.querySelectorAll('.faq-panel').forEach((item) => item.style.maxHeight = null);
    document.querySelectorAll('.faq-item i').forEach((item) => item.textContent = '+');

    if (!isOpen) {
      panel.style.maxHeight = panel.scrollHeight + 'px';
      icon.textContent = '−';
    }
  });
});

document.querySelectorAll('.lead-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;

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

    try {
      const response = await fetch(form.action, {
        method: 'POST',
        body: new FormData(form)
      });
      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.message || 'Не удалось отправить заявку');
      }

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