"use client";

import { useEffect, useRef } from "react";
import { gsap, prefersReducedMotion } from "./gsap-setup";

type RevealProps = {
  children: React.ReactNode;
  className?: string;
  /** Stagger applied to direct children instead of the wrapper itself. */
  stagger?: number;
  y?: number;
  delay?: number;
  start?: string;
};

/**
 * Generic scroll reveal for blocks (cards, rows, form fields).
 *
 * Pair with `data-reveal` on the animated elements: the CSS in globals.css
 * starts them at opacity 0, and this clears that as the trigger fires. When
 * motion is reduced the CSS opt-out already forces them visible, so this
 * simply does nothing.
 */
export default function Reveal({
  children,
  className,
  stagger,
  y = 28,
  delay = 0,
  start = "top 88%",
}: RevealProps) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (prefersReducedMotion()) {
      el.setAttribute("data-reveal-ready", "");
      return;
    }

    const ctx = gsap.context(() => {
      const targets = stagger != null ? el.querySelectorAll("[data-reveal]") : el;
      const list = stagger != null ? Array.from(targets as NodeListOf<Element>) : [el];
      if (!list.length) return;

      gsap.fromTo(
        list,
        { y, opacity: 0 },
        {
          y: 0,
          opacity: 1,
          duration: 0.9,
          ease: "power3.out",
          delay,
          stagger: stagger ?? 0,
          scrollTrigger: { trigger: el, start, once: true },
        }
      );
    }, ref);

    return () => ctx.revert();
  }, [stagger, y, delay, start]);

  // `data-reveal` on the wrapper keeps the whole block hidden pre-animation in
  // the un-staggered case; the staggered case hides its children instead.
  return (
    <div ref={ref} className={className} {...(stagger == null ? { "data-reveal": "" } : {})}>
      {children}
    </div>
  );
}
