"use client";

import { useEffect, useRef, type ReactNode } from "react";

/** Pauses SMIL animations inside its SVGs while they are off-screen, so ambient motion never runs unseen. */
export function SvgAnimationGate({ children, className }: { children: ReactNode; className?: string }) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const element = ref.current;
    if (!element || !("IntersectionObserver" in window)) return;
    const svgs = Array.from(element.querySelectorAll("svg"));
    const observer = new IntersectionObserver(([entry]) => {
      for (const svg of svgs) {
        if (entry.isIntersecting) svg.unpauseAnimations();
        else svg.pauseAnimations();
      }
    });
    observer.observe(element);
    return () => observer.disconnect();
  }, []);

  return (
    <div ref={ref} className={className}>
      {children}
    </div>
  );
}
