const header = document.querySelector('[data-header]');
const setHeader = () => header && header.classList.toggle('is-scrolled', window.scrollY > 24);
setHeader();
window.addEventListener('scroll', setHeader, { passive: true });

const revealItems = document.querySelectorAll('[data-reveal]');
const revealObserver = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add('is-visible');
      revealObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.16, rootMargin: '0px 0px -60px 0px' });
revealItems.forEach((item, index) => {
  item.style.transitionDelay = `${Math.min(index % 4, 3) * 80}ms`;
  revealObserver.observe(item);
});

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

    document.querySelectorAll('.accordion__item').forEach((other) => {
      other.classList.remove('is-open');
      other.querySelector('button').setAttribute('aria-expanded', 'false');
      other.querySelector('.accordion__content').style.maxHeight = null;
    });

    if (!isOpen) {
      item.classList.add('is-open');
      button.setAttribute('aria-expanded', 'true');
      content.style.maxHeight = `${content.scrollHeight}px`;
    }
  });
});

// Подмена локальных SVG на Unsplash-фото при наличии интернета.
document.querySelectorAll('img[data-remote-src]').forEach((img) => {
  const remote = new Image();
  remote.onload = () => { img.src = img.dataset.remoteSrc; };
  remote.onerror = () => {};
  remote.src = img.dataset.remoteSrc;
});

document.querySelectorAll('.lead-form').forEach((form) => {
  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    const button = form.querySelector('button[type="submit"]');
    const message = form.querySelector('.form-message');
    const formData = new FormData(form);
    const originalText = button.textContent;

    message.textContent = '';
    message.className = 'form-message';

    if (!formData.get('name')?.trim() || !formData.get('phone')?.trim()) {
      message.textContent = 'Заполните имя и телефон.';
      message.classList.add('is-error');
      return;
    }

    button.disabled = true;
    button.textContent = 'Отправка...';

    try {
      const response = await fetch(form.action, { method: 'POST', body: formData, headers: { 'Accept': 'application/json' } });
      const data = await response.json();
      if (!response.ok || !data.ok) throw new Error(data.message || 'Ошибка отправки.');
      message.textContent = data.message || 'Заявка отправлена. Мы скоро свяжемся с вами.';
      message.classList.add('is-success');
      form.reset();
    } catch (error) {
      message.textContent = error.message || 'Не удалось отправить заявку. Позвоните нам напрямую.';
      message.classList.add('is-error');
    } finally {
      button.disabled = false;
      button.textContent = originalText;
    }
  });
});
