document.addEventListener('DOMContentLoaded', () => {
  const header = document.querySelector('.site-header');
  const navToggle = document.querySelector('.nav-toggle');
  const nav = document.querySelector('.nav');
  const navLinks = document.querySelectorAll('.nav a');

  const setHeaderState = () => {
    if (!header) return;
    header.classList.toggle('is-scrolled', window.scrollY > 18);
  };

  setHeaderState();
  window.addEventListener('scroll', setHeaderState, { passive: true });

  if (navToggle && nav) {
    navToggle.addEventListener('click', () => {
      const isOpen = nav.classList.toggle('is-open');
      document.body.classList.toggle('menu-open', isOpen);
      navToggle.setAttribute('aria-expanded', String(isOpen));
    });

    navLinks.forEach((link) => {
      link.addEventListener('click', () => {
        nav.classList.remove('is-open');
        document.body.classList.remove('menu-open');
        navToggle.setAttribute('aria-expanded', 'false');
      });
    });
  }

  const revealItems = document.querySelectorAll('.reveal');
  if ('IntersectionObserver' in window) {
    const observer = new IntersectionObserver((entries, obs) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('is-visible');
          obs.unobserve(entry.target);
        }
      });
    }, { threshold: 0.14, rootMargin: '0px 0px -8% 0px' });

    revealItems.forEach((item) => observer.observe(item));
  } else {
    revealItems.forEach((item) => item.classList.add('is-visible'));
  }

  const faqButtons = document.querySelectorAll('.faq-button');
  faqButtons.forEach((button) => {
    button.addEventListener('click', () => {
      const item = button.closest('.faq-item');
      const panel = item.querySelector('.faq-panel');
      const isOpen = item.classList.contains('is-open');

      document.querySelectorAll('.faq-item.is-open').forEach((openItem) => {
        if (openItem !== item) {
          openItem.classList.remove('is-open');
          openItem.querySelector('.faq-button').setAttribute('aria-expanded', 'false');
          const openPanel = openItem.querySelector('.faq-panel');
          openPanel.style.maxHeight = null;
        }
      });

      item.classList.toggle('is-open', !isOpen);
      button.setAttribute('aria-expanded', String(!isOpen));
      panel.style.maxHeight = !isOpen ? `${panel.scrollHeight}px` : null;
    });
  });

  const form = document.querySelector('.contact-form');
  if (form) {
    const submitButton = form.querySelector('button[type="submit"]');
    const message = form.querySelector('.form-message');
    const defaultText = submitButton ? submitButton.textContent : '';

    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      if (!submitButton || !message) return;

      submitButton.disabled = true;
      submitButton.textContent = 'Отправка...';
      message.textContent = '';
      message.className = 'form-message';

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

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

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