"use client";

import Image from "next/image";
import React, { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";

type InfiniteMovingImagesProps = {
  images: {
    src: string;
    alt?: string;
  }[];
  direction?: "left" | "right";
  speed?: "fast" | "normal" | "slow";
  pauseOnHover?: boolean;
  className?: string;
};

const InfiniteMovingImages = ({
  images,
  direction = "left",
  speed = "fast",
  pauseOnHover = true,
  className,
}: InfiniteMovingImagesProps) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const scrollerRef = useRef<HTMLDivElement>(null);
  const [start, setStart] = useState(false);

  useEffect(() => {
    if (!containerRef.current || !scrollerRef.current) return;

    const items = Array.from(scrollerRef.current.children);
    items.forEach((item) => {
      scrollerRef.current!.appendChild(item.cloneNode(true));
    });

    containerRef.current.style.setProperty(
      "--animation-direction",
      direction === "left" ? "forwards" : "reverse"
    );

    containerRef.current.style.setProperty(
      "--animation-duration",
      speed === "fast" ? "20s" : speed === "normal" ? "40s" : "80s"
    );

    setStart(true);
  }, [direction, speed]);

  return (
    <div
      ref={containerRef}
      className={cn("overflow-hidden py-16 -my-26", className)}
      onMouseEnter={() => {
    scrollerRef.current!.style.animationPlayState = "paused";
  }}
  onMouseLeave={() => {
    scrollerRef.current!.style.animationPlayState = "running";
  }}
    >
      <div
        ref={scrollerRef}
        className={cn(
          "flex w-max items-center gap-10",
          start && "animate-scroll",
          pauseOnHover && "hover:[animation-play-state:paused]"
        )}
      >
        {images.map((img, i) => (
            <div
            key={i}
            className="flex h-40 w-40 shrink-0 items-center justify-center rounded-full bg-[rgba(255, 255, 255, 0.10)] 
            shadow-[15px_15px_50px_0_rgba(135,126,164,0.5)]">
            <Image
              src={img.src}
              alt={img.alt ?? ""}
              width={80}
              height={96}
            />
          </div>
        ))}
      </div>
    </div>
  );
};

export default InfiniteMovingImages;
