/**
 * scroll-reveal.js
 * IntersectionObserver for revealing elements on scroll.
 * Adds 90ms stagger delay per sibling index within each reveal-group.
 */

export function initScrollReveal() {
  'use strict';

  const revealElements = document.querySelectorAll('.reveal');
  if (!revealElements.length) return;

  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (!entry.isIntersecting) return;

      const el = entry.target;
      const parent = el.parentElement;
      const siblings = parent
        ? Array.from(parent.querySelectorAll(':scope > .reveal'))
        : [];
      const index = siblings.indexOf(el);
      const delay = index >= 0 ? index * 90 : 0;

      el.style.transitionDelay = delay + 'ms';
      el.classList.add('revealed');

      // Remove inline delay after transition so hover transitions are unaffected
      const cleanup = () => {
        el.style.transitionDelay = '';
        el.removeEventListener('transitionend', cleanup);
      };
      el.addEventListener('transitionend', cleanup);

      observer.unobserve(el);
    });
  }, { threshold: 0.1 });

  revealElements.forEach((el) => observer.observe(el));
}
