"use client";

import { useEffect, useRef } from "react";

/**
 * Scroll-reveal wrapper. Adds the `in` flag (via `data-in`) when the element
 * enters the viewport, or immediately under prefers-reduced-motion. The visual
 * transition lives in blog.module.css (`.reveal` / `.reveal[data-in="true"]`).
 */
export function Reveal({
  className,
  delay,
  as: Tag = "div",
  children,
}: {
  className?: string;
  /** transition-delay in seconds (design's data-d stagger). */
  delay?: number;
  as?: "div" | "section" | "article";
  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 -6% 0px" },
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

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