// Scroll-entrance reveal for the intensives page.
// Namespace: ix-* — no collision with community .reveal system.
//
// Design contract:
//   • Default/resting state = fully visible (no-JS safe, no SSR flash).
//   • ix-pending only added for sections that are genuinely off-screen at mount time.
//   • requestAnimationFrame ensures the browser commits ix-pending before we observe,
//     eliminating the race condition where the observer fires before the first paint.
//   • Animates once then unobserves. Cleans up on unmount.
//   • prefers-reduced-motion: reduce = no animation at all.

const useReveal = () => {
  const ref = React.useRef(null);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    // Don't animate sections already in view when the page loads —
    // avoids any blank-flash risk for above-fold or near-fold content.
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight * 0.88) return;

    // Put into start state.
    el.classList.add('ix-pending');

    // Wait one rAF so the browser commits ix-pending before we start observing.
    // Without this, a fast IntersectionObserver callback could fire before the
    // first paint of the start state, skipping the transition entirely.
    let observer;
    const raf = requestAnimationFrame(() => {
      observer = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) {
            el.classList.remove('ix-pending');
            el.classList.add('ix-revealed');
            observer.unobserve(el);
          }
        },
        { rootMargin: '0px 0px -8% 0px', threshold: 0 }
      );
      observer.observe(el);
    });

    return () => {
      cancelAnimationFrame(raf);
      if (observer) observer.disconnect();
      el.classList.remove('ix-pending');
    };
  }, []);

  return ref;
};

const Reveal = ({ children }) => {
  const ref = useReveal();
  return <div ref={ref} className="ix-reveal">{children}</div>;
};

window.useReveal = useReveal;
window.Reveal   = Reveal;
