"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import Image from "next/image";
import Link from "next/link";
import { ChevronLeft, ChevronRight, ArrowRight } from "lucide-react";
import { gsap, prefersReducedMotion } from "@/lib/gsap";
import { cn } from "@/lib/utils";
import { markHeroReady } from "@/components/HomePreloader";

const products = [
    
    {
        id: "iroof-max-brick",
        name: "iRoof Max",
        colorName: "Brick Red",
        subtitle: "BOLD CONTEMPORARY STYLE",
        description: "A vibrant roofing solution that enhances modern architecture. Engineered with UV-stable polymers to maintain its striking color, strength, and reliable performance in tropical climates.",
        bgImage: "/images/1930-x-730-web-banners-1-red-brick.webp",
        productImage: "/images/roof-hero22.webp",
        href: "/products/iroof-max-brick"
    },
    {
        id: "iroof-max-green",
        name: "iRoof Max",
        colorName: "Dark Green",
        subtitle: "NATURAL COOLING PERFORMANCE",
        description: "Inspired by nature, this roofing sheet features advanced ASA protection and UV-resistant polymers to reduce heat absorption while ensuring lasting color and outstanding durability.",
        bgImage: "/images/1930-x-730-web-banners-2-dark-green.webp",
        productImage: "/images/roof-hero33.webp",
        href: "/products/iroof-max-green"
    },
    {
        id: "iroof-max-ocean-blue",
        name: "iRoof Max",
        colorName: "Ocean Blue",
        subtitle: "VIBRANT COASTAL ELEGANCE",
        description: "A rich ocean blue finish designed for modern homes. Advanced UV-resistant polymers preserve its vibrant color while providing exceptional durability, weather protection, and long-lasting performance.",
        bgImage: "/images/5.webp",
        productImage: "/images/roof-hero11.webp",
        href: "/products/iroof-max-ocean-blue"
    },
    {
        id: "iroof-max-white",
        name: "iRoof Max",
        colorName: "White",
        subtitle: "BRIGHT MODERN SIMPLICITY",
        description: "A clean, elegant roofing solution with excellent solar reflectivity. Its advanced polymer construction minimizes heat buildup while delivering superior strength, weather resistance, and lasting beauty.",
        bgImage: "/images/1930-x-730-web-banners-4-white.webp",
        productImage: "/images/roof-hero44.webp",
        href: "/products/iroof-max-white"
    }
];

