"use client";

import { useEffect, useRef } from "react";

/**
 * Scroll-reveal wrapper. Sets `data-in="true"` on the element when it enters
 * the viewport (or immediately when the user prefers reduced motion). The
 * visual transition lives in the CSS module — pass its `.reveal` class via
 * `className`. Reused for the bento container, where `data-in` gates the
 * inner animations instead of fading the wrapper.
 */
export function Reveal({
  className,
  delay,
  children,
}: {
  className?: string;
  /** transition-delay in seconds (design's data-d stagger). */
  delay?: number;
  children: React.ReactNode;
}) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;

    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      el.setAttribute("data-in", "true");
      return;
    }

    const io = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            el.setAttribute("data-in", "true");
            io.unobserve(el);
          }
        }
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" },
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  return (
    <div
      ref={ref}
      className={className}
      style={delay ? { transitionDelay: `${delay}s` } : undefined}
    >
      {children}
    </div>
  );
}
