"use client";

import { useEffect, useRef } from "react";
import { gsap, ScrollTrigger, prefersReducedMotion } from "@/lib/gsap";

type Props = {
  src: string;
  alt: string;
  className?: string;
  imgClassName?: string;
  /** total px of vertical drift across the scroll pass */
  drift?: number;
};

/** Image that drifts/scales subtly while its container scrolls through the viewport. */
export default function ParallaxImg({
  src,
  alt,
  className = "",
  imgClassName = "",
  drift = 60,
}: Props) {
  const wrapRef = useRef<HTMLDivElement>(null);
  const imgRef = useRef<HTMLImageElement>(null);

  useEffect(() => {
    if (prefersReducedMotion()) return;
    const wrap = wrapRef.current;
    const img = imgRef.current;
    if (!wrap || !img) return;

    const ctx = gsap.context(() => {
      gsap.fromTo(
        img,
        { y: -drift / 2, scale: 1.12 },
        {
          y: drift / 2,
          scale: 1.12,
          ease: "none",
          scrollTrigger: {
            trigger: wrap,
            start: "top bottom",
            end: "bottom top",
            scrub: true,
          },
        }
      );
    }, wrap);

    return () => ctx.revert();
  }, [drift]);

  return (
    <div ref={wrapRef} className={`overflow-hidden ${className}`}>
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        ref={imgRef}
        src={src}
        alt={alt}
        loading="lazy"
        decoding="async"
        className={`h-full w-full object-cover will-change-transform ${imgClassName}`}
      />
    </div>
  );
}