document.addEventListener('DOMContentLoaded', () => {
  const revealItems = document.querySelectorAll('.reveal');
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.classList.add('visible');
        observer.unobserve(entry.target);
      }
    });
  }, { threshold: 0.14 });
  revealItems.forEach((item) => observer.observe(item));

  document.querySelectorAll('.accordion__item').forEach((button) => {
    button.addEventListener('click', () => {
      const isActive = button.classList.contains('active');
      document.querySelectorAll('.accordion__item').forEach((item) => {
        item.classList.remove('active');
        item.querySelector('i').textContent = '+';
      });
      if (!isActive) {
        button.classList.add('active');
        button.querySelector('i').textContent = '−';
      }
    });
  });

  const form = document.querySelector('.lead-form');
  if (form) {
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const button = form.querySelector('button[type="submit"]');
      const message = form.querySelector('.form-message');
      const defaultText = button.textContent;
      button.disabled = true;
      button.textContent = 'Отправка...';
      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 {
        button.disabled = false;
        button.textContent = defaultText;
      }
    });
  }
});