"use client";

import { useLayoutEffect, useRef, type ReactNode } from "react";

import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";

gsap.registerPlugin(ScrollTrigger);

type ParallaxProps = {
  children: ReactNode;
  className?: string;
  /** Fraction of the viewport the element travels. */
  amount?: number;
};

/** Subtle vertical parallax for hero media. Transform-only; no-op under reduced motion. */
export default function Parallax({
  children,
  className,
  amount = 0.08,
}: ParallaxProps) {
  const wrapRef = useRef<HTMLDivElement | null>(null);
  const innerRef = useRef<HTMLDivElement | null>(null);

  useLayoutEffect(() => {
    const wrap = wrapRef.current;
    const inner = innerRef.current;
    if (!wrap || !inner) return;

    const mq = gsap.matchMedia();
    mq.add("(prefers-reduced-motion: no-preference)", () => {
      const tween = gsap.fromTo(
        inner,
        { yPercent: -amount * 100 },
        {
          yPercent: amount * 100,
          ease: "none",
          scrollTrigger: {
            trigger: wrap,
            start: "top bottom",
            end: "bottom top",
            scrub: 1,
          },
        }
      );
      return () => {
        tween.scrollTrigger?.kill();
        tween.kill();
      };
    });

    return () => mq.revert();
  }, [amount]);

  return (
    <div ref={wrapRef} className={`overflow-hidden ${className ?? ""}`}>
      <div ref={innerRef} className="h-full scale-[1.12]">
        {children}
      </div>
    </div>
  );
}
