'use client';
import React, { useEffect, useRef, useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay, EffectFade } from 'swiper/modules';
import type { Swiper as SwiperCore } from 'swiper';

import 'swiper/css';
import 'swiper/css/effect-fade';

interface SlideData {
    id: number;
    videoUrl: string;
    title: string;
    subtitle: string;
    description: string;
    ctaText: string;
    ctaLink: string;
}

const slides: SlideData[] = [
    {
        id: 1,
        videoUrl: '/videos/218309.mp4',
        title: 'THE TREE STETHOSCOPE',
        subtitle: 'PULSE OF NATURE',
        description: 'Transforming agriculture with smart innovation. We optimize resources to build a future that is as intelligent as it is sustainable.',
        ctaText: 'See what we do',
        ctaLink: '#see-what-we-do',
    },
    {
        id: 2,
        videoUrl: '/videos/257791.mp4',
        title: 'MERA-THE AI ASSISTANT',
        subtitle: 'MEET MERA',
        description: 'Smart, intuitive,and always there.MERA is the personal assistant designed to make your life easier, one task at a time.',
        ctaText: 'Know More',
        ctaLink: '#Know-more',
    },
    {
        id: 3,
        videoUrl: '/videos/180523-864532673.mp4',
        title: 'THE SUDARShAN PH01K2JW',
        subtitle: 'ATMOSPHERE TO ORBIT',
        description: 'The worlds first AI hybrid craft. Engineered for speed and autonomy to redefine defense and space.',
        ctaText: 'Learn More',
        ctaLink: '#Learn-More',
    },
];

interface CircularProgressProps {
    durationMs: number;
    isPlaying: boolean;
    videoRef?: React.RefObject<HTMLVideoElement | null>;
    onComplete?: () => void;
    strokeColor?: string;
    size?: number;
}

const CircularProgressTimer: React.FC<CircularProgressProps> = ({
    durationMs,
    isPlaying,
    videoRef,
    onComplete,
    strokeColor = '#FFFFFF',
    size = 64,
}) => {
    const radius = 14.3;
    const circumference = 2 * Math.PI * radius;
    const rafRef = useRef<number | null>(null);
    const startRef = useRef<number>(0);
    const [progress, setProgress] = useState(0);

    useEffect(() => {
        const animate = (time: number) => {
            if (!isPlaying) return;

            let pct = 0;

            if (videoRef && videoRef.current) {
                const v = videoRef.current;
                const dur = v.duration;
                const ct = v.currentTime || 0;
                if (!isNaN(dur) && dur > 0) {
                    pct = Math.min(1, ct / dur);
                } else {
                    const elapsed = time - startRef.current;
                    pct = Math.min(1, elapsed / durationMs);
                }
            } else {
                const elapsed = time - startRef.current;
                pct = Math.min(1, elapsed / durationMs);
            }

            setProgress(pct);

            if (pct >= 1) {
                if (typeof onComplete === 'function') onComplete();
                return;
            }

            rafRef.current = requestAnimationFrame(animate);
        };

        startRef.current = performance.now();

        if (isPlaying) {
            if (rafRef.current) cancelAnimationFrame(rafRef.current);
            rafRef.current = requestAnimationFrame(animate);
        }

        return () => {
            if (rafRef.current) {
                cancelAnimationFrame(rafRef.current);
                rafRef.current = null;
            }
        };
    }, [isPlaying, durationMs, videoRef, onComplete]);

    const strokeDashoffset = circumference * (1 - progress);

    return (
        <svg
            width={size}
            height={size}
            viewBox="0 0 32 32"
            className="transform -rotate-90"
            style={{ pointerEvents: 'none' }}
        >
            <circle
                cx="16"
                cy="16"
                r={radius}
                stroke="rgba(255,255,255,0.06)"
                strokeWidth="3"
                fill="transparent"
            />
            <circle
                cx="16"
                cy="16"
                r={radius}
                stroke={strokeColor}
                strokeWidth="3"
                strokeLinecap="round"
                strokeDasharray={circumference}
                strokeDashoffset={strokeDashoffset}
                fill="transparent"
            />
        </svg>
    );
};

const AUTOPLAY_DELAY = 6000;

