// components/parallax/MultiImageParallax.tsx
"use client";

import React, { useRef } from "react";
import Image from "next/image";
import gsap from "gsap";
import { useIsomorphicLayoutEffect } from "@/hooks/use-isomorphic-layout-effect";
import { cn } from "@/lib/utils";

interface MultiImageItem {
  src: string;
  alt: string;
  speed: number;
  direction: "up" | "down";
  width?: number;
  height?: number;
  className?: string;
}

interface MultiImageParallaxProps {
  images: MultiImageItem[];
  className?: string;
  containerClassName?: string;
  stagger?: number;
}

export const MultiImageParallax: React.FC<MultiImageParallaxProps> = ({
  images,
  className = "",
  containerClassName = "",
  stagger = 0.1,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const imagesRef = useRef<(HTMLDivElement | null)[]>([]);

  useIsomorphicLayoutEffect(() => {
    if (!containerRef.current) return;

    const ctx = gsap.context(() => {
      images.forEach((image, index) => {
        const imageElement = imagesRef.current[index];
        if (!imageElement) return;

        const multiplier = image.direction === "up" ? -1 : 1;
        const yPercent = 30 * image.speed * multiplier;

        gsap.to(imageElement, {
          yPercent,
          ease: "none",
          scrollTrigger: {
            trigger: containerRef.current,
            start: "top bottom",
            end: "bottom top",
            scrub: true,
          },
          delay: index * stagger,
        });
      });
    });

    return () => ctx.revert();
  }, [images, stagger]);

  return (
    <div
      ref={containerRef}
      className={cn("multi-image-parallax", "relative", containerClassName)}
    >
      <div className={cn("relative w-full h-full", className)}>
        {images.map((image, index) => (
          <div
            key={index}
            ref={(el: HTMLDivElement | null) => {
              if (el) {
                imagesRef.current[index] = el;
              }
            }}
            className={cn(
              "absolute inset-0",
              "will-change-transform",
              image.className
            )}
            style={{ zIndex: index }}
          >
            <Image
              src={image.src}
              alt={image.alt}
              width={image.width}
              height={image.height}
              className="w-full h-full object-cover"
              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 80vw, 70vw"
            />
          </div>
        ))}
      </div>
    </div>
  );
};
