"use client";

import { default as Image } from "next-image-export-optimizer";
import chicagoPic from "@/public/content/chicago.jpg";
import indianapolisPic from "@/public/content/indianapolis.png";
import naturePic from "@/public/content/nature.jpg";
import { useEffect, useState } from "react";
import { useTransition, animated } from "@react-spring/web";

interface Props {
  className?: string;
}

const Carousel = ({ className }: Props) => {
  const [backgroundIndex, setBackgroundIndex] = useState(0);
  const backgroundImages = [
    { image: chicagoPic, desc: "Chicago Skyline" },
    { image: indianapolisPic, desc: "Indianapolis Skyline" },
    { image: naturePic, desc: "Two women hiking in the mountains" },
  ];

  useEffect(() => {
    const interval = setInterval(() => {
      setBackgroundIndex(
        (prevIndex) => (prevIndex + 1) % backgroundImages.length,
      );
    }, 9000);

    return () => clearInterval(interval);
  }, []);

  const transitions = useTransition(backgroundIndex, {
    key: backgroundIndex,
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
    config: { duration: 2500 },
    exitBeforeEnter: true,
  });

  return transitions((style, item) => (
    <animated.div style={style} className={className}>
      <Image
        src={backgroundImages[item].image}
        alt={backgroundImages[item].desc}
        className="h-full w-full object-cover"
      />
    </animated.div>
  ));
};

export default Carousel;
