"use client";

import Link from "next/link";
import { useState, useEffect, useRef, useCallback } from "react";
import Image from "next/image";
import { ArrowRight, Play, Pause, Volume2, VolumeX } from "lucide-react";
import { gsap, prefersReducedMotion } from "@/lib/gsap";
import { cn } from "@/lib/utils";
import WhyIRoof from "./WhyIRoof";
import LayerShowcase from "./LayerShowcase";
import HomeAdvantages from "./HomeAdvantages";
import DealerNetworkBanner from "./DealerNetworkBanner";

// Home page showcase video (YouTube).
const SHOWCASE_VIDEO_ID = "WOiQcHW1VpY";

// Minimal typing for the parts of the YouTube IFrame Player API used here.
interface YouTubePlayer {
    playVideo(): void;
    pauseVideo(): void;
    mute(): void;
    unMute(): void;
    destroy(): void;
}

interface YouTubeApi {
    Player: new (
        element: HTMLElement,
        options: {
            videoId: string;
            host?: string;
            playerVars?: Record<string, string | number>;
            events?: {
                onReady?: () => void;
                onStateChange?: (event: { data: number }) => void;
            };
        }
    ) => YouTubePlayer;
}

declare global {
    interface Window {
        YT?: YouTubeApi;
        onYouTubeIframeAPIReady?: () => void;
    }
}

const YT_STATE = { ENDED: 0, PLAYING: 1, PAUSED: 2, BUFFERING: 3 } as const;

let youTubeApiPromise: Promise<YouTubeApi> | null = null;

// Load the IFrame API script once, on demand.
const loadYouTubeApi = () => {
    if (window.YT?.Player) return Promise.resolve(window.YT);
    if (!youTubeApiPromise) {
        youTubeApiPromise = new Promise((resolve, reject) => {
            const previous = window.onYouTubeIframeAPIReady;
            window.onYouTubeIframeAPIReady = () => {
                previous?.();
                resolve(window.YT!);
            };
            const script = document.createElement("script");
            script.src = "https://www.youtube.com/iframe_api";
            script.async = true;
            script.onerror = () => {
                youTubeApiPromise = null;
                reject(new Error("Failed to load the YouTube player"));
            };
            document.head.appendChild(script);
        });
    }
    return youTubeApiPromise;
};