const VideoSlider: React.FC = () => {
    const [swiperInstance, setSwiperInstance] = useState<SwiperCore | null>(null);
    const [isPaused, setIsPaused] = useState(false);
    const [activeIndex, setActiveIndex] = useState(0);

    // <-- CORRECT initialization: pass the array value directly (not a function)
    const videoRefs = useRef<React.RefObject<HTMLVideoElement | null>[]>(
        slides.map(() => React.createRef<HTMLVideoElement>())
    );

    // Ensure only the active slide's video plays
    useEffect(() => {
        videoRefs.current.forEach((r, idx) => {
            const v = r?.current;
            if (!v) return;
            if (idx === activeIndex) {
                if (!isPaused) {
                    const p = v.play();
                    if (p && typeof p.then === 'function') p.catch(() => { });
                }
            } else {
                v.pause();
            }
        });
    }, [activeIndex, isPaused]);

    const handlePlayPause = () => {
        if (swiperInstance) {
            if (isPaused) {
                swiperInstance.autoplay.start();
            } else {
                swiperInstance.autoplay.stop();
            }
        }
        setIsPaused((p) => !p);
    };

    useEffect(() => {
        const currentRef = videoRefs.current[activeIndex];
        const v = currentRef?.current;
        if (!v) return;
        if (isPaused) {
            v.pause();
        } else {
            const p = v.play();
            if (p && typeof p.then === 'function') p.catch(() => { });
        }
    }, [isPaused, activeIndex]);

    const handleSlideChange = (swiper: SwiperCore) => {
        setActiveIndex(swiper.realIndex ?? swiper.activeIndex ?? 0);
    };

    const handleOnSwiper = (swiper: SwiperCore) => {
        setSwiperInstance(swiper);
    };

    return (
        <div className="w-full h-screen relative bg-indigo-200 overflow-hidden">
            <Swiper
                modules={[Autoplay, EffectFade]}
                effect="fade"
                spaceBetween={0}
                slidesPerView={1}
                autoplay={{
                    delay: AUTOPLAY_DELAY,
                    disableOnInteraction: false,
                    pauseOnMouseEnter: true,
                }}
                loop={true}
                onSwiper={handleOnSwiper}
                onSlideChange={handleSlideChange}
                className="w-full h-full"
            >
                {slides.map((slide, idx) => (
                    <SwiperSlide key={slide.id}>
                        <div className="relative w-full h-full">
                            <video
                                ref={videoRefs.current[idx]}
                                className="absolute inset-0 w-full h-full object-cover"
                                src={slide.videoUrl}
                                autoPlay
                                loop
                                muted
                                playsInline
                                preload="auto"
                            />

                            <div className="absolute inset-0 bg-black/50"></div>
                            <div className="relative z-10 w-full h-full flex items-center justify-start text-white px-10 md:px-21">
                                <div className="max-w-7xl flex flex-col md:flex-row justify-between w-full">
                                    <div className="md:w-1/2">
                                        <h1 className="text-5xl  sm:text-8xl font-extrabold  tracking-tighter filter drop-shadow-lg">
                                            {slide.title}
                                        </h1>
                                    </div>

                                    <div className="md:w-1/3 pt-8 md:pt-0 md:flex md:flex-col md:items-start md:text-left">
                                        <div className="mb-6">
                                            <div className="w-12 h-1 bg-[#4a00e0] mb-2 md:ml-left"></div>
                                            <h2 className="text-xl font-semibold uppercase text-white">
                                                {slide.subtitle}
                                            </h2>
                                        </div>

                                        <p className="text-base sm:text-lg mb-8 opacity-90 max-w-sm md:max-w-full">
                                            {slide.description}
                                        </p>

                                        <a
                                            href={slide.ctaLink}
                                            className="inline-flex items-center text-lg font-semibold text-[#4a00e0] pb-1 transition duration-300 hover:text-white"
                                        >
                                            {slide.ctaText}
                                            <svg
                                                className="w-6 h-6 ml-2 bg-[#4a00e0] rounded p-1"
                                                fill="none"
                                                stroke="#ffffff"
                                                viewBox="0 0 24 24"
                                                xmlns="http://www.w3.org/2000/svg"
                                            >
                                                <path
                                                    strokeLinecap="round"
                                                    strokeLinejoin="round"
                                                    strokeWidth="4"
                                                    d="M9 5l7 7-7 7"
                                                ></path>
                                            </svg>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </SwiperSlide>
                ))}
            </Swiper>

            <div
                className="absolute bottom-10 left-10 z-10"
                onClick={handlePlayPause}
            >
                <button
                    className="relative w-16 h-16 flex items-center justify-center rounded-full bg-transparent p-1 transition-all duration-300 hover:scale-95"
                    aria-label={isPaused ? 'Play slider' : 'Pause slider'}
                    type="button"
                >
                    <CircularProgressTimer
                        durationMs={AUTOPLAY_DELAY}
                        isPlaying={!isPaused}
                        videoRef={videoRefs.current[activeIndex]}
                        onComplete={() => {
                            if (swiperInstance && !isPaused) {
                                swiperInstance.slideNext();
                            }
                        }}
                        strokeColor="#FFFFFF"
                        size={64}
                    />

                    <div className="absolute inset-3 rounded-full flex items-center justify-center bg-transparent ring-1 ring-white/10">
                        {isPaused ? (
                            <svg
                                className="w-5 h-5 ml-1 text-white"
                                fill="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path d="M6 19L18 12L6 5V19Z" />
                            </svg>
                        ) : (
                            <svg
                                className="w-5 h-5 text-white"
                                fill="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
                            </svg>
                        )}
                    </div>
                </button>
            </div>
        </div>
    );
};

export default VideoSlider;
