
const revealItems = document.querySelectorAll('[data-reveal]');
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add('is-visible');
      observer.unobserve(entry.target);
    }
  });
}, { threshold: 0.12 });

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

document.querySelectorAll('.faq-question').forEach((button) => {
  button.addEventListener('click', () => {
    const current = button.closest('.faq-item');
    document.querySelectorAll('.faq-item').forEach((item) => {
      if (item !== current) item.classList.remove('active');
    });
    current.classList.toggle('active');
  });
});

document.querySelectorAll('[data-tab]').forEach((tab) => {
  tab.addEventListener('click', () => {
    const id = tab.dataset.tab;
    document.querySelectorAll('[data-tab]').forEach((item) => item.classList.remove('active'));
    document.querySelectorAll('[data-panel]').forEach((panel) => panel.classList.remove('active'));
    tab.classList.add('active');
    document.querySelector(`[data-panel="${id}"]`)?.classList.add('active');
  });
});

document.querySelectorAll('a[href^="#"]').forEach((link) => {
  link.addEventListener('click', (e) => {
    const target = document.querySelector(link.getAttribute('href'));
    if (!target) return;
    e.preventDefault();
    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
  });
});

const form = document.querySelector('.lead-form');
const message = document.querySelector('.form-message');

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

    const btn = form.querySelector('button[type="submit"]');
    const original = btn.textContent;
    btn.textContent = 'Отправка...';
    btn.disabled = true;
    message.textContent = '';

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

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

      form.reset();
      message.textContent = data.message || 'Заявка отправлена. Мы скоро свяжемся с вами.';
      message.className = 'form-message success';
    } catch (error) {
      message.textContent = error.message || 'Ошибка отправки. Попробуйте позже.';
      message.className = 'form-message error';
    } finally {
      btn.textContent = original;
      btn.disabled = false;
    }
  });
}
