const header = document.querySelector('.site-header');
const revealItems = document.querySelectorAll('.reveal');
const faqButtons = document.querySelectorAll('.faq-item');
const forms = document.querySelectorAll('.lead-form');

window.addEventListener('scroll', () => {
  header.classList.toggle('scrolled', window.scrollY > 24);
});

const revealObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
      revealObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.14 });

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

faqButtons.forEach(button => {
  button.addEventListener('click', () => {
    const panel = button.nextElementSibling;
    const isOpen = button.classList.contains('active');
    faqButtons.forEach(btn => {
      btn.classList.remove('active');
      if (btn.nextElementSibling) btn.nextElementSibling.classList.remove('open');
    });
    if (!isOpen) {
      button.classList.add('active');
      panel.classList.add('open');
    }
  });
});

forms.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.disabled = true;
    button.textContent = 'Отправка...';
    message.textContent = '';

    try {
      const response = await fetch(form.action, {
        method: 'POST',
        body: new FormData(form),
        headers: { 'Accept': 'application/json' }
      });
      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 = originalText;
    }
  });
});
