"use client";

import { useRef, useState, useEffect } from "react";
import { Play, Pause, Volume2, VolumeX,  Maximize, Minimize } from "lucide-react";
import { withCDN } from "@/src/lib/utils";

export type VideoItem = {
  id: number;
  video: string;
  thumbnail: string;
  title: string;
};

const videos: VideoItem[] = [
  {
    id: 1,
    video: "https://yemedia.b-cdn.net/v3.mp4",
    thumbnail: withCDN("/discover/discover-1.png"),
    title: "AlgoC Program",
  },
  {
    id: 2,
    video: "https://www.pexels.com/download/video/5071853/",
    thumbnail: withCDN("/discover/discover-6.png"),
    title: "Program name",
  },
  {
    id: 3,
    video: "https://www.pexels.com/download/video/4911544/",
    thumbnail: withCDN("/discover/discover-5.png"),
    title: "Program name",
  },
  {
    id: 4,
    video: "https://yemedia.b-cdn.net/v3.mp4",
    thumbnail: withCDN("/discover/discover-1.png"),
    title: "AlgoC Program",
  },
  {
    id: 5,
    video: "https://www.pexels.com/download/video/5071853/",
    thumbnail: withCDN("/discover/discover-6.png"),
    title: "Program name",
  },
  {
    id: 6,
    video: "https://www.pexels.com/download/video/4911544/",
    thumbnail: withCDN("/discover/discover-5.png"),
    title: "Program name",
  },
   {
    id: 7,
    video: "https://yemedia.b-cdn.net/v3.mp4",
    thumbnail: withCDN("/discover/discover-1.png"),
    title: "AlgoC Program",
  },
];

