import React, { useRef, useEffect, useState } from "react";
import classNames from "classnames";
import Carousel from "../../containers/carousel";
import styles from "./hero.module.scss";

const Hero = ({ slider }: any) => {
  const carouselRef = useRef(null);
  const [currentSlide, setCurrentSlide] = useState(0);

  useEffect(() => {
    const carousel: any = carouselRef.current;

    const handleVideoEnded = () => {
      if (carousel) {
        // Check if there's a next slide
        if (carousel.isEnd) {
          // If it's the last slide, go back to the first slide
          carousel.slideTo(0);
        } else {
          carousel.slideNext();
        }
      }
    };

    // Add event listeners to all video elements in the carousel
    const videoElements = document.querySelectorAll(".hero__video");
    videoElements.forEach((video) => {
      video.addEventListener("ended", handleVideoEnded);
    });

    // Add an event listener for the slide change transition end
    if (carousel) {
      carousel.on("slideChangeTransitionEnd", () => {
        const activeIndex = carousel.activeIndex;
        setCurrentSlide(activeIndex);
        const videoElements = document.querySelectorAll(".hero__video");
        videoElements.forEach((video: any, index) => {
          if (index === activeIndex) {
            video.play();
          } else {
            video.pause();
            video.currentTime = 0; // Reset video to the beginning
          }
        });
      });

      carousel.on("slideChangeTransitionStart", () => {
        const previousIndex = carousel.previousIndex;
        const videoElements = document.querySelectorAll(".hero__video");
        videoElements.forEach((video: any, index) => {
          if (index === previousIndex) {
            video.pause();
          }
        });
      });
    }

    return () => {
      // Remove event listeners when the component unmounts
      videoElements.forEach((video) => {
        video.removeEventListener("ended", handleVideoEnded);
      });
    };
  }, [currentSlide]);

  return (
    <div className={classNames("relative h-full", styles.hero)}>
      <div className="hero__carousel">
        <Carousel
          ref={carouselRef}
          items={slider}
          slidesPerView={1}
          lazy
          pagination={{ clickable: true }}
          spaceBetween={2}
        >
          {({ title, video, description }: any, index: number) => (
            <div>
              <video
                controls={false}
                width="100vw"
                height="100%"
                className={classNames(
                  "absolute top-0 right-0 left-0 bottom-0 -z-[1] object-cover w-[100vw] h-full",
                  "hero__video"
                )}
                autoPlay={index === 0}
                muted
              >
                <source src={video} type="video/mp4" />
                Your browser does not support the video tag.
              </video>

              <div className="lg:w-1/2 h-full flex flex-col justify-end">
                <div className="container">
                  <div className="text-white mb-[25%]">
                    <div
                      className="mb-4 text-4xl text-bold"
                      dangerouslySetInnerHTML={{ __html: title }}
                    ></div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </Carousel>
      </div>
    </div>
  );
};

export default Hero;
