const ambientReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const ambientSections = [...document.querySelectorAll('.ambient-section')];

if (!ambientReduced && 'IntersectionObserver' in window) {
  const ambientObserver = new IntersectionObserver((entries) => entries.forEach((entry) => {
    entry.target.classList.toggle('is-ambient-active', entry.isIntersecting && !document.hidden);
  }), { threshold: .08 });
  ambientSections.forEach((section) => ambientObserver.observe(section));
  document.addEventListener('visibilitychange', () => {
    ambientSections.forEach((section) => {
      const bounds = section.getBoundingClientRect();
      section.classList.toggle('is-ambient-active', !document.hidden && bounds.bottom > 0 && bounds.top < window.innerHeight);
    });
  });
} else if (!ambientReduced) {
  ambientSections.forEach((section) => section.classList.add('is-ambient-active'));
}