export default function Hero() {
    const [currentIndex, setCurrentIndex] = useState(0);
    // Pause auto-advance while the visitor is hovering or keyboard-focused inside the hero.
    const [isPaused, setIsPaused] = useState(false);
    const contentRef = useRef<HTMLElement>(null);

    const nextSlide = useCallback(() => {
        setCurrentIndex((prevIndex) => (prevIndex + 1) % products.length);
    }, []);

    const prevSlide = useCallback(() => {
        setCurrentIndex((prevIndex) => (prevIndex === 0 ? products.length - 1 : prevIndex - 1));
    }, []);

    // Auto-advance every 6 seconds, resets when user changes index manually
    useEffect(() => {
        if (isPaused || prefersReducedMotion()) return;
        const timer = setInterval(nextSlide, 6000);
        return () => clearInterval(timer);
    }, [currentIndex, nextSlide, isPaused]);

    // GSAP text animation on slide change
    useEffect(() => {
        const ctx = gsap.context(() => {
            gsap.fromTo(".hero-text-animate",
                { y: 15, opacity: 0 },
                { y: 0, opacity: 1, duration: 1, stagger: 0.1, ease: "power2.out" }
            );
        });
        return () => ctx.revert();
    }, [currentIndex]);

    return (
        <section
            ref={contentRef}
            aria-roledescription="carousel"
            aria-label="Featured iRoof products"
            onMouseEnter={() => setIsPaused(true)}
            onMouseLeave={() => setIsPaused(false)}
            onFocus={() => setIsPaused(true)}
            onBlur={(e) => {
                if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setIsPaused(false);
            }}
            className="relative h-auto xl:h-[100svh] min-h-0 xl:min-h-[600px] w-full overflow-hidden flex flex-col xl:flex-row bg-white pt-[64px]">
            <style dangerouslySetInnerHTML={{ __html: `
                @keyframes float-premium {
                    0%, 100% { transform: translateY(0px) rotate(0deg); }
                    50% { transform: translateY(-12px) rotate(1deg); }
                }
                .animate-float-premium {
                    animation: float-premium 6s ease-in-out infinite;
                }
                @keyframes progress-fill {
                    0% { width: 0%; }
                    100% { width: 100%; }
                }
            `}} />

            {/* LEFT COLUMN: Clean Text & Details (White background) */}
            <div className="w-full xl:w-[30%] min-[1600px]:w-[10%] bg-white flex flex-col justify-start xl:justify-center px-6 sm:px-12 xl:px-12 min-[1600px]:px-4 order-2 xl:order-1 pt-4 pb-8 sm:pb-12 xl:py-12 relative z-20">
                <div className="max-w-md w-full mx-auto flex flex-col items-center text-center">

                    {/* Subtitle / Category badge */}
                    <div className="flex items-center gap-3 text-brand-accent/90 text-[10px] xl:text-xs font-semibold tracking-[0.3em] uppercase mb-4 hero-text-animate">
                        <span className="w-6 h-[2px] bg-brand-accent rounded-full"></span>
                        {products[currentIndex].subtitle}
                    </div>

                    {/* Title with color highlight */}
                    <h1 className="hero-text-animate font-heading text-2xl sm:text-4xl xl:text-5xl font-black text-brand-dark uppercase tracking-tight leading-[1.1] mb-6">
                        {products[currentIndex].name} <br />
                        <span className="text-brand-accent font-black">
                            {products[currentIndex].colorName}
                        </span>
                    </h1>

                    {/* Description Paragraph */}
                    <p className="hero-text-animate text-[12px] sm:text-[14px] xl:text-[15px] text-zinc-500 font-sans leading-relaxed mb-6 sm:mb-8 max-w-sm mx-auto">
                        {products[currentIndex].description}
                    </p>

                    {/* CTA Button */}
                    <div className="hero-text-animate w-full flex justify-center">
                        <Link
                            href={products[currentIndex].href}
                            className="w-auto px-8 py-3 sm:py-4  inline-flex items-center justify-center bg-brand-accent hover:bg-brand-dark text-white rounded-md text-[10px] md:text-[11px] font-semibold uppercase tracking-[0.2em] transition-all duration-300 hover:scale-105 active:scale-95 shadow-[0_10px_20px_-5px_rgba(177,32,40,0.4)] group"
                        >
                            View Product
                            <ArrowRight className="w-4 h-4 ml-2 transition-transform duration-300 group-hover:translate-x-1" />
                        </Link>
                    </div>

                    {/* Mobile Arrow Buttons (below CTA button) */}
                    <div className="flex justify-center gap-4 mt-4 xl:hidden hero-text-animate">
                        <button
                            onClick={prevSlide}
                            className="w-10 h-10 rounded-full border border-zinc-200 flex items-center justify-center text-zinc-400 hover:text-brand-dark hover:border-brand-dark hover:bg-zinc-50 transition-all duration-300 cursor-pointer"
                            aria-label="Previous slide"
                        >
                            <ChevronLeft className="w-5 h-5" />
                        </button>
                        <button
                            onClick={nextSlide}
                            className="w-10 h-10 rounded-full border border-zinc-200 flex items-center justify-center text-zinc-400 hover:text-brand-dark hover:border-brand-dark hover:bg-zinc-50 transition-all duration-300 cursor-pointer"
                            aria-label="Next slide"
                        >
                            <ChevronRight className="w-5 h-5" />
                        </button>
                    </div>

                    {/* Controls & Page indicator */}
                    <div className="hero-text-animate mt-6 sm:mt-12 hidden xl:flex flex-row min-[1600px]:flex-col items-center gap-6 min-[1600px]:gap-4 border-t border-zinc-100 pt-6 sm:pt-8 w-full justify-center">
                        {/* Page count */}
                        <div className="flex items-center gap-1.5 select-none font-heading">
                            <span className="text-xl font-bold text-brand-dark">0{currentIndex + 1}</span>
                            <span className="text-xs text-zinc-300">/</span>
                            <span className="text-xs text-zinc-400 font-medium">0{products.length}</span>
                        </div>
                        {/* Navigation buttons */}
                        <div className="flex gap-2">
                            <button
                                onClick={prevSlide}
                                className="w-10 h-10 rounded-full border border-zinc-200 flex items-center justify-center text-zinc-400 hover:text-brand-dark hover:border-brand-dark hover:bg-zinc-50 transition-all duration-300 cursor-pointer"
                                aria-label="Previous slide"
                            >
                                <ChevronLeft className="w-5 h-5" />
                            </button>
                            <button
                                onClick={nextSlide}
                                className="w-10 h-10 rounded-full border border-zinc-200 flex items-center justify-center text-zinc-400 hover:text-brand-dark hover:border-brand-dark hover:bg-zinc-50 transition-all duration-300 cursor-pointer"
                                aria-label="Next slide"
                            >
                                <ChevronRight className="w-5 h-5" />
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            {/* RIGHT COLUMN: House Background & Floating stand-alone Product Sheet */}
            <div className="w-full xl:w-[70%] min-[1600px]:w-[90%] h-[35vh] min-h-[250px] sm:min-h-[320px] xl:min-h-0 xl:h-full relative order-1 xl:order-2 bg-zinc-950 overflow-hidden">
                
                {/* Background application images (fades on active slide) */}
                {products.map((p, index) => (
                    <div
                        key={p.id}
                        className={cn(
                            "absolute inset-0 transition-opacity duration-1000 ease-in-out",
                            index === currentIndex ? "opacity-100 scale-100" : "opacity-0 scale-105"
                        )}
                    >
                        <Image
                            src={p.bgImage}
                            alt={`iRoof application background ${p.colorName}`}
                            fill
                            sizes="100vw"
                            priority={index === 0}
                            className="object-cover object-top"
                            // Lets the home preloader finish as soon as the first slide is ready.
                            onLoad={index === 0 ? markHeroReady : undefined}
                        />
                        {/* Dark/Gradient overlays to isolate the foreground 3D product sheet */}
                        <div className="absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-black/10 xl:from-black/60 xl:via-transparent xl:to-black/20" />
                    </div>
                ))}

                {/* Foreground: 3D Floating Product Sheet (Aligned top-left) */}
                {/* {products.map((p, index) => (
                    <div
                        key={`sheet-${p.id}`}
                        className={cn(
                            "absolute inset-0 flex items-start justify-start top-[-30%] sm:p-10 lg:p-8 pt-20 sm:pt-24 lg:pt-40 2xl:pt-64 transition-all duration-1000 ease-in-out z-10",
                            index === currentIndex ? "opacity-100 scale-100 translate-y-0" : "opacity-0 scale-95 translate-y-8 pointer-events-none"
                        )}
                    >
                        <Link
                            href={p.href}
                            className="relative w-[75%] h-[75%] max-w-[380px] max-h-[380px] lg:max-w-[420px] lg:max-h-[420px] animate-float-premium drop-shadow-[0_25px_30px_rgba(0,0,0,0.65)] hover:scale-105 transition-transform duration-500 block cursor-pointer"
                        >
                            <Image
                                src={p.productImage}
                                alt={`${p.name} ${p.colorName} product sheet`}
                                fill
                                className="object-contain"
                                priority={true}
                            />
                        </Link>
                    </div>
                ))} */}

                {/* Floating Badges Container (Lowered to avoid overlapping navbar) */}
                <div className="absolute top-8 right-6 xl:top-12 xl:right-10 z-20 flex flex-col items-center gap-4">
                    {/* Warranty Badge */}
                    <div className="relative w-28 h-28 sm:w-32 sm:h-32 xl:w-44 xl:h-44 hover:scale-105 transition-transform duration-500 drop-shadow-2xl opacity-90 hover:opacity-100">
                        <Image src="/images/warranty-badge5.webp" alt="10 Year Warranty" fill sizes="176px" className="object-contain" priority />
                    </div>
                </div>
            </div>

            {/* Bottom progress bar for slide timer */}
            <div className="absolute bottom-0 left-0 w-full hidden md:block h-[3px] bg-zinc-100 z-30 motion-reduce:hidden">
                <div
                    key={`${currentIndex}-${isPaused}`}
                    className="h-full bg-brand-accent"
                    style={{
                        animation: isPaused ? "none" : "progress-fill 6000ms linear forwards"
                    }}
                />
            </div>
        </section>
    );
}
