const { useState, useEffect } = React;

const fetchApi = async (url) => {
    const res = await fetch(url);
    return res.json();
};

function Navbar({ setView, activeBrandFilter, setActiveBrandFilter }) {
    const [menuData, setMenuData] = useState({ brands: [] });
    const [isMenuOpen, setIsMenuOpen] = useState(false);
    const [isBrandsDropdownOpen, setIsBrandsDropdownOpen] = useState(false);
    const [isSearchOpen, setIsSearchOpen] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');

    useEffect(() => {
        fetchApi('api/menu.php').then(res => {
            if (res.success) setMenuData(res.data);
        });
    }, []);

    const handleSearch = (e) => {
        e.preventDefault();
        if (searchQuery.trim()) {
            setView('shop', null, '', { q: searchQuery });
            setIsSearchOpen(false);
            setIsMenuOpen(false);
        }
    };

    const handleBrandSelect = (brandSlug) => {
        setView('shop', null, '', { brands: [brandSlug] });
        setIsBrandsDropdownOpen(false);
        setIsMenuOpen(false);
    };

    return (
        <>
            <nav className="flex items-center justify-between px-6 lg:px-16 py-4 lg:py-6 bg-[#FAF6F0]/90 backdrop-blur-md sticky top-0 z-50 border-b border-[#EBE5DF] transition-all duration-300">

                {/* Mobile Left: Burger Menu */}
                <div className="lg:hidden flex-1 flex justify-start">
                    <button onClick={() => setIsMenuOpen(true)} className="text-[#221C1E] hover:text-[#540B24] hover:scale-105 transition-all p-2">
                        <i className="fa-solid fa-bars text-xl"></i>
                    </button>
                </div>

                {/* Logo */}
                <div onClick={() => setView('home')} className="flex items-center justify-center lg:justify-start cursor-pointer w-auto lg:w-1/4">
                    <span className="text-2xl lg:text-3xl font-serif font-semibold tracking-[0.25em] text-[#221C1E] hover:text-[#540B24] transition-colors">ZAAFA</span>
                </div>

                {/* Desktop Menu */}
                <div className="hidden lg:flex items-center justify-center flex-1 space-x-10 text-[12px] font-semibold tracking-[0.2em] text-[#221C1E] uppercase">
                    <a href="#" onClick={(e) => { e.preventDefault(); setView('shop'); }} className="hover:text-[#540B24] transition-colors py-2">All Perfumes</a>

                    {/* Brands Dropdown */}
                    <div className="relative group py-2"
                        onMouseEnter={() => setIsBrandsDropdownOpen(true)}
                        onMouseLeave={() => setIsBrandsDropdownOpen(false)}>
                        <a href="#" className="hover:text-[#540B24] transition-colors flex items-center gap-1.5">
                            Brands <i className="fa-solid fa-chevron-down text-[9px] transition-transform group-hover:rotate-180"></i>
                        </a>

                        {isBrandsDropdownOpen && (
                            <div className="absolute top-full left-1/2 -translate-x-1/2 w-56 bg-white border border-[#EBE5DF] shadow-2xl rounded-lg p-3 grid grid-cols-1 gap-1.5 animate-fade-in">
                                {menuData.brands.map(brand => (
                                    <a key={brand.id} href="#" onClick={(e) => { e.preventDefault(); handleBrandSelect(brand.slug); }}
                                        className="text-[11px] text-neutral-600 hover:text-[#540B24] hover:bg-[#FAF6F0] px-3 py-2 rounded transition-colors uppercase tracking-wider block">
                                        {brand.name}
                                    </a>
                                ))}
                                {menuData.brands.length === 0 && <div className="text-[11px] text-neutral-500 italic p-2">No brands available</div>}
                            </div>
                        )}
                    </div>

                    <a href="#" onClick={(e) => { e.preventDefault(); setView('shop', null, '', { q: '' }); }} className="hover:text-[#540B24] transition-colors py-2">Collections</a>
                </div>

                {/* Right Icons */}
                <div className="flex items-center justify-end w-auto lg:w-1/4 space-x-3 text-[#221C1E]">
                    <button onClick={() => setIsSearchOpen(true)} className="hover:text-[#540B24] hover:scale-105 transition-all p-2">
                        <i className="fa-solid fa-magnifying-glass text-lg"></i>
                    </button>
                </div>
            </nav>

            {/* Search Modal Overlay */}
            {isSearchOpen && (
                <div className="fixed inset-0 z-[100] bg-[#FAF6F0]/98 backdrop-blur-md flex flex-col items-center pt-32 px-6 animate-fade-in">
                    <button onClick={() => setIsSearchOpen(false)} className="absolute top-8 right-8 text-3xl text-neutral-500 hover:text-[#221C1E] transition-colors">
                        <i className="fa-solid fa-xmark"></i>
                    </button>
                    <h2 className="text-xs font-semibold tracking-[0.3em] uppercase text-[#540B24] mb-8">Search our fragrance house</h2>
                    <form onSubmit={handleSearch} className="w-full max-w-2xl relative">
                        <input type="text" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)}
                            placeholder="Search by brand, note, title..."
                            className="w-full text-2xl lg:text-4xl py-4 border-b border-[#EBE5DF] bg-transparent text-[#221C1E] outline-none focus:border-[#540B24] transition-colors font-serif placeholder-neutral-400" autoFocus />
                        <button type="submit" className="absolute right-0 top-1/2 -translate-y-1/2 text-2xl text-neutral-500 hover:text-[#540B24]">
                            <i className="fa-solid fa-arrow-right"></i>
                        </button>
                    </form>
                </div>
            )}

            {/* Mobile Sidebar Navigation */}
            <div className={`fixed inset-0 z-[60] bg-black/60 backdrop-blur-sm transition-opacity duration-300 lg:hidden ${isMenuOpen ? 'opacity-100 visible' : 'opacity-0 invisible'}`} onClick={() => setIsMenuOpen(false)}>
                <div className={`w-4/5 max-w-xs bg-[#FAF6F0] border-r border-[#EBE5DF] h-full shadow-2xl transition-transform duration-300 flex flex-col ${isMenuOpen ? 'translate-x-0' : '-translate-x-full'}`} onClick={e => e.stopPropagation()}>
                    <div className="p-6 border-b border-[#EBE5DF] flex justify-between items-center">
                        <div onClick={() => { setView('home'); setIsMenuOpen(false); }} className="text-xl font-serif font-bold tracking-wider text-[#221C1E] cursor-pointer">
                            ZAAFA
                        </div>
                        <button onClick={() => setIsMenuOpen(false)} className="text-neutral-500 hover:text-[#221C1E] text-xl p-2">
                            <i className="fa-solid fa-xmark"></i>
                        </button>
                    </div>
                    <div className="flex-1 overflow-y-auto p-6 space-y-8">
                        <div>
                            <h4 className="text-[10px] font-bold text-[#540B24] uppercase tracking-widest mb-4">Store Nav</h4>
                            <ul className="space-y-4 text-sm font-semibold tracking-wide text-[#221C1E]">
                                <li><a href="#" onClick={(e) => { e.preventDefault(); setView('shop'); setIsMenuOpen(false); }} className="hover:text-[#540B24]">All Perfumes</a></li>
                            </ul>
                        </div>
                        <div>
                            <h4 className="text-[10px] font-bold text-[#540B24] uppercase tracking-widest mb-4">Perfume Brands</h4>
                            <ul className="space-y-3 pl-2 border-l border-[#EBE5DF]">
                                {menuData.brands.map(brand => (
                                    <li key={brand.id}>
                                        <a href="#" onClick={(e) => { e.preventDefault(); handleBrandSelect(brand.slug); }}
                                            className="block text-xs uppercase tracking-wider text-[#6A5A5C] hover:text-[#540B24] transition-colors py-1">
                                            {brand.name}
                                        </a>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

function Footer() {
    return (
        <footer className="bg-[#540B24] text-[#FAF6F0]/80 pt-20 pb-10 font-sans">
            <div className="max-w-[1400px] mx-auto px-6 lg:px-16 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-12 mb-16">
                <div>
                    <h4 className="font-serif font-bold text-[#F4D9B5] mb-6 uppercase text-xs tracking-widest">ZAAFA House</h4>
                    <p className="text-xs text-[#FAF6F0]/90 mb-6 leading-relaxed">
                        Curators of global elite niche fragrances. Crafted for those who appreciate distinction, luxury, and premium elegance.
                    </p>
                    <div className="space-y-3 text-xs">
                        <p className="flex items-start"><i className="fa-solid fa-location-dot mt-0.5 mr-3 w-4 text-[#F4D9B5]"></i> Dubai, United Arab Emirates</p>

                        <p className="flex items-center"><i className="fa-solid fa-phone mr-3 w-4 text-[#F4D9B5]"></i> +971 55 178 7454</p>
                    </div>
                </div>
                <div>
                    <h4 className="font-serif font-bold text-[#F4D9B5] mb-6 uppercase text-xs tracking-widest">Fragrance Collections</h4>
                    <ul className="text-xs text-[#FAF6F0]/90 space-y-4 font-medium">
                        <li><a href="#" className="hover:text-[#F4D9B5] transition-colors">Our Brands</a></li>
                        <li><a href="#" className="hover:text-[#F4D9B5] transition-colors">Signature Blends</a></li>
                        <li><a href="#" className="hover:text-[#F4D9B5] transition-colors">Double-Pack Offers</a></li>
                        <li><a href="#" className="hover:text-[#F4D9B5] transition-colors">Trending Scents</a></li>
                    </ul>
                </div>
                <div>
                    <h4 className="font-serif font-bold text-[#F4D9B5] mb-6 uppercase text-xs tracking-widest">Information</h4>
                    <ul className="text-xs text-[#FAF6F0]/90 space-y-4 font-medium">
                        <li><a href="#" className="hover:text-[#F4D9B5] transition-colors">About ZAAFA</a></li>
                        <li><a href="#" className="hover:text-[#F4D9B5] transition-colors">Delivery Options</a></li>
                        <li><a href="#" className="hover:text-[#F4D9B5] transition-colors">Terms of Experience</a></li>
                        <li><a href="#" className="hover:text-[#F4D9B5] transition-colors">Support Center</a></li>
                    </ul>
                </div>
                <div>
                    <h4 className="font-serif font-bold text-[#F4D9B5] mb-6 uppercase text-xs tracking-widest">Newsletter</h4>
                    <p className="text-xs text-[#FAF6F0]/90 mb-6 leading-relaxed">Subscribe to receive exclusive fragrance releases and collection updates.</p>
                    <form className="flex flex-col space-y-3" onSubmit={e => e.preventDefault()}>
                        <input type="email" placeholder="Your luxury email address" className="px-4 py-3 text-xs border border-[#7D1B3D] rounded bg-[#691230] text-white focus:outline-none focus:border-[#F4D9B5] transition-colors placeholder-[#FAF6F0]/40" />
                        <button type="submit" className="bg-[#F4D9B5] text-[#540B24] px-6 py-3 text-xs font-bold tracking-widest uppercase rounded hover:bg-[#FAF6F0] transition-colors">Subscribe</button>
                    </form>
                </div>
            </div>
            <div className="max-w-[1400px] mx-auto px-6 lg:px-16 pt-8 border-t border-[#7D1B3D] flex flex-col md:flex-row justify-between items-center text-[10px] uppercase tracking-widest">
                <p>&copy; {new Date().getFullYear()} ZAAFA. All Rights Reserved.</p>
                <p className="mt-4 md:mt-0 flex gap-4">
                    <a href="#" className="hover:text-[#F4D9B5]">Privacy Policy</a>
                    <a href="#" className="hover:text-[#F4D9B5]">Terms of Use</a>
                </p>
            </div>
        </footer>
    );
}

function HeroSlider() {
    const [current, setCurrent] = useState(0);
    const slides = [
        "img/s1.webp",
        "img/s2.webp",
        "img/s3.webp"
    ];

    useEffect(() => {
        const timer = setInterval(() => {
            setCurrent(prev => (prev + 1) % slides.length);
        }, 6000);
        return () => clearInterval(timer);
    }, [slides.length]);

    return (
        <section className="relative w-full overflow-hidden group border-b border-[#EBE5DF]">
            {/* Structural base image to set height dynamically (100% width, height auto) */}
            <img src={slides[0]} className="w-full h-auto block opacity-0 pointer-events-none" aria-hidden="true" />
            
            {slides.map((slide, i) => (
                <img 
                    key={i}
                    src={slide} 
                    alt={`Slide ${i + 1}`}
                    className={`absolute inset-0 w-full h-auto block transition-opacity duration-1000 ${i === current ? 'opacity-100 z-10' : 'opacity-0 z-0'}`} 
                />
            ))}
            
            {/* Navigation Dots */}
            <div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex space-x-3 z-30">
                {slides.map((_, i) => (
                    <button key={i} onClick={() => setCurrent(i)}
                        className={`h-1.5 rounded-full transition-all duration-500 ${i === current ? 'w-8 bg-[#540B24]' : 'w-2 bg-white/60 hover:bg-white'}`}
                    />
                ))}
            </div>

            {/* Navigation Arrows */}
            <button onClick={() => setCurrent((current - 1 + slides.length) % slides.length)} 
                    className="absolute left-6 top-1/2 -translate-y-1/2 w-12 h-12 flex items-center justify-center border border-white/20 bg-black/20 hover:bg-black/55 text-white hover:border-white rounded-full backdrop-blur-sm opacity-0 group-hover:opacity-100 transition-all duration-300 z-30">
                <i className="fa-solid fa-chevron-left text-sm"></i>
            </button>
            <button onClick={() => setCurrent((current + 1) % slides.length)} 
                    className="absolute right-6 top-1/2 -translate-y-1/2 w-12 h-12 flex items-center justify-center border border-white/20 bg-black/20 hover:bg-black/55 text-white hover:border-white rounded-full backdrop-blur-sm opacity-0 group-hover:opacity-100 transition-all duration-300 z-30">
                <i className="fa-solid fa-chevron-right text-sm"></i>
            </button>
        </section>
    );
}

function Home({ setView }) {
    const [data, setData] = useState({ products: [], brands: [] });
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetchApi('api/home.php').then(res => {
            if (res.success) setData(res.data);
            setLoading(false);
            setTimeout(() => {
                const pos = sessionStorage.getItem('scroll_' + (window.location.hash || '#'));
                if (pos) {
                    window.scrollTo(0, parseInt(pos, 10));
                } else {
                    window.scrollTo(0, 0);
                }
            }, 50);
        });
    }, []);

    const goToProduct = (prod) => {
        sessionStorage.setItem('scroll_' + (window.location.hash || '#'), window.scrollY);
        const slug = prod.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
        setView('product', prod.id, slug);
    };

    if (loading) {
        return (
            <div className="h-[80vh] flex flex-col gap-4 items-center justify-center text-neutral-500 bg-[#FAF6F0]">
                <i className="fa-solid fa-spinner animate-spin text-3xl text-[#540B24]"></i>
                <p className="text-xs uppercase tracking-[0.2em] font-semibold text-[#540B24] animate-pulse">Entering Fragrance House...</p>
            </div>
        );
    }

    return (
        <div className="animate-fade-in bg-[#FAF6F0]">
            {/* HERO SLIDER */}
            <HeroSlider />

            {/* BRANDS NAVIGATION BAR */}
            <section className="py-12 border-b border-[#EBE5DF] bg-[#FAF6F0]">
                <div className="max-w-[1400px] mx-auto px-6 lg:px-16 text-center">
                    <p className="text-[10px] font-bold text-[#540B24] tracking-[0.35em] uppercase mb-8">Elite Perfume Houses</p>
                    <div className="flex flex-wrap gap-3 sm:gap-4 md:gap-6 py-3 justify-center items-center">
                        {data.brands.map(brand => (
                            <div key={brand.id} onClick={() => setView('shop', null, '', { brands: [brand.slug] })}
                                className="cursor-pointer border border-[#EBE5DF] hover:border-[#540B24]/50 bg-white px-4 py-2 sm:px-6 sm:py-3.5 rounded transition-all hover:scale-105">
                                <span className="font-serif text-[10px] sm:text-xs md:text-sm font-semibold tracking-wider text-[#221C1E] uppercase hover:text-[#540B24]">
                                    {brand.name}
                                </span>
                            </div>
                        ))}
                    </div>
                </div>
            </section>

            {/* CURATED POPULAR PRODUCTS */}
            <section className="max-w-[1400px] mx-auto px-6 lg:px-16 py-24">
                <div className="flex flex-col md:flex-row justify-between items-start md:items-end mb-16 gap-6">
                    <div>
                        <span className="text-[10px] font-bold text-[#540B24] tracking-[0.3em] uppercase mb-2 inline-block">Curated Selection</span>
                        <h2 className="text-3xl lg:text-4xl font-serif font-semibold tracking-wider uppercase text-[#221C1E]">Signature Fragrances</h2>
                    </div>
                    <a href="#" onClick={(e) => { e.preventDefault(); setView('shop'); }}
                        className="text-[11px] font-bold uppercase tracking-wider text-neutral-500 hover:text-[#540B24] transition-colors border-b border-[#EBE5DF] hover:border-[#540B24] pb-1">
                        View All Collections <i className="fa-solid fa-arrow-right ml-1"></i>
                    </a>
                </div>

                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-8">
                    {data.products.map(prod => (
                        <div key={prod.id} className="group bg-white border border-[#EBE5DF] hover:border-[#540B24]/30 hover:shadow-xl rounded-lg overflow-hidden flex flex-col justify-between transition-all duration-300">

                            {/* Product Image */}
                            <div onClick={() => goToProduct(prod)} className="cursor-pointer bg-[#FAF6F0]/50 aspect-[4/5] flex items-center justify-center overflow-hidden relative border-b border-[#EBE5DF]">
                                {prod.main_image ? (
                                    <img src={prod.main_image} alt={prod.title} className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" />
                                ) : (
                                    <i className="fa-solid fa-box text-3xl text-[#EBE5DF]"></i>
                                )}
                            </div>

                            {/* Product Info */}
                            <div className="p-4 lg:p-5 flex flex-col justify-between flex-1 text-center">
                                <div onClick={() => goToProduct(prod)} className="cursor-pointer mb-5">
                                    <h3 className="text-xs sm:text-sm font-semibold text-[#221C1E] line-clamp-1 group-hover:text-[#540B24] transition-colors">{prod.title}</h3>

                                    {/* Double Pricing options */}
                                    <div className="mt-3 flex flex-col gap-0.5 sm:gap-1 items-center justify-center">
                                        <p className="text-[9px] sm:text-xs text-[#6A5A5C] whitespace-nowrap">1 Piece: <span className="font-semibold text-neutral-800 text-[11px] sm:text-sm">AED {parseFloat(prod.price).toFixed(2)}</span></p>
                                        <p className="text-[9px] sm:text-xs text-[#540B24] font-medium whitespace-nowrap">2 Pieces: <span className="font-bold text-[#540B24] text-[11px] sm:text-sm">AED {parseFloat(prod.price_two).toFixed(2)}</span></p>
                                    </div>
                                </div>

                                <button onClick={() => goToProduct(prod)} className="w-full py-1.5 sm:py-2.5 rounded bg-white border border-[#EBE5DF] hover:border-[#540B24] hover:bg-[#540B24] hover:text-white text-[#221C1E] text-[8px] sm:text-[10px] font-bold uppercase tracking-wider sm:tracking-widest transition-all">
                                    Details
                                </button>
                            </div>
                        </div>
                    ))}
                    {data.products.length === 0 && <p className="text-neutral-500 col-span-full text-center py-20 font-serif">No products found in the boutique.</p>}
                </div>
            </section>
        </div>
    );
}

function Shop({ setView, initialFilters }) {
    const [data, setData] = useState({ products: [], brands: [] });
    const [loading, setLoading] = useState(true);
    const [activeBrands, setActiveBrands] = useState([]);

    useEffect(() => {
        const { q } = initialFilters;
        const qStr = q ? `?q=${encodeURIComponent(q)}` : '';
        setLoading(true);
        fetchApi(`api/shop.php${qStr}`).then(res => {
            if (res.success) {
                setData(res.data);
                // Synchronize url filters
                if (initialFilters.brands && initialFilters.brands.length > 0) {
                    setActiveBrands(initialFilters.brands);
                } else {
                    setActiveBrands([]);
                }
            }
            setLoading(false);
            setTimeout(() => {
                const pos = sessionStorage.getItem('scroll_' + (window.location.hash || '#'));
                if (pos) {
                    window.scrollTo(0, parseInt(pos, 10));
                } else {
                    window.scrollTo(0, 0);
                }
            }, 50);
        });
    }, [initialFilters.q, initialFilters.brands]);

    // Apply client-side brand filters to fetched products
    let filteredProducts = data.products;
    if (activeBrands.length > 0) {
        const brandIdsToKeep = data.brands.filter(b => activeBrands.includes(b.slug)).map(b => parseInt(b.id));
        filteredProducts = filteredProducts.filter(p => brandIdsToKeep.includes(parseInt(p.brand_id)));
    }

    const toggleBrand = (brandSlug) => {
        let newBrands = [...activeBrands];
        if (newBrands.includes(brandSlug)) {
            newBrands = newBrands.filter(b => b !== brandSlug);
        } else {
            newBrands.push(brandSlug);
        }
        setActiveBrands(newBrands);
        setView('shop', null, '', { q: initialFilters.q, brands: newBrands });
    };

    const goToProduct = (prod) => {
        sessionStorage.setItem('scroll_' + (window.location.hash || '#'), window.scrollY);
        const slug = prod.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
        setView('product', prod.id, slug);
    };

    if (loading) {
        return (
            <div className="min-h-screen flex flex-col gap-4 items-center justify-center text-neutral-500 bg-[#FAF6F0]">
                <i className="fa-solid fa-spinner animate-spin text-3xl text-[#540B24]"></i>
                <p className="text-xs uppercase tracking-[0.2em] font-semibold text-[#540B24] animate-pulse">Filtering Fragrance Database...</p>
            </div>
        );
    }

    return (
        <div className="pb-24 animate-fade-in bg-[#FAF6F0] min-h-screen text-[#221C1E]">

            {/* Search metadata banner if query active */}
            {initialFilters.q && (
                <div className="bg-[#FAF6F0] border-b border-[#EBE5DF] py-6 text-center">
                    <p className="text-xs text-neutral-500">Search Results For: <span className="font-serif italic text-[#540B24] text-sm font-semibold ml-2">"{initialFilters.q}"</span></p>
                </div>
            )}

            {/* Main shop container */}
            <div className="max-w-[1400px] mx-auto px-6 lg:px-16 py-12">

                {/* Header row */}
                <div className="flex flex-col md:flex-row justify-between items-start md:items-center border-b border-[#EBE5DF] pb-6 mb-10 gap-4">
                    <div>
                        <span className="text-[10px] font-bold text-[#540B24] tracking-[0.3em] uppercase mb-1 inline-block">Maison Catalog</span>
                        <h1 className="text-3xl font-serif tracking-wider uppercase text-[#221C1E]">Our Boutique</h1>
                    </div>
                    <span className="text-xs text-neutral-500">{filteredProducts.length} fragrances available</span>
                </div>

                {/* Brands filter strip (Horizontal pill selector) */}
                <div className="hidden md:flex mb-10 bg-white border border-[#EBE5DF] p-5 rounded-lg flex-col md:flex-row gap-4 items-center">
                    <span className="text-[10px] font-bold text-[#540B24] tracking-[0.2em] uppercase shrink-0"><i className="fa-solid fa-filter mr-1.5 text-[#540B24]"></i> Filter Brand:</span>
                    <div className="flex flex-wrap gap-2.5 items-center w-full">
                        <button onClick={() => { setActiveBrands([]); setView('shop', null, '', { q: initialFilters.q, brands: [] }); }}
                            className={`px-4 py-2 rounded text-[10px] font-bold uppercase tracking-wider transition-all border ${activeBrands.length === 0 ? 'bg-[#540B24] text-white border-transparent hover:bg-[#45081C]' : 'bg-[#FAF6F0] text-[#6A5A5C] border-[#EBE5DF] hover:text-[#540B24]'}`}>
                            All Brands
                        </button>
                        {data.brands.map(b => {
                            const isSelected = activeBrands.includes(b.slug);
                            return (
                                <button key={b.id} onClick={() => toggleBrand(b.slug)}
                                    className={`px-4 py-2 rounded text-[10px] font-bold uppercase tracking-wider transition-all border ${isSelected ? 'bg-[#540B24] text-white border-transparent hover:bg-[#45081C]' : 'bg-[#FAF6F0] text-[#6A5A5C] border-[#EBE5DF] hover:text-[#540B24]'}`}>
                                    {b.name}
                                </button>
                            );
                        })}
                    </div>
                </div>

                {/* Product Grid */}
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-8">
                    {filteredProducts.map(prod => (
                        <div key={prod.id} className="group bg-white border border-[#EBE5DF] hover:border-[#540B24]/30 hover:shadow-xl rounded-lg overflow-hidden flex flex-col justify-between transition-all duration-300">

                            {/* Product Image */}
                            <div onClick={() => goToProduct(prod)} className="cursor-pointer bg-[#FAF6F0]/50 aspect-[4/5] flex items-center justify-center overflow-hidden relative border-b border-[#EBE5DF]">
                                {prod.main_image ? (
                                    <img src={prod.main_image} alt={prod.title} className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" />
                                ) : (
                                    <i className="fa-solid fa-box text-3xl text-[#EBE5DF]"></i>
                                )}
                            </div>

                            {/* Product Info */}
                            <div className="p-4 lg:p-5 flex flex-col justify-between flex-1 text-center">
                                <div onClick={() => goToProduct(prod)} className="cursor-pointer mb-5">
                                    <h3 className="text-xs sm:text-sm font-semibold text-[#221C1E] line-clamp-1 group-hover:text-[#540B24] transition-colors">{prod.title}</h3>

                                    {/* Double Pricing */}
                                    <div className="mt-3 flex flex-col gap-0.5 sm:gap-1 items-center justify-center">
                                        <p className="text-[9px] sm:text-xs text-[#6A5A5C] whitespace-nowrap">1 Piece: <span className="font-semibold text-neutral-800 text-[11px] sm:text-sm">AED {parseFloat(prod.price).toFixed(2)}</span></p>
                                        <p className="text-[9px] sm:text-xs text-[#540B24] font-medium whitespace-nowrap">2 Pieces: <span className="font-bold text-[#540B24] text-[11px] sm:text-sm">AED {parseFloat(prod.price_two).toFixed(2)}</span></p>
                                    </div>
                                </div>

                                <button onClick={() => goToProduct(prod)} className="w-full py-1.5 sm:py-2.5 rounded bg-white border border-[#EBE5DF] hover:border-[#540B24] hover:bg-[#540B24] hover:text-white text-[#221C1E] text-[8px] sm:text-[10px] font-bold uppercase tracking-wider sm:tracking-widest transition-all">
                                    Details
                                </button>
                            </div>
                        </div>
                    ))}
                    {filteredProducts.length === 0 && (
                        <div className="col-span-full py-32 flex flex-col items-center justify-center text-neutral-500">
                            <i className="fa-solid fa-box-open text-4xl mb-4 opacity-50 text-[#540B24]"></i>
                            <p className="font-serif italic text-lg">No perfumes match your filter choice.</p>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

function ProductDetail({ productId, setView }) {
    const [product, setProduct] = useState(null);
    const [loading, setLoading] = useState(true);
    const [activeImage, setActiveImage] = useState(0);
    const [selectedQty, setSelectedQty] = useState('1'); // '1' or '2' pieces

    useEffect(() => {
        window.scrollTo(0, 0);
        fetchApi(`api/product.php?id=${productId}`).then(res => {
            if (res.success) setProduct(res.data);
            setLoading(false);
        });
    }, [productId]);

    if (loading) {
        return (
            <div className="h-[80vh] flex flex-col gap-4 items-center justify-center text-neutral-500 bg-[#FAF6F0]">
                <i className="fa-solid fa-spinner animate-spin text-3xl text-[#540B24]"></i>
                <p className="text-xs uppercase tracking-[0.2em] font-semibold text-[#540B24] animate-pulse">Revealing Fragrance...</p>
            </div>
        );
    }
    if (!product) return <div className="min-h-screen flex items-center justify-center bg-[#FAF6F0] text-neutral-500">Product not found.</div>;

    const images = product.images || [];
    const activePrice = selectedQty === '2' ? product.price_two : product.price;

    const getWhatsAppUrl = () => {
        const productTitle = product.title;
        const brandName = product.brand_name || 'Premium Brand';
        const qtyLabel = selectedQty === '2' ? '2 Pieces Package' : '1 Piece';
        const priceLabel = `AED ${parseFloat(activePrice).toFixed(2)}`;
        const productUrl = `${window.location.origin}${window.location.pathname}#product/${productId}-${productTitle.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')}`;

        const messageText = `Hi ZAAFA, I would like to order:
Fragrance: ${productTitle}
Brand: ${brandName}
Package Offer: ${qtyLabel}
Price: ${priceLabel}
Link: ${productUrl}`;

        return `https://wa.me/971551787454?text=${encodeURIComponent(messageText)}`;
    };

    return (
        <div className="bg-[#FAF6F0] text-[#221C1E] min-h-screen">
            <div className="max-w-[1200px] mx-auto px-6 py-12 lg:py-20 animate-fade-in">
                {/* Top Breadcrumb */}
                <div className="text-[10px] text-neutral-500 font-medium tracking-[0.25em] uppercase mb-10">
                    <span className="cursor-pointer hover:text-[#540B24]" onClick={() => setView('home')}>Home</span>
                    <span className="mx-2 text-neutral-300">/</span>
                    <span className="cursor-pointer hover:text-[#540B24]" onClick={() => setView('shop')}>Perfumes</span>
                    <span className="mx-2 text-neutral-300">/</span>
                    <span className="text-[#221C1E]">{product.title}</span>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-16">
                    {/* Images Section */}
                    <div className="flex flex-col-reverse lg:flex-row gap-4">
                        <div className="flex lg:flex-col gap-4 overflow-x-auto lg:overflow-y-auto lg:w-24 shrink-0 hide-scrollbar">
                            {images.map((img, i) => (
                                <div key={i} onClick={() => setActiveImage(i)}
                                    className={`w-20 h-24 lg:w-24 lg:h-28 flex-shrink-0 rounded overflow-hidden cursor-pointer border transition-all bg-white flex items-center justify-center p-1 ${activeImage === i ? 'border-[#540B24] opacity-100' : 'border-[#EBE5DF] opacity-50 hover:opacity-100'}`}>
                                    <img src={img.image_url} className="w-full h-full object-cover rounded" alt="Thumb" />
                                </div>
                            ))}
                        </div>
                        <div className="w-full aspect-[4/5] bg-white border border-[#EBE5DF] rounded-xl flex items-center justify-center overflow-hidden relative">
                            {images[activeImage] ? (
                                <img src={images[activeImage].image_url} className="w-full h-full object-cover" alt="Main" />
                            ) : (
                                <i className="fa-solid fa-image text-8xl text-[#EBE5DF]"></i>
                            )}
                        </div>
                    </div>

                    {/* Info Section */}
                    <div className="pt-2 flex flex-col justify-between">
                        <div>
                            {product.brand_name && (
                                <span className="text-[10px] font-bold tracking-[0.3em] uppercase text-[#540B24] mb-3 inline-block">
                                    {product.brand_name}
                                </span>
                            )}
                            <h1 className="text-3xl lg:text-5xl font-serif tracking-wider leading-tight mb-6 uppercase text-[#221C1E]">
                                {product.title}
                            </h1>

                            {/* Dual Package Pricing Selector */}
                            <div className="mb-8 border border-[#EBE5DF] rounded-lg p-5 bg-white space-y-4">
                                <p className="text-[10px] font-bold tracking-[0.25em] text-[#6A5A5C] uppercase">Select Quantity Package</p>

                                <div className="grid grid-cols-2 gap-4">
                                    {/* 1 Piece option */}
                                    <div onClick={() => setSelectedQty('1')}
                                        className={`cursor-pointer p-4 rounded border transition-all flex flex-col justify-between min-h-[90px] ${selectedQty === '1' ? 'bg-[#FAF6F0] border-[#540B24]' : 'bg-white border-[#EBE5DF] hover:border-[#FAF6F0]'}`}>
                                        <div className="flex items-center justify-between">
                                            <span className="text-[10px] font-bold uppercase tracking-wider text-[#221C1E]">1 Piece</span>
                                            <div className={`w-3.5 h-3.5 rounded-full border flex items-center justify-center ${selectedQty === '1' ? 'border-[#540B24]' : 'border-neutral-300'}`}>
                                                {selectedQty === '1' && <div className="w-1.5 h-1.5 rounded-full bg-[#540B24]" />}
                                            </div>
                                        </div>
                                        <p className="text-lg font-bold text-[#221C1E] mt-2">AED {parseFloat(product.price).toFixed(2)}</p>
                                    </div>

                                    {/* 2 Pieces option */}
                                    <div onClick={() => setSelectedQty('2')}
                                        className={`cursor-pointer p-4 rounded border transition-all flex flex-col justify-between min-h-[90px] relative ${selectedQty === '2' ? 'bg-[#FAF6F0] border-[#540B24] shadow-md shadow-[#540B24]/5' : 'bg-white border-[#EBE5DF] hover:border-[#FAF6F0]'}`}>
                                        <span className="absolute -top-2.5 right-3 bg-[#540B24] text-white text-[8px] font-bold uppercase px-2 py-0.5 rounded-full tracking-wider">Best Value</span>
                                        <div className="flex items-center justify-between">
                                            <span className="text-[10px] font-bold uppercase tracking-wider text-[#221C1E]">2 Pieces (Combo)</span>
                                            <div className={`w-3.5 h-3.5 rounded-full border flex items-center justify-center ${selectedQty === '2' ? 'border-[#540B24]' : 'border-neutral-300'}`}>
                                                {selectedQty === '2' && <div className="w-1.5 h-1.5 rounded-full bg-[#540B24]" />}
                                            </div>
                                        </div>
                                        <p className="text-lg font-bold text-[#540B24] mt-2">AED {parseFloat(product.price_two).toFixed(2)}</p>
                                    </div>
                                </div>
                            </div>

                            {/* Description (tinymce HTML) */}
                            <div className="prose prose-sm text-neutral-600 mb-10 max-w-none leading-relaxed prose-headings:text-[#221C1E] prose-strong:text-[#221C1E]"
                                dangerouslySetInnerHTML={{ __html: product.description }}></div>
                        </div>

                        {/* Order details actions */}
                        <div>
                            <div className="pt-8 border-t border-[#EBE5DF] flex flex-col gap-4">
                                <a href={getWhatsAppUrl()} target="_blank"
                                    className="w-full bg-[#540B24] hover:bg-[#45081C] text-white py-4.5 rounded-lg flex items-center justify-center space-x-3 font-bold transition-all shadow-xl shadow-[#540B24]/10 hover:-translate-y-0.5">
                                    <i className="fa-brands fa-whatsapp text-2xl"></i>
                                    <span className="text-xs tracking-[0.2em] font-semibold uppercase">Order via WhatsApp</span>
                                </a>
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-10 border-t border-[#EBE5DF] pt-8">
                                <div className="bg-white border border-[#EBE5DF] p-4 rounded-lg flex items-start space-x-4">
                                    <i className="fa-solid fa-truck-fast text-xl text-[#540B24] mt-0.5"></i>
                                    <div>
                                        <h4 className="font-bold text-[10px] text-[#221C1E] tracking-widest uppercase">Free Delivery in UAE</h4>
                                        <p className="text-[10px] text-neutral-500 mt-1">Enjoy complimentary, reliable delivery to all UAE emirates on every order.</p>
                                    </div>
                                </div>
                                <div className="bg-white border border-[#EBE5DF] p-4 rounded-lg flex items-start space-x-4">
                                    <i className="fa-solid fa-money-bill-wave text-xl text-[#540B24] mt-0.5"></i>
                                    <div>
                                        <h4 className="font-bold text-[10px] text-[#221C1E] tracking-widest uppercase">Cash on Delivery</h4>
                                        <p className="text-[10px] text-neutral-500 mt-1">Convenient Cash on Delivery (COD) services available within all UAE emirates.</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    );
}

function ScrollToTopButton() {
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        const toggleVisibility = () => {
            if (window.pageYOffset > 300) {
                setIsVisible(true);
            } else {
                setIsVisible(false);
            }
        };
        window.addEventListener("scroll", toggleVisibility);
        return () => window.removeEventListener("scroll", toggleVisibility);
    }, []);

    const scrollToTop = () => {
        window.scrollTo({
            top: 0,
            behavior: "smooth"
        });
    };

    if (!isVisible) return null;

    return (
        <button onClick={scrollToTop} className="fixed bottom-12 right-6 lg:bottom-16 lg:right-16 bg-[#540B24] hover:bg-[#45081C] text-white w-12 h-12 rounded-full shadow-2xl flex items-center justify-center hover:-translate-y-1 transition-all z-50">
            <i className="fa-solid fa-arrow-up"></i>
        </button>
    );
}

function App() {
    const [view, setView] = useState('home');
    const [currentProductId, setCurrentProductId] = useState(null);
    const [shopFilters, setShopFilters] = useState({ brands: [] });

    // Dynamic Hash URL Routing
    useEffect(() => {
        const handleHashChange = () => {
            const hashStr = window.location.hash.replace('#', '');
            const [path, qs] = hashStr.split('?');
            const params = new URLSearchParams(qs || '');

            if (path.startsWith('product/')) {
                const part = path.replace('product/', '');
                const id = part.split('-')[0]; // Extract the ID before the dash
                setCurrentProductId(id);
                setView('product');
            } else if (path.startsWith('shop')) {
                const brs = params.get('brands');
                const q = params.get('q');
                setShopFilters({
                    brands: brs ? brs.split(',') : [],
                    q: q || ''
                });
                setView('shop');
            } else {
                setView('home');
            }
        };

        handleHashChange(); // Execute on initial load
        window.addEventListener('hashchange', handleHashChange);
        return () => window.removeEventListener('hashchange', handleHashChange);
    }, []);

    // Custom router navigate
    const navigate = (newView, id = null, slug = '', params = {}) => {
        let targetHash = '';
        if (newView === 'home') {
            targetHash = '';
        } else if (newView === 'product') {
            targetHash = `product/${id}${slug ? '-' + slug : ''}`;
        } else if (newView === 'shop') {
            const urlParams = new URLSearchParams();
            if (params.brands && params.brands.length > 0) urlParams.set('brands', params.brands.join(','));
            if (params.q) urlParams.set('q', params.q);
            const qs = urlParams.toString();
            targetHash = `shop${qs ? '?' + qs : ''}`;
        }

        sessionStorage.removeItem('scroll_#' + targetHash);
        window.scrollTo(0, 0);
        window.location.hash = targetHash;
    };

    return (
        <div className="text-[#221C1E] antialiased bg-[#FAF6F0] min-h-screen selection:bg-[#F4D9B5] selection:text-[#540B24] transition-all">
            <style dangerouslySetInnerHTML={{
                __html: `
                .hide-scrollbar::-webkit-scrollbar { display: none; }
                .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
            `}} />

            <div className="bg-[#540B24] text-[#FAF6F0] text-center text-[9px] py-2.5 px-4 font-semibold tracking-[0.25em] uppercase relative z-50 border-b border-[#7D1B3D]">
                DISCOVER PREMIUM LUXURY SCENTS | FREE DELIVERY ACROSS UAE FOR 2 PIECES PACKAGES
            </div>

            <Navbar setView={navigate} />
            <main className="min-h-screen">
                {view === 'home' && <Home setView={navigate} />}
                {view === 'shop' && <Shop setView={navigate} initialFilters={shopFilters} />}
                {view === 'product' && <ProductDetail productId={currentProductId} setView={navigate} />}
            </main>
            <ScrollToTopButton />
            <Footer />
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
