import React, { useState, useEffect } from 'react';
import Slider from 'react-slick';
import { motion, AnimatePresence, useAnimation } from 'framer-motion';
import 'animate.css';

// Mock Data for the Hero Slider
const mockSliders = [
    {
        title: "Future of Sustainable Energy",
        subtitle: "Pioneering the next generation of clean, reliable, and affordable power solutions for a better planet.",
        link: "#services",
        image_url: "https://placehold.co/1920x1080/0d9488/ffffff?text=Renewable+Energy"
    },
    {
        title: "Data-Driven Intelligence",
        subtitle: "Unlocking powerful insights with advanced AI and machine learning to optimize efficiency and forecast market trends.",
        link: "#analytics",
        image_url: "https://placehold.co/1920x1080/064e3b/ffffff?text=AI+Analytics"
    },
    {
        title: "Global Infrastructure Modernization",
        subtitle: "Building robust, scalable, and resilient digital and physical foundations that connect communities worldwide.",
        link: "#projects",
        image_url: "https://placehold.co/1920x1080/10b981/ffffff?text=Global+Tech"
    },
];

// --- Sub-Components & Variants ---

// Custom Next Arrow with colored border and responsive design
const NextArrow = (props) => {
    const { onClick, currentSlide, slideCount } = props;
    return (
        <motion.button
            className="absolute top-1/2 right-2 sm:right-4 md:right-8 z-20 transform -translate-y-1/2 text-white rounded-full p-3 sm:p-4 md:p-6 transition-all duration-500 focus:outline-none group animate__animated animate__fadeInRight border-2 border-emerald-400"
            onClick={onClick}
            aria-label="Next slide"
            whileHover={{ scale: 1.1, x: 5 }}
            whileTap={{ scale: 0.95 }}
            initial={{ opacity: 0, x: 50 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.8, delay: 0.5 }}
        >
            <svg className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 lg:w-9 lg:h-9 group-hover:translate-x-1 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M9 5l7 7-7 7" />
            </svg>
            {/* Subtle glow effect */}
            <div className="absolute inset-0 rounded-full bg-gradient-to-r from-emerald-400/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
            {/* Ripple effect */}
            <div className="absolute inset-0 rounded-full border-2 border-white/20 animate-ping opacity-0 group-hover:opacity-20"></div>
        </motion.button>
    );
};

// Custom Previous Arrow with colored border and responsive design
const PrevArrow = (props) => {
    const { onClick } = props;
    return (
        <motion.button
            className="absolute top-1/2 left-2 sm:left-4 md:left-8 z-20 transform -translate-y-1/2 text-white rounded-full p-3 sm:p-4 md:p-6 transition-all duration-500 focus:outline-none group animate__animated animate__fadeInLeft border-2 border-emerald-400"
            onClick={onClick}
            aria-label="Previous slide"
            whileHover={{ scale: 1.1, x: -5 }}
            whileTap={{ scale: 0.95 }}
            initial={{ opacity: 0, x: -50 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.8, delay: 0.5 }}
        >
            <svg className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 lg:w-9 lg:h-9 group-hover:-translate-x-1 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M15 19l-7-7 7-7" />
            </svg>
            {/* Subtle glow effect */}
            <div className="absolute inset-0 rounded-full bg-gradient-to-l from-emerald-400/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
            {/* Ripple effect */}
            <div className="absolute inset-0 rounded-full border-2 border-white/20 animate-ping opacity-0 group-hover:opacity-20"></div>
        </motion.button>
    );
};

// Animation variants for content entry
const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
        opacity: 1,
        transition: {
            staggerChildren: 0.2,
            delayChildren: 0.3
        }
    }
};

const itemVariants = {
    hidden: { y: 40, opacity: 0, skewY: 2, scale: 0.95 },
    visible: {
        y: 0,
        opacity: 1,
        skewY: 0,
        scale: 1,
        transition: { 
            duration: 0.8, 
            ease: [0.25, 1, 0.5, 1] // Cinematic smooth transition
        }
    }
};

