import { useEffect, type RefObject } from "react";

/**
 * Applies GSAP entrance animations and scroll-triggered effects to any hero section.
 *
 * Inside the referenced element, it automatically finds and animates:
 *  - `h1`              → clip-path wipe + fade in
 *  - `p` elements      → fade up (staggered)
 *  - `a, button` in a row → fade up (staggered)
 *  - `img, video`      → subtle scale parallax on scroll
 *
 * The entire hero fades out as the user scrolls past it.
 */
export function useHeroAnimation(ref: RefObject<HTMLElement | HTMLDivElement | null>) {
  useEffect(() => {
    const section = ref.current;
    if (!section) return;

    const prefersReduced = window.matchMedia(
      "(prefers-reduced-motion: reduce)"
    ).matches;
    if (prefersReduced) return;

    let ctx: ReturnType<typeof import("gsap").gsap.context> | undefined;
    let cancelled = false;

    (async () => {
      const { gsap } = await import("gsap");
      const { ScrollTrigger } = await import("gsap/ScrollTrigger");
      gsap.registerPlugin(ScrollTrigger);

      if (cancelled || !ref.current) return;

      ctx = gsap.context(() => {
        const h1 = section.querySelector("h1");
        const paragraphs = section.querySelectorAll<HTMLElement>(
          ".relative p, .relative > div > p, .relative > div > div > p"
        );
        const buttons = section.querySelectorAll<HTMLElement>(
          ".relative a[href], .relative button:not([disabled])"
        );
        const bgMedia = section.querySelector<HTMLElement>("img.absolute, video.absolute, img[class*='object-cover'], video[class*='object-cover']");

        const tl = gsap.timeline({
          defaults: { ease: "power3.out" },
          delay: 0.3,
        });

        if (h1) {
          tl.fromTo(
            h1,
            { clipPath: "inset(0 100% 0 0)", y: 14, opacity: 0 },
            {
              clipPath: "inset(0 0% 0 0)",
              y: 0,
              opacity: 1,
              duration: 0.85,
              ease: "power4.out",
            }
          );
        }

        if (paragraphs.length) {
          tl.fromTo(
            Array.from(paragraphs),
            { opacity: 0, y: 16 },
            { opacity: 1, y: 0, duration: 0.5, stagger: 0.08 },
            "-=0.3"
          );
        }

        if (buttons.length) {
          tl.fromTo(
            Array.from(buttons),
            { y: 20, opacity: 0 },
            { y: 0, opacity: 1, stagger: 0.08, duration: 0.5 },
            "-=0.3"
          );
        }

        if (bgMedia) {
          gsap.to(bgMedia, {
            scale: 1.05,
            ease: "none",
            scrollTrigger: {
              trigger: section,
              start: "top top",
              end: "bottom top",
              scrub: 1.5,
            },
          });
        }

        gsap.to(section, {
          opacity: 0,
          ease: "none",
          scrollTrigger: {
            trigger: section,
            start: "65% top",
            end: "bottom top",
            scrub: 0.8,
          },
        });
      }, section);
    })();

    return () => {
      cancelled = true;
      ctx?.revert();
    };
  }, [ref]);
}
