"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { ChevronRight, ArrowUpRight, ArrowRight, Maximize2, Thermometer, X, ExternalLink, ShieldCheck, Download, Flame, Droplets, Feather, Wrench, Layers, Shield, VolumeX, Sun, Ruler, Sparkles } from "lucide-react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import Navbar from "@/components/Navbar";
import Breadcrumbs from "@/components/Breadcrumbs";
import Footer from "@/components/Footer";
import { cn } from "@/lib/utils";
import WhyIRoof from "@/components/sections/WhyIRoof";

import { products, Product } from "@/lib/products";

const categories = ["All", "iRoof Max"];

const lineArtMap: Record<string, string> = {
    "iroof-max-brick": "/images/Line art  I - ROOF MAX _ Brick Red.jpg",
    "iroof-max-green": "/images/Line art  I - ROOF MAX _ Dark Green.jpg",
    "iroof-max-chocolate-brown": "/images/Line art  I - ROOF MAX _ Chocolate Brown.jpg",
    "iroof-max-white": "/images/Line art  I - ROOF MAX _ White.jpg",
};

export default function ProductsPage() {
    const mainRef = useRef<HTMLDivElement>(null);
    const [activeCategory, setActiveCategory] = useState("All");
    const [hoveredProduct, setHoveredProduct] = useState<string | null>(null);
    const [zoomedImage, setZoomedImage] = useState<string | null>(null);



    // 1. HERO ENTRANCE - Mount Only
    useEffect(() => {
        const ctx = gsap.context(() => {
            const heroTl = gsap.timeline();
            heroTl.from(".products-hero-badge", { y: 20, opacity: 0, delay: 0.5 })
                .from(".products-hero-title", { y: 40, opacity: 0, duration: 1.2, stagger: 0.2 }, "-=0.6")
                .from(".products-hero-desc", { y: 20, opacity: 0, duration: 1 }, "-=0.8");

            // Refresh markers after hero animation finishes
            setTimeout(() => ScrollTrigger.refresh(), 1000);
        }, mainRef);

        const handleLoad = () => ScrollTrigger.refresh();
        window.addEventListener("load", handleLoad);
        return () => {
            ctx.revert();
            window.removeEventListener("load", handleLoad);
        };
    }, []);

    // 2. PRODUCT GRID REVEAL - Reactive to Category
    useEffect(() => {
        // We use a tiny delay to ensure React has updated the DOM before GSAP scans it
        const timer = setTimeout(() => {
            const ctx = gsap.context(() => {
                const cards = gsap.utils.toArray(".product-card-definitive");
                if (cards.length === 0) return;

                gsap.fromTo(cards,
                    { y: 60, opacity: 0 },
                    {
                        y: 0,
                        opacity: 1,
                        duration: 1,
                        stagger: 0.05,
                        ease: "power2.out",
                        scrollTrigger: {
                            trigger: ".product-grid-definitive",
                            start: "top 95%",
                            toggleActions: "play none none none",
                            onRefresh: () => console.log("Grid Trigger Synced")
                        },
                        clearProps: "all" // CRITICAL: Reset styles after animation so they don't get stuck
                    }
                );

                ScrollTrigger.refresh();
            }, mainRef);
            return () => ctx.revert();
        }, 50);

        return () => clearTimeout(timer);
    }, [activeCategory]);



    const filteredProducts = activeCategory === "All"
        ? products
        : products.filter(p => p.category === activeCategory);

    return (
        <main ref={mainRef} className="min-h-screen bg-white selection:bg-brand-accent selection:text-white">
            <Navbar />

            {/* PRODUCTS HERO - Banner */}
            <section className="relative pt-24 pb-8 md:pt-40 md:pb-16 min-h-[20vh] w-full flex items-center justify-center overflow-hidden mb-24">
                <Image
                    src="/images/pexels9.webp"
                    alt="Products Background"
                    fill
                    className="object-cover"
                    priority
                />
                {/* Dark overlay for text readability */}
                <div className="absolute inset-0 bg-brand-dark/70" />

                <div className="relative z-10 text-center px-6 reveal-up">
                    <h1 className="products-hero-title text-4xl md:text-6xl lg:text-7xl font-medium text-white tracking-tight mt-6">
                        Our Products
                    </h1>
                </div>
            </section>

            {/* BREADCRUMBS ONLY */}
            <div className="max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40 pt-8 pb-4">
                <Breadcrumbs items={[{ label: "Products" }]} className="mb-0" />
            </div>

            {/* CATEGORY EXPLORER BAR */}
            <section className="bg-white border-b border-zinc-100 py-8">
                <div className="max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40 flex items-center justify-between">
                    <div className="flex items-center gap-4 overflow-x-auto pb-2 md:pb-0 scrollbar-hide">
                        {categories.map((cat) => (
                            <button
                                key={cat}
                                onClick={() => setActiveCategory(cat)}
                                className={cn(
                                    "px-10 py-3.5 rounded-full text-[10px] font-black uppercase tracking-[0.2em] transition-all duration-500 whitespace-nowrap",
                                    activeCategory === cat
                                        ? "bg-brand-dark text-white shadow-2xl shadow-black/20"
                                        : "bg-zinc-50 text-zinc-400 hover:bg-zinc-100 hover:text-brand-dark"
                                )}
                            >
                                {cat}
                            </button>
                        ))}
                    </div>
                </div>
            </section>

            {/* PRODUCT GRID - SIMPLIFIED HOVER */}
            <section className=" bg-white min-h-[600px]">
                <div className="max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40">
                    <div className="product-grid-definitive grid grid-cols-1 xl:grid-cols-4 gap-8">
                        {filteredProducts.map((p) => (
                            <Link
                                href={`/products/${p.id}`}
                                key={p.id}
                                className="product-card-definitive 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-500 overflow-hidden cursor-pointer"
                            >
                                {/* Image Container with Hover Swap */}
                                <div className="relative w-full aspect-square overflow-hidden bg-brand-dark/[0.02]">
                                    <Image
                                        src={p.image}
                                        alt={p.name}
                                        fill
                                        className="object-cover transition-opacity duration-700 group-hover:opacity-0"
                                    />
                                    <Image
                                        src={lineArtMap[p.id] || "/images/template-image-for-iroof1.webp"}
                                        alt={`${p.name} Details hover`}
                                        fill
                                        className="object-cover 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-6 text-left bg-white">
                                    <h4 className="text-[10px] sm:text-[11px] font-black uppercase tracking-[0.2em] text-brand-accent mb-2 transition-colors duration-300">
                                        iRoof Max
                                    </h4>
                                    <h3 className="text-lg lg:text-xl font-bold tracking-tight text-brand-dark group-hover:text-brand-accent transition-colors duration-500 line-clamp-2">
                                        {p.name.split(' ').slice(1).join(' ')} Roofing Sheet
                                    </h3>

                                    <div className="flex flex-wrap gap-2 mb-6 mt-3 flex-grow">
                                        {p.tags.slice(0, 3).map((tag, i) => (
                                            <span key={i} className="text-[9px] font-bold uppercase tracking-widest text-brand-dark/60 bg-brand-dark/5 px-2 py-1 flex items-center justify-center rounded-[4px]">
                                                {tag}
                                            </span>
                                        ))}
                                    </div>

                                    {/* Minimal Button */}
                                    <div className="border-t border-brand-dark/5 pt-5 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>
                </div>
            </section>



            {/* I-ROOF MAX TECHNICAL - RELOCATED */}
            <section className="py-16 bg-gray-50 mb-16" id="advantages">
                <div className="max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40">
                    <div className="reveal-up">
                        <div className="flex flex-col md:flex-row md:items-end justify-between gap-8 mb-16">
                            <div>
                                <h2 className="text-3xl md:text-[2.5rem] font-semibold text-brand-dark tracking-tighter mb-4">
                                    iRoof <span className="text-brand-accent">Max</span>
                                </h2>
                                <p className="text-[15px] font-normal text-brand-dark/70 max-w-2xl leading-relaxed">
                                    Manufactured using the highest quality ASA and UPVC raw materials, the 4-layer premium product exported globally, i-Roof Max.
                                </p>
                            </div>
                            <div className="flex items-center gap-3 px-6 py-3 rounded-full bg-zinc-50 border border-zinc-100">
                                <span className="text-[10px] font-medium uppercase tracking-widest text-brand-dark/40">Standard Reference</span>
                                <span className="text-xs font-medium text-brand-dark">Grade-A100</span>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 xl:grid-cols-2 gap-16 xl:gap-24">
                            {/* Advantages */}
                            <div>
                                <h3 className="text-xs font-semibold uppercase tracking-[0.3em] text-brand-dark/30 mb-8">Engineering Advantages</h3>
                                <div className="space-y-4">
                                    {[
                                        "Minimum noise generation during heavy rainfall.",
                                        "Reduced framework costs.",
                                        "100% free of carcinogenic and harmful materials.",
                                        "Beautiful interior aesthetic due to the White Bottom layer.",
                                        "Completely rust-free and corrosion-resistant.",
                                        "Significant heat reduction for a cooler interior.",
                                        "Available in 41-inch width and 10 convenient lengths.",
                                        "Long-lasting color retention that prevents fading.",
                                        "Superior strength achieved through a 4-layer structure.",
                                        "Exceptional durability thanks to the LG ASA outer layer."
                                    ].map((adv, i) => (
                                        <div key={i} className="flex items-start gap-4">
                                            <div className="w-1 h-1 rounded-full bg-brand-accent mt-2.5 shrink-0" />
                                            <p className="text-[13px] font-medium text-brand-dark/60 leading-tight">{adv}</p>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* Specifications */}
                            <div>
                                <h3 className="text-xs font-semibold uppercase tracking-[0.3em] text-brand-dark mb-8">Technical Specification Sheet</h3>
                                <div className="divide-y divide-zinc-300">
                                    {[
                                        { label: "Thickness", val: "2.8 (+/-0.1) mm" },
                                        { label: "Length", val: "5'9\" Feet to 20'10\" Feet" },
                                        { label: "Full Width", val: "3 Feet 5 Inches" },
                                        { label: "Covering Width", val: "3 Feet 1.5 Inches" },
                                        { label: "Gap Between Purlin", val: "26 Inches" },
                                        { label: "Weight", val: "480g/sqft" },
                                        { label: "Layers", val: "4 layers" }
                                    ].map((spec, i) => (
                                        <div key={i} className="flex items-center justify-between py-5 first:pt-0">
                                            <span className="text-sm font-medium uppercase tracking-widest text-brand-dark/90">{spec.label}</span>
                                            <span className="text-sm font-medium text-brand-dark">{spec.val}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            {/* ENGINEERING DATASHEET SECTION */}
            <section className=" bg-white pb-12">
                <div className="container max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40">
                    <div className="grid grid-cols-1 xl:grid-cols-2 gap-24 items-center">
                        <div>
                            <span className="text-[10px] font-black text-brand-accent uppercase tracking-[0.5em] mb-6 block">The iRoof Standard</span>
                            <h2 className="text-3xl md:text-[2.5rem] font-black text-brand-dark tracking-tighter leading-none mb-10">
                                Engineering <br />
                                <span className="text-zinc-300">Beyond the Edge</span>
                            </h2>
                            <p className="text-lg text-zinc-400 font-medium leading-relaxed italic mb-12">
                                Every iRoof sheet passes through 14 stages of technical validation. We don&apos;t just meet the standards; we define them for the Sri Lankan environment.
                            </p>
                            <div className="space-y-6">
                                {[
                                    "Hyper-Salinity Resistance Protocols",
                                    "Dynamic Heat Defraction (ASA Coating)",
                                    "Grade 5 Cyclone/Tornado Resilience",
                                    "Non-Oxidative Core Technology"
                                ].map((item, i) => (
                                    <div key={i} className="flex items-center gap-4 group">
                                        <div className="w-6 h-6 rounded-full bg-brand-accent/10 flex items-center justify-center text-brand-accent group-hover:bg-brand-accent group-hover:text-white transition-all">
                                            <ChevronRight size={14} />
                                        </div>
                                        <span className="text-sm font-bold text-brand-dark tracking-tight">{item}</span>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div className="relative aspect-square bg-zinc-50 overflow-hidden group border border-zinc-100 shadow-sm">
                            <Image
                                src="/images/blueroofnew.webp"
                                alt="Technical Detail"
                                fill
                                className="object-cover group-hover:grayscale-0 transition-all duration-1000"
                            />
                            {/* Technical Overlay */}
                            {/* <div className="absolute inset-x-8 bottom-8 p-10 bg-brand-dark/90 backdrop-blur-xl rounded-[2.5rem] border border-white/10 text-white">
                                <div className="flex items-center gap-6 mb-4">
                                    <div className="text-3xl font-black text-brand-accent italic">SLS</div>
                                    <div className="h-8 w-[1px] bg-white/10" />
                                    <div className="text-[10px] font-black uppercase tracking-widest">Official Certification <br /> #1222:2024</div>
                                </div>
                                <p className="text-xs text-zinc-400 font-medium leading-relaxed">
                                    The only roofing solution in the region to exceed ISO 9001:2015 tensile requirements by over 40%.
                                </p>
                            </div> */}
                        </div>
                    </div>
                </div>
            </section>

            <WhyIRoof />



            {/* Technical Diagrams */}
            <section className="py-20">
                <div className="max-w-[1400px] mx-auto px-6">
                    <div className="space-y-16 reveal-up">
                        <div className="grid grid-cols-1 xl:grid-cols-2 gap-12">
                            <div className="space-y-6">
                                <h4 className="text-sm font-black text-brand-dark tracking-tight uppercase">Layers</h4>
                                <div className="relative aspect-[4/3] overflow-hidden border border-zinc-100 bg-zinc-50 group cursor-pointer" onClick={() => setZoomedImage("/images/i-roof-xtra-layers (1)1.webp")}>
                                    <Image src="/images/i-roof-xtra-layers (1)1.webp" alt="iRoof Layers" fill className="object-contain p-8 group-hover:scale-110 transition-transform duration-700" />
                                </div>
                            </div>
                            <div className="space-y-6">
                                <h4 className="text-sm font-black text-brand-dark tracking-tight uppercase">Side Lap Details</h4>
                                <div className="relative aspect-[4/3] overflow-hidden border border-zinc-100 bg-zinc-50 group cursor-pointer" onClick={() => setZoomedImage("/images/i-roof-xtra-side-lap (1)1.webp")}>
                                    <Image src="/images/i-roof-xtra-side-lap (1)1.webp" alt="Side Lap Details" fill className="object-contain p-8 group-hover:scale-110 transition-transform duration-700" />
                                </div>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 xl:grid-cols-2 gap-12">
                            <div className="space-y-6">
                                <h4 className="text-sm font-black text-brand-dark tracking-tight uppercase">Comparison</h4>
                                <div className="relative aspect-[4/3] overflow-hidden border border-zinc-100 group cursor-pointer" onClick={() => setZoomedImage("/images/i-roof-xtra-comparison (1)1.webp")}>
                                    <Image src="/images/i-roof-xtra-comparison (1)1.webp" alt="Product Comparison" fill className="object-contain p-8 group-hover:scale-[1.02] transition-transform duration-1000" />
                                </div>
                            </div>
                            <div className="space-y-6">
                                <h4 className="text-sm font-black text-brand-dark tracking-tight uppercase">Installation Instructions</h4>
                                <div className="relative aspect-[4/3] overflow-hidden border border-zinc-100 bg-zinc-50 group cursor-pointer" onClick={() => setZoomedImage("/images/i-roof-installation1.webp")}>
                                    <Image src="/images/i-roof-installation1.webp" alt="Installation Instructions" fill className="object-contain p-8 group-hover:scale-[1.01] transition-transform duration-1000" />
                                </div>
                            </div>
                        </div>

                        <div className="flex flex-col xl:flex-row items-center justify-between p-8 md:p-12 rounded-[1.5rem] bg-brand-dark text-white gap-8 mt-12">
                            <div className="max-w-md">
                                <p className="text-lg font-bold leading-tight mb-2">Ready to install your iRoof?</p>
                                <p className="text-white/50 text-xs font-medium uppercase tracking-widest">Download current technical instructions (PDF)</p>
                            </div>
                            <a
                                href="/images/downloads/iRoof-Installation-Instructions.pdf"
                                target="_blank"
                                className="px-12 py-5 rounded-full bg-brand-accent text-white text-[11px] font-semibold uppercase tracking-[0.3em] flex items-center gap-4 hover:bg-white hover:text-brand-dark transition-all shadow-2xl"
                            >
                                Download Now
                                <Download size={18} />
                            </a>
                        </div>
                    </div>
                </div>
            </section>

            {zoomedImage && (
                <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 md:p-10 bg-brand-dark/95 backdrop-blur-xl animate-in fade-in duration-300" onClick={() => setZoomedImage(null)}>
                    <button
                        onClick={() => setZoomedImage(null)}
                        className="fixed top-6 right-6 md:top-8 md:right-8 z-50 w-12 h-12 rounded-full bg-white/10 text-white flex items-center justify-center hover:bg-red-600 transition-colors"
                    >
                        <X size={24} />
                    </button>
                    <div className="relative w-full max-w-5xl h-full max-h-[85vh]">
                        <Image src={zoomedImage} alt="Zoomed" fill className="object-contain" />
                    </div>
                </div>
            )}

            <Footer />
        </main>
    );
}
