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.12 });
  revealItems.forEach(item => observer.observe(item));

  document.querySelectorAll('.accordion button').forEach(button => {
    button.addEventListener('click', () => {
      const isOpen = button.classList.contains('open');
      document.querySelectorAll('.accordion button').forEach(item => {
        item.classList.remove('open');
        item.querySelector('span').textContent = '+';
      });
      if (!isOpen) {
        button.classList.add('open');
        button.querySelector('span').textContent = '−';
      }
    });
  });

  document.querySelectorAll('form').forEach(form => {
    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      const button = form.querySelector('button[type="submit"]');
      const message = form.querySelector('.form-message');
      const initialText = button.textContent;
      button.textContent = 'Отправка...';
      button.disabled = true;
      message.textContent = '';
      try {
        const response = await fetch(form.action, { method: 'POST', body: new FormData(form) });
        const result = await response.json();
        message.textContent = result.message || 'Заявка отправлена.';
        if (result.success) form.reset();
      } catch (error) {
        message.textContent = 'Не удалось отправить заявку. Позвоните нам или попробуйте позже.';
      } finally {
        button.textContent = initialText;
        button.disabled = false;
      }
    });
  });
});