export default function VideoSlider({ dynamicVideos }: { dynamicVideos?: VideoItem[] }) {
  const currentVideos = dynamicVideos && dynamicVideos.length > 0 ? dynamicVideos : videos;
  const videoRef = useRef<HTMLVideoElement>(null);

  const [active, setActive] = useState(0);
  const [muted, setMuted] = useState(true);
  // Mirrors `muted` so the autoplay effect (which runs on every video switch)
  // can read the CURRENT choice without restarting the video on each toggle.
  const mutedRef = useRef(true);
  const [isPlaying, setIsPlaying] = useState(true);
  const [hasAudio, setHasAudio] = useState(true);

  const [isFullscreen, setIsFullscreen] = useState(false);
  const videoWrapperRef = useRef<HTMLDivElement>(null);


  // ✅ AUTOPLAY ON LOAD & TAB CHANGE
  useEffect(() => {
    if (!videoRef.current) return;

    const video = videoRef.current;
    // Keep the user's sound choice when switching videos (don't force-mute).
    video.muted = mutedRef.current;
    video.currentTime = 0;

    const playPromise = video.play();
    if (playPromise !== undefined) {
      playPromise.catch(() => {
      });
    }

    setIsPlaying(true);
  }, [active, currentVideos]);

  // ✅ DYNAMIC AUDIO TRACK DETECTION TO SHOW/HIDE MUTE BUTTON
  useEffect(() => {
    if (!videoRef.current) return;

    const video = videoRef.current;
    setHasAudio(true); // Reset to true initially when the video src changes

    const checkAudio = () => {
      const hasAudioTrack =
        (typeof (video as any).webkitAudioDecodedByteCount !== "undefined" && (video as any).webkitAudioDecodedByteCount > 0) ||
        (typeof (video as any).mozHasAudio !== "undefined" && (video as any).mozHasAudio) ||
        Boolean((video as any).audioTracks && (video as any).audioTracks.length > 0);

      if (hasAudioTrack) {
        setHasAudio(true);
      }
    };

    video.addEventListener("loadeddata", checkAudio);
    video.addEventListener("playing", checkAudio);
    video.addEventListener("timeupdate", checkAudio);

    // After a short delay during playback, run a final fallback check to verify audio bytes decoded
    const checkTimeout = setTimeout(() => {
      const hasAudioTrack =
        (typeof (video as any).webkitAudioDecodedByteCount !== "undefined" && (video as any).webkitAudioDecodedByteCount > 0) ||
        (typeof (video as any).mozHasAudio !== "undefined" && (video as any).mozHasAudio) ||
        Boolean((video as any).audioTracks && (video as any).audioTracks.length > 0);
      
      setHasAudio(hasAudioTrack);
    }, 1000);

    return () => {
      video.removeEventListener("loadeddata", checkAudio);
      video.removeEventListener("playing", checkAudio);
      video.removeEventListener("timeupdate", checkAudio);
      clearTimeout(checkTimeout);
    };
  }, [active, currentVideos]);

  const handlePlayPause = () => {
    if (!videoRef.current) return;

    if (videoRef.current.paused) {
      videoRef.current.play();
      setIsPlaying(true);
    } else {
      videoRef.current.pause();
      setIsPlaying(false);
    }
  };

  const handleMute = () => {
    if (!videoRef.current) return;
    const next = !muted;
    videoRef.current.muted = next;
    setMuted(next);
    // Persist the choice so it stays applied across video switches.
    mutedRef.current = next;
  };

const handleFullscreen = async () => {
  if (!videoWrapperRef.current) return;

  if (!document.fullscreenElement) {
    await videoWrapperRef.current.requestFullscreen();
    setIsFullscreen(true);
  } else {
    await document.exitFullscreen();
    setIsFullscreen(false);
  }
};
useEffect(() => {
  const fullscreenChange = () => {
    setIsFullscreen(!!document.fullscreenElement);
  };

  document.addEventListener(
    "fullscreenchange",
    fullscreenChange
  );

  return () => {
    document.removeEventListener(
      "fullscreenchange",
      fullscreenChange
    );
  };
}, []);

  return (
    <section className="relative w-full h-[750px] md:h-[445px] lg:h-[700px] overflow-hidden v1">
      <div className="relative flex flex-col-reverse md:flex-row gap-0 md:gap-4 w-full h-full videos-container">

        {/* MAIN VIDEO */}
        <div
          ref={videoWrapperRef}
          className={`relative flex-1 overflow-hidden bg-black h-[550px] md:h-[450px] lg:h-[700px]
          before:content-['']
          before:absolute
          before:top-0
          before:left-0
          before:w-full
          before:h-full
          before:bg-[#0000002a]
          max-[768px]:before:bg-[#3030304d]
          ${isFullscreen ? "video-is-fullscreen" : ""}
         `}
        >
          <video
            ref={videoRef}
            src={currentVideos[active]?.video}
            className="w-full object-cover max-[767px]:h-[550px] max-[1024px]:h-[680px]"
            muted
            autoPlay
            playsInline
            loop
          />

          {/* CONTROLS */}
          <div className="absolute top-4 right-3 md:top-auto md:bottom-20 md:right-[300px] flex items-center justify-center gap-0 vide0-fullscreen z-10 v-controls">
          <button
            onClick={handlePlayPause}
            aria-label={isPlaying ? "Pause" : "Play"}
            className="bg-transparent p-3 rounded-full text-white cursor-pointer"
          >
            {isPlaying ? <Pause size={30} /> : <Play size={30} />}
          </button>
          <button
            onClick={handleMute}
            aria-label={muted ? "Turn sound on" : "Turn sound off"}
            title={muted ? "Turn sound on" : "Turn sound off"}
            className="bg-transparent p-3 rounded-full text-white cursor-pointer"
          >
            {muted ? <VolumeX size={30} /> : <Volume2 size={30} />}
          </button>
          <button
            onClick={handleFullscreen}
            className="bg-transparent p-3 rounded-full text-white cursor-pointer"
          >
            {isFullscreen ? (
              <Minimize size={30} />
            ) : (
              <Maximize size={30} />
            )}
          </button>
         </div>

          <div className="absolute lg:left-32 lg:top-8 md:left-8 md:top-2 flex items-center justify-center gap-0 vide0-slider hidden">
            <button
              onClick={handlePlayPause}
              className="bg-transparent p-3 rounded-full"
            >
              {isPlaying ? <Pause size={30} /> : <Play size={30} />}
            </button>

            {hasAudio && (
              <button
                onClick={handleMute}
                className="bg-transparent p-3 rounded-full"
              >
                {muted ? <VolumeX size={30} /> : <Volume2 size={30} />}
              </button>
            )}
          </div>
        </div>

        {/* THUMBNAILS */}
        <div className="w-[150px] h-[750px] md:h-[450px] lg:h-[700px] mb-5 md:w-[150px] overflow-x-auto no-scrollbar bg-white h-full p-2.5 relative  md:absolute md:right-9 lg:right-17 xl:right-[calc(50%-638px)] video-thumbnail-wrapper">
          {currentVideos.map((item, index) => (
            <button
              key={item.id || index}
              onClick={() => setActive(index)}
              className={`rounded-xl border-2 cursor-pointer mb-3 relative video-slider z-4 ${
                active === index
                  ? "border-[#0097DC]"
                  : "border-transparent"
              }`}
            > 
            <div className="rounded-[12px] overflow-hidden">
              <img
                src={item.thumbnail}
                alt={item.title}
                className="w-[130px] h-[94px] object-cover "
              />
              </div>
              <img
                src={withCDN("/Layer_2.png")}
                alt="Play Button"
                className="w-[25px] h-[25px] object-contain play-btn opacity-0"
              />
              <p className="text-sm mt-1 text-center z-9 text-[10px] p-[10px] py-[6px] rounded-[50px] bg-[#0097DC] text-white absolute bottom-[-6px] right-[-11px] text-center mt-1 txt">
                  {item.title}
               </p>
            </button>
          ))}
          
        </div>
        
      </div>
    </section>
  );
}