export default function ProductsAndGallery() {
    const edgeSectionRef = useRef<HTMLDivElement>(null);
    const edgeScrollRef = useRef<HTMLDivElement>(null);

    // Video Showcase & Custom Cursor states/refs
    const [isPlayingVideo, setIsPlayingVideo] = useState(false);
    const [isVideoBuffering, setIsVideoBuffering] = useState(false);
    const [isMuted, setIsMuted] = useState(true);
    const playerMountRef = useRef<HTMLDivElement>(null);
    const playerRef = useRef<YouTubePlayer | null>(null);
    const playerReadyRef = useRef(false);
    const wantsPlayRef = useRef(false);
    const isMutedRef = useRef(true);
    const cursorRef = useRef<HTMLDivElement>(null);
    const videoContainerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (typeof window !== "undefined") {
            const mm = gsap.matchMedia();

            mm.add("(max-width: 767px)", () => {
                const container = edgeScrollRef.current;
                const section = edgeSectionRef.current;
                if (!container || !section) return;

                gsap.to(container, {
                    x: () => -(container.scrollWidth - window.innerWidth + 32),
                    ease: "none",
                    scrollTrigger: {
                        trigger: section,
                        start: "center center",
                        pin: true,
                        scrub: 1,
                        end: () => "+=" + container.scrollWidth,
                        invalidateOnRefresh: true,
                    }
                });
            });

            return () => mm.revert();
        }
    }, []);

    // Create the YouTube player on first use. Muted, since browsers only allow muted autoplay.
    const ensurePlayer = useCallback(() => {
        const wrapper = playerMountRef.current;
        if (playerRef.current || !wrapper) return;

        setIsVideoBuffering(true);
        loadYouTubeApi()
            .then((YT) => {
                if (playerRef.current || !wrapper.isConnected) return;
                // YouTube swaps this element for its iframe, so give it one React doesn't manage.
                const mount = document.createElement("div");
                wrapper.appendChild(mount);
                playerRef.current = new YT.Player(mount, {
                    videoId: SHOWCASE_VIDEO_ID,
                    host: "https://www.youtube-nocookie.com",
                    playerVars: {
                        autoplay: 0,
                        mute: 1,
                        controls: 0,
                        disablekb: 1,
                        playsinline: 1,
                        rel: 0,
                        iv_load_policy: 3,
                        loop: 1,
                        playlist: SHOWCASE_VIDEO_ID,
                    },
                    events: {
                        onReady: () => {
                            playerReadyRef.current = true;
                            setIsVideoBuffering(false);
                            if (isMutedRef.current) playerRef.current?.mute();
                            else playerRef.current?.unMute();
                            if (wantsPlayRef.current) playerRef.current?.playVideo();
                        },
                        onStateChange: ({ data }) => {
                            if (data === YT_STATE.PLAYING) {
                                setIsPlayingVideo(true);
                                setIsVideoBuffering(false);
                            } else if (data === YT_STATE.BUFFERING) {
                                setIsVideoBuffering(true);
                            } else if (data === YT_STATE.PAUSED || data === YT_STATE.ENDED) {
                                setIsPlayingVideo(false);
                                setIsVideoBuffering(false);
                            }
                        },
                    },
                });
            })
            .catch((err) => {
                console.error(err);
                setIsVideoBuffering(false);
            });
    }, []);

    const playVideo = useCallback(() => {
        wantsPlayRef.current = true;
        if (playerReadyRef.current) playerRef.current?.playVideo();
        else ensurePlayer();
    }, [ensurePlayer]);

    const pauseVideo = useCallback(() => {
        wantsPlayRef.current = false;
        if (playerReadyRef.current) playerRef.current?.pauseVideo();
    }, []);

    // Autoplay when the showcase enters the viewport, pause when it leaves.
    useEffect(() => {
        const container = videoContainerRef.current;
        if (!container) return;
        // No autoplay for reduced-motion users; they can still press play.
        const autoplay = !prefersReducedMotion();

        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    if (autoplay) playVideo();
                } else {
                    pauseVideo();
                }
            },
            { threshold: 0.2 } // trigger when 20% visible
        );
        observer.observe(container);

        return () => {
            observer.disconnect();
            playerRef.current?.destroy();
            playerRef.current = null;
            playerReadyRef.current = false;
        };
    }, [playVideo, pauseVideo]);

    // Custom Glassmorphism Cursor Mouse Events
    const handleVideoMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
        if (!cursorRef.current || !videoContainerRef.current) return;

        const rect = videoContainerRef.current.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        gsap.to(cursorRef.current, {
            x: x,
            y: y,
            duration: 0.1,
            ease: "power2.out",
            overwrite: "auto",
        });
    };

    const handleVideoMouseEnter = (e: React.MouseEvent<HTMLDivElement>) => {
        if (!cursorRef.current || !videoContainerRef.current) return;

        const rect = videoContainerRef.current.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        gsap.set(cursorRef.current, { xPercent: -50, yPercent: -50, x, y });
        gsap.to(cursorRef.current, {
            scale: 1,
            opacity: 1,
            duration: 0.3,
            ease: "back.out(1.5)",
        });
    };

    const handleVideoMouseLeave = () => {
        if (!cursorRef.current) return;

        gsap.to(cursorRef.current, {
            scale: 0.5,
            opacity: 0,
            duration: 0.3,
            ease: "power2.in",
        });
    };

    const handleVideoClick = () => {
        if (isPlayingVideo) pauseVideo();
        else playVideo();
    };

    const toggleMute = () => {
        const muted = !isMuted;
        isMutedRef.current = muted;
        setIsMuted(muted);
        if (playerReadyRef.current) {
            if (muted) playerRef.current?.mute();
            else playerRef.current?.unMute();
        }
    };

    const products = [
        {
            model: "iRoof Max",
            type: "Brick Red Roofing Sheet",
            desc: "iRoof Max Brick Red blends classic roofing design with ASA-powered polymer technology for superior weather resistance.",
            image: "/images/brick-red.webp",
            hoverImage: "/images/line-art-i-roof-max-brick-red.webp"
        },
        {
            model: "iRoof Max",
            type: "Dark Green Roofing Sheet",
            desc: "iRoof Max Dark Green blends naturally with outdoor surroundings, making it a perfect choice for residential designs.",
            image: "/images/dark-green.webp",
            hoverImage: "/images/line-art-i-roof-max-dark-green.webp"
        },
        {
            model: "iRoof Max",
            type: "Ocean Blue Roofing Sheet",
            desc: "A premium ocean-tone roofing solution, iRoof Max Ocean Blue delivers vibrant cooling elegance and exceptional weather resistance.",
            image: "/images/ocean-blue.webp",
            hoverImage: "/images/line-art-i-roof-max-ocean-blue.webp"
        },
        {
            model: "iRoof Max",
            type: "White Roofing Sheet",
            desc: "A clean and modern roofing solution, iRoof Max White offers superior heat reflection and long-lasting durability.",
            image: "/images/White.jpg",
            hoverImage: "/images/line-art-i-roof-max-white.webp"
        },
    ];

    return (
        <div className="pt-8 lg:pt-28 pb-12 overflow-x-clip">
            <section id="manufacturing-excellence" className="reveal-up max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40 mb-12 flex flex-col md:flex-row md:items-end justify-between gap-8 text-center md:text-left">
                <div className="max-w-2xl mx-auto md:mx-0">
                    <div className="flex items-center justify-center md:justify-start gap-6 mb-4 group">
                        <div className="h-[1.5px] w-12 bg-brand-accent group-hover:w-20 transition-all duration-700" />
                        <span className="text-[11px] font-bold text-brand-accent uppercase tracking-[0.4em]">Our iRoof Collection</span>
                        <div className="h-[1.5px] w-12 bg-brand-accent group-hover:w-20 transition-all duration-700 md:hidden" />
                    </div>
                    <h2 className="text-3xl md:text-5xl font-bold text-brand-dark tracking-tight leading-none mb-0">
                        Manufacturing &nbsp;
                        <span className="text-brand-accent">Excellence</span>
                    </h2>
                    <div className="max-w-3xl mx-auto space-y-8">
                            

                            <p className="text-sm md:text-base text-zinc-500 leading-relaxed pt-4">
                            i-Roof is a <strong className="font-semibold text-brand-dark">Sri Lankan manufactured roofing solution</strong>. From residential masterpieces to large-scale industrial hubs, our 100% locally made range guarantees durability, heat reflection and timeless aesthetics.
                            </p>
                        </div>
                </div>
                {/* Warranty Badge Image */}
                <div className="mx-auto md:mx-0 relative w-32 h-32 md:w-40 md:h-40 xl:w-44 xl:h-44 group cursor-default">
                    <div className="absolute inset-0 transition-transform duration-700 group-hover:scale-105 pt-4">
                        <Image
                            src="/images/warranty-badge5.webp"
                            alt="10 Year Warranty Badge"
                            fill
                            sizes="176px"
                            className="object-contain"
                        />
                    </div>
                </div>
            </section>

            {/* PRODUCT GRID */}
            <section className="max-w-[1400px] mx-auto px-4 sm:px-8 md:px-16 lg:px-32 pb-12">
                <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4 items-stretch stagger-group">
                    {products.map((product, i) => (
                        <Link
                            key={i}
                            href="/products"
                            className="stagger-item flex flex-col h-full group bg-white border border-brand-dark/5 shadow-sm hover:shadow-2xl hover:border-brand-accent/20 transition-all duration-100 overflow-hidden cursor-pointer"
                            aria-label={`View ${product.model} ${product.type}`}
                        >

                            {/* Image Container with Hover Swap */}
                            <div className="relative w-full aspect-square overflow-hidden bg-brand-dark/[0.02]">
                                {/* Default Image */}
                                <Image
                                    src={product.image}
                                    alt={`${product.model} ${product.type}`}
                                    fill
                                    sizes="(min-width: 1280px) 25vw, (min-width: 768px) 50vw, 100vw"
                                    className="object-contain scale-[1.2] mix-blend-multiply transition-opacity duration-700 group-hover:opacity-0"
                                />
                                {/* Hover Image */}
                                <Image
                                    src={product.hoverImage}
                                    alt={`${product.model} hover`}
                                    fill
                                    sizes="(min-width: 1280px) 25vw, (min-width: 768px) 50vw, 100vw"
                                    className="object-contain p-3 mix-blend-multiply opacity-0 transition-all duration-700 group-hover:opacity-100 scale-105 group-hover:scale-100"
                                />
                            </div>

                            {/* Clean Text Content */}
                            <div className="flex flex-col flex-grow p-5 text-left">
                                <h4 className="text-[10px] sm:text-[11px] font-black uppercase tracking-[0.2em] text-brand-accent mb-2 transition-colors duration-300">
                                    {product.model}
                                </h4>
                                <h3 className="text-base lg:text-lg font-bold tracking-tight text-brand-dark group-hover:text-brand-accent transition-colors duration-500 line-clamp-2">
                                    {product.type}
                                </h3>

                                <p className="text-xs text-brand-dark/50 mt-2 mb-4 line-clamp-2 leading-relaxed font-medium">
                                    {product.desc}
                                </p>

                                {/* Minimal Button */}
                                <div className="mt-auto border-t border-brand-dark/5 pt-4 group-hover:border-brand-accent/20 transition-colors duration-500">
                                    <div className="inline-flex items-center w-full justify-between gap-2 text-brand-dark text-[11px] font-black uppercase tracking-[0.2em] group-hover:text-brand-accent transition-all duration-300">
                                        View Details
                                        <ArrowRight className="w-4 h-4 transition-transform duration-300 group-hover:translate-x-1" />
                                    </div>
                                </div>
                            </div>
                        </Link>
                    ))}
                </div>
            </section>

            {/* Advantages shared by all colours */}
            <HomeAdvantages />

            {/* FULL-WIDTH VIDEO SHOWCASE */}
            <section 
                ref={videoContainerRef}
                data-no-global-cursor="true"
                className="w-full aspect-video md:aspect-[21/9] relative overflow-hidden select-none cursor-none mt-8 mb-0"
                onMouseMove={handleVideoMouseMove}
                onMouseEnter={handleVideoMouseEnter}
                onMouseLeave={handleVideoMouseLeave}
                onClick={handleVideoClick}
            >
                {/* YouTube player: 16:9, centred and cropped to fill the wider 21:9 frame */}
                <div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden={!isPlayingVideo}>
                    <div
                        ref={playerMountRef}
                        className="absolute left-0 top-1/2 w-full aspect-video -translate-y-1/2 [&>iframe]:w-full [&>iframe]:h-full"
                    />
                </div>

                {/* Cover Image / Overlay */}
                <div 
                    className={cn(
                        "absolute inset-0 w-full h-full z-10 transition-all duration-700 ease-in-out bg-transparent",
                        isPlayingVideo ? "opacity-0 pointer-events-none" : "opacity-100"
                    )}
                >
                    {/* Cover Thumbnail Image */}
                    {/* eslint-disable-next-line @next/next/no-img-element -- YouTube thumbnail is a third-party image */}
                    <img 
                        src={`https://img.youtube.com/vi/${SHOWCASE_VIDEO_ID}/maxresdefault.jpg`}
                        alt="iRoof: No. 1 ASA Roofing Sheets in Sri Lanka" 
                        loading="lazy"
                        decoding="async"
                        className="w-full h-full object-cover scale-[1.12] max-md:scale-[1.35] transition-transform duration-[1500ms]"
                    />
                </div>

                {/* Centered Loading Spinner */}
                <div 
                    className={cn(
                        "absolute inset-0 flex items-center justify-center bg-black/10 backdrop-blur-[2px] transition-all duration-300 pointer-events-none z-15",
                        isVideoBuffering ? "opacity-100" : "opacity-0"
                    )}
                >
                    <div className="flex flex-col items-center justify-center p-6 rounded-2xl bg-white/10 backdrop-blur-md border border-white/20 shadow-2xl">
                        <div className="w-10 h-10 border-4 border-white/30 border-t-brand-accent rounded-full animate-spin" />
                        <span className="text-[10px] font-black uppercase tracking-[0.2em] text-white mt-3 select-none"></span>
                    </div>
                </div>

                {/* Mute/Unmute glassmorphic floating toggle button */}
                <button
                    onClick={(e) => {
                        e.stopPropagation();
                        toggleMute();
                    }}
                    className="absolute bottom-6 right-6 md:bottom-8 md:right-8 z-35 flex items-center justify-center w-12 h-12 md:w-14 md:h-14 rounded-full border border-white/20 bg-black/30 backdrop-blur-md text-white transition-all duration-300 hover:scale-110 active:scale-95 cursor-pointer shadow-[0_8px_32px_0_rgba(0,0,0,0.3)] hover:bg-black/50"
                    aria-label={isMuted ? "Unmute video" : "Mute video"}
                >
                    {isMuted ? (
                        <VolumeX className="w-5 h-5 md:w-6 md:h-6 text-white animate-pulse" />
                    ) : (
                        <Volume2 className="w-5 h-5 md:w-6 md:h-6 text-white" />
                    )}
                </button>

                {/* Transparent Interaction Overlay (always on top of video, captures moves/clicks) */}
                <div className="absolute inset-0 z-20 w-full h-full bg-transparent" />

                {/* Custom Glassmorphism Cursor (GSAP outer wrapper) */}
                <div 
                    ref={cursorRef}
                    className="absolute pointer-events-none z-30 w-32 h-32 opacity-0 scale-50"
                    style={{
                        left: 0,
                        top: 0,
                        willChange: 'transform',
                    }}
                >
                    {/* Inner active-scale wrapper */}
                    <div className="w-full h-full rounded-full border border-white/35 backdrop-blur-md bg-white/20 shadow-2xl flex flex-col items-center justify-center text-white transition-transform duration-150 active:scale-90">
                        {isVideoBuffering ? (
                            <>
                                <div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                                <span className="text-[10px] font-black uppercase tracking-[0.2em] mt-2 animate-pulse">Loading...</span>
                            </>
                        ) : isPlayingVideo ? (
                            <>
                                <Pause className="w-6 h-6 text-white animate-pulse" fill="white" />
                                <span className="text-[10px] font-black uppercase tracking-[0.2em] mt-2">Pause Video</span>
                            </>
                        ) : (
                            <>
                                <Play className="w-6 h-6 text-white" fill="white" />
                                <span className="text-[10px] font-black uppercase tracking-[0.2em] mt-2">Play Video</span>
                            </>
                        )}
                    </div>
                </div>
            </section>

            {/* The i-Roof Edge: scroll-driven 4-layer breakdown */}
            <LayerShowcase />

            <WhyIRoof />

            <DealerNetworkBanner />

        </div >
    );
}
