import styles from "./Carousel.module.css"
import BannerImg from '../image/BannerImg'
import Card from '../Card/Card'
import { useEffect, useRef, useState } from "react"
import { data } from "../../utils/Data"
const Carasole = () => {
    const [currentIndex, setcurrentIndex] = useState<number>(0);
    const carouselref = useRef<HTMLDivElement | null>(null)
    const removeAnimation = () => {
        carouselref?.current?.classList.remove(styles.animations)
    }
    useEffect(() => {
        carouselref?.current?.classList.add(styles.animations)
        const timeout = setTimeout(removeAnimation, 150)
        return () => { clearTimeout(timeout) }
    }, [currentIndex])

    const handleNext = () => {
        setcurrentIndex((prevIndex) =>
            prevIndex === data.length - 1 ? 0 : prevIndex + 1
        )
    }



    useEffect(() => {
        const autoPlayInterval = setInterval(handleNext, 5000);
        return () => {
            clearInterval(autoPlayInterval);
        };
    }, [currentIndex]);

    const customChange = (index: number) => {
        setcurrentIndex(index);
    }
    // console.log(length)
    return (
        <div className={styles.carasole} ref={carouselref} key={currentIndex}>
            <BannerImg src={data[currentIndex]?.src} alt={data[currentIndex]?.title} />
            <Card {...data[currentIndex]} current={currentIndex} length={data.length} onClick={customChange} />
        </div>
    )
}

export default Carasole