"use client";

import gsap from "gsap";
import { type RefObject, useLayoutEffect } from "react";

type TableAnimRefs = {
  tableSectionRef: RefObject<HTMLDivElement | null>;
  skeletonTbodyRef: RefObject<HTMLTableSectionElement | null>;
  dataTbodyRef: RefObject<HTMLTableSectionElement | null>;
};

/**
 * Stagger row entrance for table skeleton vs data body (matches admins/tenders pattern).
 */
export function useTableSectionRowAnimations(
  isPending: boolean,
  /** Changes when loaded list/payload updates — retriggers data row animation */
  dataEpoch: unknown,
  refs: TableAnimRefs,
) {
  const { tableSectionRef, skeletonTbodyRef, dataTbodyRef } = refs;

  useLayoutEffect(() => {
    const reduced =
      typeof window !== "undefined" &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    const ctx = gsap.context(() => {
      if (reduced) return;

      if (isPending) {
        const tbody = skeletonTbodyRef.current;
        if (!tbody) return;
        const rows = tbody.querySelectorAll("tr");
        gsap.fromTo(
          rows,
          { opacity: 0.35, y: 14 },
          {
            opacity: 1,
            y: 0,
            duration: 0.42,
            stagger: 0.032,
            ease: "power2.out",
          },
        );
        return;
      }

      const tbody = dataTbodyRef.current;
      if (!tbody) return;
      const rows = tbody.querySelectorAll("tr");
      if (!rows.length) return;
      gsap.fromTo(
        rows,
        { opacity: 0, y: 18 },
        {
          opacity: 1,
          y: 0,
          duration: 0.46,
          stagger: 0.05,
          ease: "power3.out",
          clearProps: "opacity,transform",
        },
      );
    }, tableSectionRef);

    return () => ctx.revert();
  }, [isPending, dataEpoch]);
}