const buttonVariants = {
    hidden: { scale: 0.8, opacity: 0, y: 20 },
    visible: {
        scale: 1,
        opacity: 1,
        y: 0,
        transition: { 
            duration: 0.6, 
            ease: "easeOut",
            delay: 0.7
        }
    },
    hover: {
        scale: 1.05,
        boxShadow: "0 10px 15px -3px rgba(16, 185, 129, 0.5), 0 4px 6px -2px rgba(16, 185, 129, 0.2)",
        transition: { duration: 0.3, ease: "easeInOut" }
    },
    tap: {
        scale: 0.98
    }
};

// --- Main Hero Slider Component ---

const HeroSlider = ({ sliders = mockSliders }) => {
    const [currentSlide, setCurrentSlide] = useState(0);
    const [imageLoadError, setImageLoadError] = useState({});
    const [isLoaded, setIsLoaded] = useState(false);
    const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
    const [isHovered, setIsHovered] = useState(false);

    // Track mouse position for parallax effect
    useEffect(() => {
        const handleMouseMove = (e) => {
            setMousePosition({ x: e.clientX, y: e.clientY });
        };
        
        window.addEventListener('mousemove', handleMouseMove);
        
        // Set loaded state after a short delay
        const timer = setTimeout(() => setIsLoaded(true), 100);
        
        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
            clearTimeout(timer);
        };
    }, []);

    // Settings for the slick carousel
    const settings = {
        dots: true,
        infinite: true,
        speed: 1500, // Slower for a more dramatic transition
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 8000, // Longer dwell time
        fade: true,
        cssEase: 'cubic-bezier(0.7, 0, 0.3, 1)',
        pauseOnHover: true,
        arrows: true,
        nextArrow: <NextArrow />,
        prevArrow: <PrevArrow />,
        beforeChange: (oldIndex, newIndex) => setCurrentSlide(newIndex),
        // Custom paging for stylish dots
        customPaging: (i) => (
            <button
                className={`w-2 h-2 md:w-3 md:h-3 mx-0.5 md:mx-1 rounded-full transition-all duration-300 ${
                    i === currentSlide 
                        ? 'bg-emerald-400 w-6 md:w-8 shadow-md shadow-emerald-400/50 animate__animated animate__pulse animate__infinite' // Active dot uses accent color
                        : 'bg-white/40 hover:bg-emerald-400/70' // Inactive dots are subtle
                }`}
                aria-label={`Go to slide ${i + 1}`}
            />
        ),
        dotsClass: "slick-dots flex justify-center absolute bottom-6 sm:bottom-8 md:bottom-12 w-full z-20 space-x-1 md:space-x-2",
    };

    const getImageUrl = (slide) => {
        return slide.image_url;
    };

    // Calculate parallax offset based on mouse position
    const parallaxOffset = {
        x: (mousePosition.x - window.innerWidth / 2) / 50,
        y: (mousePosition.y - window.innerHeight / 2) / 50
    };

    return (
        <section 
            className="relative h-[60vh] sm:h-[70vh] md:h-screen overflow-hidden font-inter" 
            id="home"
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
        >
            {/* Top Accent Border with animated gradient */}
            <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-emerald-600 via-teal-500 to-green-600 z-30">
                <motion.div 
                    className="h-full bg-gradient-to-r from-transparent via-white/30 to-transparent"
                    animate={{ x: ["-100%", "100%"] }}
                    transition={{ duration: 3, repeat: Infinity, ease: "linear" }}
                />
            </div>
            
            {/* Animated background particles */}
            <div className="absolute inset-0 z-10 overflow-hidden pointer-events-none">
                {[...Array(30)].map((_, i) => (
                    <motion.div
                        key={i}
                        className="absolute w-1 h-1 bg-white/20 rounded-full"
                        style={{
                            left: `${Math.random() * 100}%`,
                            top: `${Math.random() * 100}%`,
                        }}
                        animate={{
                            y: [0, -30, 0],
                            opacity: [0, 1, 0],
                            scale: [1, 1.5, 1],
                        }}
                        transition={{
                            duration: 3 + Math.random() * 4,
                            repeat: Infinity,
                            delay: Math.random() * 5,
                            ease: "easeInOut"
                        }}
                    />
                ))}
            </div>
            
            {/* Floating shapes for visual interest */}
            <div className="absolute inset-0 z-5 overflow-hidden pointer-events-none">
                <motion.div
                    className="absolute top-1/4 left-1/4 w-64 h-64 bg-emerald-400/10 rounded-full blur-3xl"
                    animate={{
                        x: [0, 30, 0],
                        y: [0, -30, 0],
                        scale: [1, 1.1, 1],
                    }}
                    transition={{
                        duration: 10,
                        repeat: Infinity,
                        ease: "easeInOut"
                    }}
                />
                <motion.div
                    className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-teal-400/10 rounded-full blur-3xl"
                    animate={{
                        x: [0, -40, 0],
                        y: [0, 40, 0],
                        scale: [1, 1.2, 1],
                    }}
                    transition={{
                        duration: 12,
                        repeat: Infinity,
                        ease: "easeInOut"
                    }}
                />
            </div>
            
            <Slider {...settings}>
                {sliders.map((slide, index) => (
                    <div key={index} className="relative h-[60vh] sm:h-[70vh] md:h-screen">
                        
                        {/* Background Image Container with Continuous Zoom Effect */}
                        <motion.div
                            className={`absolute inset-0 bg-cover bg-center bg-no-repeat transition-all duration-1000 ${
                                index === currentSlide ? 'scale-105' : 'scale-100'
                            }`}
                            style={{ 
                                backgroundImage: !imageLoadError[index] ? 
                                    `url(${getImageUrl(slide)})` : 
                                    'linear-gradient(to top right, #1f2937, #0d1e33)', // Darker, more sophisticated fallback
                                backgroundColor: '#1f2937',
                                transform: `scale(${index === currentSlide ? 1.05 : 1.0}) translateX(${index === currentSlide ? parallaxOffset.x : 0}px) translateY(${index === currentSlide ? parallaxOffset.y : 0}px)`
                            }}
                            animate={{
                                scale: index === currentSlide ? 1.05 : 1.0,
                                x: index === currentSlide ? parallaxOffset.x : 0,
                                y: index === currentSlide ? parallaxOffset.y : 0,
                            }}
                            transition={{
                                duration: 12, // Slowed down zoom
                                ease: "easeInOut",
                                repeat: Infinity,
                                repeatType: "reverse"
                            }}
                            onError={() => {
                                setImageLoadError(prev => ({...prev, [index]: true}));
                                console.error(`Failed to load image for slide ${index}`);
                            }}
                        />

                        {/* Dark, Themed Overlay (for maximum contrast and cinematic feel) */}
                        <div className="absolute inset-0 bg-black/50" />
                        <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/30 to-black/90" />

                        {/* Animated gradient overlay */}
                        <motion.div 
                            className="absolute inset-0 opacity-30"
                            style={{
                                background: `radial-gradient(circle at ${mousePosition.x}px ${mousePosition.y}px, rgba(16, 185, 129, 0.2) 0%, transparent 50%)`
                            }}
                        />

                        {/* Content using AnimatePresence to force re-render/re-animation when slide changes */}
                        <div className="relative h-full flex items-center justify-center">
                            <AnimatePresence mode="wait">
                                {index === currentSlide && (
                                    <motion.div
                                        key={index} // Key change forces re-render and re-triggers animation
                                        className="container mx-auto px-4 sm:px-6 md:px-12 text-center z-10 max-w-5xl"
                                        variants={containerVariants}
                                        initial="hidden"
                                        animate="visible"
                                        exit="hidden" // Define exit state for smooth fade-out
                                    >
                                        {/* Title with enhanced styling */}
                                        <motion.h1
                                            variants={itemVariants}
                                            className="text-2xl sm:text-3xl md:text-5xl lg:text-6xl xl:text-7xl font-extrabold leading-tight mb-2 sm:mb-4 md:mb-6 tracking-tight animate__animated animate__fadeInUp"
                                            style={{ textShadow: '0 4px 10px rgba(0,0,0,0.5)' }}
                                        >
                                            <span className="relative">
                                                <span className="bg-clip-text text-transparent bg-gradient-to-r from-white via-white/90 to-emerald-300">
                                                    {slide.title}
                                                </span>
                                                {/* Animated underline */}
                                                <motion.div 
                                                    className="absolute -bottom-2 left-0 h-1 bg-gradient-to-r from-emerald-400 to-transparent"
                                                    initial={{ width: 0 }}
                                                    animate={{ width: "100%" }}
                                                    transition={{ duration: 1, delay: 1 }}
                                                />
                                            </span>
                                        </motion.h1>

                                        {/* Subtitle with enhanced styling */}
                                        <motion.p
                                            variants={itemVariants}
                                            className="text-sm sm:text-base md:text-lg lg:text-xl xl:text-2xl mb-4 sm:mb-6 md:mb-8 lg:mb-12 text-white/80 font-light max-w-4xl mx-auto leading-relaxed animate__animated animate__fadeIn animate__delay-1s"
                                        >
                                            {slide.subtitle}
                                        </motion.p>

                                        {/* Call to Action Button with enhanced styling */}
                                        {slide.link && (
                                            <motion.div
                                                variants={buttonVariants}
                                                whileHover="hover"
                                                whileTap="tap"
                                                className="animate__animated animate__fadeInUp animate__delay-2s"
                                            >
                                                <a
                                                    href={slide.link}
                                                    className="relative inline-block px-4 sm:px-6 md:px-8 lg:px-10 xl:px-12 py-2 sm:py-3 md:py-4 rounded-full text-sm sm:text-base md:text-lg lg:text-xl font-semibold bg-gradient-to-r from-emerald-600 to-green-500 text-white hover:from-emerald-700 hover:to-green-600 transition-all duration-300 transform shadow-2xl shadow-emerald-700/50 overflow-hidden group"
                                                    aria-label="Find out more about our services"
                                                >
                                                    {/* Button Shine Effect */}
                                                    <span className="absolute inset-0 rounded-full bg-gradient-to-r from-transparent via-white/30 to-transparent transform -skew-x-12 -translate-x-full group-hover:translate-x-full transition-transform duration-700"></span>
                                                    {/* Button inner glow */}
                                                    <span className="absolute inset-0 rounded-full bg-gradient-to-r from-transparent via-white/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></span>
                                                    {/* Button ripple effect */}
                                                    <span className="absolute inset-0 rounded-full border-2 border-white/20 animate-ping opacity-0 group-hover:opacity-30"></span>
                                                    <span className="relative z-10">Discover More</span>
                                                </a>
                                            </motion.div>
                                        )}
                                    </motion.div>
                                )}
                            </AnimatePresence>
                        </div>

                        {/* Slide counter with enhanced styling */}
                        <div className="absolute top-2 sm:top-4 right-2 sm:right-4 md:top-8 md:right-8 z-20 animate__animated animate__fadeIn">
                            <div className="px-2 sm:px-3 md:px-4 py-1 sm:py-2 bg-black/40 backdrop-blur-sm rounded-lg text-emerald-300 font-mono text-xs sm:text-sm md:text-sm shadow-inner shadow-emerald-700/20 border border-emerald-400/20">
                                <span className="text-white/60">Slide</span> {index + 1} / {sliders.length}
                            </div>
                        </div>

                        {/* Progress bar */}
                        <div className="absolute bottom-0 left-0 right-0 h-1 bg-black/30 z-20">
                            <motion.div 
                                className="h-full bg-gradient-to-r from-emerald-400 to-green-500"
                                initial={{ width: "0%" }}
                                animate={{ width: "100%" }}
                                transition={{ duration: 8, repeat: Infinity, ease: "linear" }}
                            />
                        </div>
                    </div>
                ))}
            </Slider>

            {/* Enhanced Scroll Indicator with Dots Pattern */}
            <motion.div 
                className="absolute bottom-4 sm:bottom-6 md:bottom-8 left-1/2 transform -translate-x-1/2 z-20"
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 1.2 }}
            >
                <motion.a 
                    href="#next-section" // Link to the next content section
                    className="flex flex-col items-center text-white/70 hover:text-emerald-400 transition-colors duration-300 group animate__animated animate__fadeIn animate__delay-3s animate__infinite"
                    whileHover={{ y: 5 }}
                    aria-label="Scroll down to next section"
                >
                    {/* Animated dots pattern */}
                    <div className="flex space-x-1 mb-2">
                        {[0, 1, 2].map((dot) => (
                            <motion.div
                                key={dot}
                                className="w-2 h-2 bg-emerald-400 rounded-full"
                                animate={{
                                    y: [0, -8, 0],
                                    opacity: [0.7, 1, 0.7],
                                }}
                                transition={{
                                    duration: 1.5,
                                    repeat: Infinity,
                                    delay: dot * 0.2,
                                    ease: "easeInOut"
                                }}
                            />
                        ))}
                    </div>
                    
                    {/* Scroll arrow */}
                    <div className="relative">
                        <motion.div 
                            className="w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 rounded-full border border-emerald-400/30 flex items-center justify-center backdrop-blur-sm bg-white/5"
                            whileHover={{ scale: 1.1 }}
                            transition={{ duration: 0.3 }}
                        >
                            <motion.svg 
                                className="w-4 h-4 sm:w-5 sm:h-5 md:w-6 md:h-6 text-emerald-400"
                                fill="none" 
                                stroke="currentColor" 
                                viewBox="0 0 24 24" 
                                xmlns="http://www.w3.org/2000/svg"
                                animate={{ y: [0, 4, 0] }}
                                transition={{ 
                                    duration: 2, 
                                    repeat: Infinity,
                                    ease: "easeInOut"
                                }}
                            >
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 14l-7 7m0 0l-7-7m7 7V3" />
                            </motion.svg>
                            {/* Animated rings */}
                            <motion.div 
                                className="absolute inset-0 rounded-full border border-emerald-400/20"
                                animate={{ scale: [1, 1.3, 1.5], opacity: [1, 0.5, 0] }}
                                transition={{ duration: 2, repeat: Infinity }}
                            />
                            <motion.div 
                                className="absolute inset-0 rounded-full border border-emerald-400/10"
                                animate={{ scale: [1, 1.3, 1.5], opacity: [1, 0.5, 0] }}
                                transition={{ duration: 2, repeat: Infinity, delay: 0.5 }}
                            />
                                {/* Glow effect */}
                                <div className="absolute inset-0 rounded-full bg-emerald-400/10 blur-md group-hover:bg-emerald-400/20 transition-colors duration-300"></div>
                        </motion.div>
                    </div>
                </motion.a>
            </motion.div>

            {/* Loading overlay */}
            {!isLoaded && (
                <motion.div 
                    className="absolute inset-0 bg-black/90 z-50 flex items-center justify-center"
                    initial={{ opacity: 1 }}
                    animate={{ opacity: 0 }}
                    transition={{ duration: 0.5, delay: 0.5 }}
                    onAnimationComplete={() => setIsLoaded(true)}
                >
                    <div className="relative">
                        <div className="w-16 h-16 border-4 border-emerald-400/30 border-t-emerald-400 rounded-full animate-spin"></div>
                        <div className="absolute inset-0 flex items-center justify-center">
                            <div className="w-8 h-8 bg-emerald-400 rounded-full animate-pulse"></div>
                        </div>
                    </div>
                </motion.div>
            )}
        </section>
    );
};

export default HeroSlider;