"use client";

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

type ScrollRevealProps = {
  children: ReactNode;
  /** Stagger delay in ms, typically index * 100 for a grid of items. */
  delay?: number;
  className?: string;
  /** "up" = fade + rise, "scale" = fade + rise + scale from 0.98. */
  variant?: "up" | "scale";
};

/** Reveals its children the first time they scroll into view. Reduced motion is handled globally in CSS. */
export default function ScrollReveal({ children, delay = 0, className = "", variant = "up" }: ScrollRevealProps) {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);

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

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setVisible(true);
          observer.disconnect();
        }
      },
      { threshold: 0.15 },
    );

    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  return (
    <div
      ref={ref}
      className={`${className} ${visible ? (variant === "scale" ? "animate-card-in" : "animate-fade-up") : "opacity-0"}`}
      style={{ animationDelay: `${delay}ms` }}
    >
      {children}
    </div>
  );
}
