const { useState, useEffect } = React;

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

function Navbar({ setView }) {
    return (
        <nav className="flex items-center justify-between px-6 lg:px-12 py-5 bg-white/90 backdrop-blur-md sticky top-0 z-50 border-b border-gray-100">
            <div onClick={() => setView('home')} className="text-2xl font-bold tracking-wider cursor-pointer flex items-center space-x-2">
                <i className="fa-solid fa-gem text-xl"></i> 
                <span>LUXE</span>
            </div>
            
            <div className="hidden lg:flex items-center space-x-8 text-[13px] font-medium text-gray-500 tracking-wide uppercase">
                <a href="#" onClick={(e) => { e.preventDefault(); setView('shop'); }} className="text-black font-semibold border-b border-black pb-1">All Products</a>
                <a href="#" onClick={(e) => { e.preventDefault(); setView('shop', null, '', {category: 'watches'}); }} className="hover:text-black transition-colors">Watches</a>
                <a href="#" onClick={(e) => { e.preventDefault(); setView('shop', null, '', {category: 'bags-wallets'}); }} className="hover:text-black transition-colors">Bags & Wallets</a>
                <a href="#" onClick={(e) => { e.preventDefault(); setView('shop', null, '', {category: 'footwear'}); }} className="hover:text-black transition-colors">Footwear</a>
                <a href="#" onClick={(e) => { e.preventDefault(); setView('shop', null, '', {category: 'jewellery'}); }} className="hover:text-black transition-colors">Jewellery</a>
            </div>
            
            <div className="flex items-center space-x-6 text-gray-700">
                <button className="hover:text-black hover:scale-110 transition-transform"><i className="fa-solid fa-magnifying-glass"></i></button>
                <button className="hover:text-black hover:scale-110 transition-transform"><i class="fa-regular fa-user"></i></button>
                <button className="hover:text-black hover:scale-110 transition-transform relative">
                    <i className="fa-solid fa-cart-shopping"></i>
                    <span className="absolute -top-2 -right-2 bg-black text-white text-[10px] w-4 h-4 flex items-center justify-center rounded-full">0</span>
                </button>
                <button className="lg:hidden hover:text-black hover:scale-110 transition-transform"><i className="fa-solid fa-bars text-lg"></i></button>
            </div>
        </nav>
    );
}

function Footer() {
    return (
        <footer className="bg-[#f9f9f9] pt-20 pb-10 border-t border-gray-200">
            <div className="max-w-[1400px] mx-auto px-6 lg:px-12 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-12 mb-16">
                <div>
                    <h4 className="font-bold mb-6 text-gray-900 uppercase text-xs tracking-widest">Our Store</h4>
                    <div className="space-y-4 text-sm text-gray-600">
                        <p className="flex items-start"><i className="fa-solid fa-location-dot mt-1 mr-3 w-4"></i> 123 Luxury Avenue, New York, NY 10001</p>
                        <p className="flex items-center"><i className="fa-solid fa-envelope mr-3 w-4"></i> info@luxurystore.com</p>
                        <p className="flex items-center"><i className="fa-solid fa-phone mr-3 w-4"></i> +1 (234) 567 8900</p>
                    </div>
                </div>
                <div>
                    <h4 className="font-bold mb-6 text-gray-900 uppercase text-xs tracking-widest">Customer Service</h4>
                    <ul className="text-sm text-gray-600 space-y-4 font-medium">
                        <li><a href="#" className="hover:text-black transition-colors">Contact Us</a></li>
                        <li><a href="#" className="hover:text-black transition-colors">Shipping Details</a></li>
                        <li><a href="#" className="hover:text-black transition-colors">Returns & Exchanges</a></li>
                        <li><a href="#" className="hover:text-black transition-colors">FAQ</a></li>
                    </ul>
                </div>
                <div>
                    <h4 className="font-bold mb-6 text-gray-900 uppercase text-xs tracking-widest">Information</h4>
                    <ul className="text-sm text-gray-600 space-y-4 font-medium">
                        <li><a href="#" className="hover:text-black transition-colors">About Us</a></li>
                        <li><a href="#" className="hover:text-black transition-colors">Careers</a></li>
                        <li><a href="#" className="hover:text-black transition-colors">Privacy Policy</a></li>
                        <li><a href="#" className="hover:text-black transition-colors">Terms of Service</a></li>
                    </ul>
                </div>
                <div>
                    <h4 className="font-bold mb-6 text-gray-900 uppercase text-xs tracking-widest">Newsletter</h4>
                    <p className="text-[13px] text-gray-600 mb-6 leading-relaxed">Subscribe to receive updates.</p>
                    <form className="flex flex-col space-y-3" onSubmit={e=>e.preventDefault()}>
                        <input type="email" placeholder="Enter your email" className="px-5 py-3.5 w-full text-sm border border-gray-300 rounded-md focus:outline-none focus:border-black transition-colors bg-white" />
                        <button type="submit" className="bg-black text-white px-6 py-3.5 text-xs font-bold tracking-widest uppercase rounded-md hover:bg-gray-800 transition-colors shadow-lg">Subscribe</button>
                    </form>
                </div>
            </div>
        </footer>
    );
}

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

    useEffect(() => {
        window.scrollTo(0, 0);
        fetchApi('api/home.php').then(res => {
            if (res.success) setData(res.data);
            setLoading(false);
        });
    }, []);

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

    if (loading) return <div className="h-[60vh] flex items-center justify-center text-gray-500 animate-pulse">Loading Luxe Experience...</div>;

    return (
        <div className="animate-fade-in">
            {/* HEROS */}
            <section className="bg-[#f0f0f0] relative flex items-center min-h-[60vh] overflow-hidden">
                <div className="max-w-[1400px] mx-auto w-full px-6 lg:px-12 grid grid-cols-1 lg:grid-cols-2 gap-12 relative z-10 py-16 lg:py-24 items-center">
                    <div className="space-y-6 lg:max-w-lg z-20">
                        <p className="text-xs font-semibold tracking-[0.2em] text-gray-500 uppercase">A Legacy You Wear</p>
                        <h1 className="text-4xl sm:text-5xl lg:text-6xl font-bold text-gray-900 leading-[1.1] tracking-tight">Uncompromising<br/>craftsmanship</h1>
                        <p className="text-gray-600 text-sm hidden lg:block max-w-sm mt-4 leading-relaxed">Discover an exclusive collection of luxury items crafted to perfection.</p>
                        <div className="pt-6">
                            <button className="inline-block border border-black bg-transparent text-black px-10 py-3.5 text-sm font-semibold tracking-wider hover:bg-black hover:text-white transition-all duration-300">SHOP NOW</button>
                        </div>
                    </div>
                    <div className="relative w-full h-full lg:absolute lg:top-0 lg:right-0 lg:w-1/2 flex items-center lg:h-full z-10">
                        <img src="https://images.unsplash.com/photo-1548171915-e29ed8563dd4?q=80&w=1920&auto=format&fit=crop" className="w-full h-[400px] lg:h-full object-cover object-center lg:rounded-l-3xl rounded-lg" alt="Luxury" />
                    </div>
                </div>
            </section>

            {/* CATEGORIES */}
            <section className="py-20 px-6 lg:px-12 max-w-[1400px] mx-auto text-center">
                <h2 className="text-xl lg:text-2xl font-semibold mb-12 text-gray-900 tracking-widest uppercase">Shop By Category</h2>
                <div className="flex overflow-x-auto gap-10 pb-10 snap-x hide-scrollbar justify-start md:justify-center">
                    {data.categories.map(cat => (
                        <div key={cat.id} className="snap-center shrink-0 flex flex-col items-center group cursor-pointer w-24 lg:w-32">
                            <div className="w-24 h-24 lg:w-32 lg:h-32 rounded-full overflow-hidden mb-5 bg-[#f5f5f5] flex items-center justify-center shadow-sm group-hover:shadow-md transition-shadow">
                                {cat.thumb_image ? (
                                    <img src={cat.thumb_image} className="object-cover w-full h-full group-hover:scale-110 transition-transform duration-500" alt={cat.name} />
                                ) : (
                                    <i className="fa-solid fa-layer-group text-3xl text-gray-300"></i>
                                )}
                            </div>
                            <p className="text-[11px] font-semibold tracking-widest text-gray-700 uppercase">{cat.name}</p>
                        </div>
                    ))}
                    {data.categories.length===0 && <p className="text-gray-500 w-full">No categories available.</p>}
                </div>
            </section>

            {/* POPULAR PRODUCTS */}
            <section className="max-w-[1400px] mx-auto px-6 lg:px-12 py-20 bg-gray-50/50">
                <div className="flex justify-between items-end mb-10 pb-4 border-b border-gray-100">
                    <h2 className="text-xl lg:text-2xl font-bold tracking-widest uppercase text-gray-900">Popular Products</h2>
                    <a href="#" className="text-[11px] font-bold uppercase tracking-wider hover:text-gray-500 transition-colors border-b border-black pb-0.5">View All</a>
                </div>
                
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
                    {data.products.map(prod => (
                        <div key={prod.id} className="text-center group flex flex-col h-full bg-white rounded-xl shadow-sm hover:shadow-xl transition-shadow border border-gray-100 overflow-hidden pb-4">
                            
                            <div onClick={() => goToProduct(prod)} className="cursor-pointer bg-[#f7f7f7] relative w-full aspect-[4/5] flex items-center justify-center overflow-hidden">
                                {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-110 mix-blend-multiply" />
                                ) : (
                                    <i className="fa-solid fa-box text-4xl text-gray-300"></i>
                                )}
                            </div>
                            
                            <div className="px-4 pt-4 pb-2 cursor-pointer text-center" onClick={() => goToProduct(prod)}>
                                <h3 className="text-sm font-semibold text-gray-900 truncate">{prod.title}</h3>
                                <p className="text-sm font-bold text-gray-500 mt-1 mb-3">AED {parseFloat(prod.price).toFixed(2)}</p>
                                
                                {/* WhatsApp Button - Smaller and inline */}
                                <a href={`https://wa.me/971551787454?text=${encodeURIComponent(`Hi, I am interested in ${prod.title}`)}`} target="_blank" className="inline-flex items-center space-x-1.5 bg-[#25D366] text-white px-4 py-1.5 rounded-full text-[11px] font-bold shadow-sm hover:bg-[#1ebe57] transition-colors" onClick={(e) => e.stopPropagation()}>
                                    <i className="fa-brands fa-whatsapp text-[14px]"></i>
                                    <span>Inquire</span>
                                </a>
                            </div>
                        </div>
                    ))}
                    {data.products.length === 0 && <p className="text-gray-500 col-span-full text-center">No products found.</p>}
                </div>
            </section>

            {/* BRANDS */}
            <section className="max-w-[1400px] mx-auto px-6 lg:px-12 py-16 border-t border-gray-100 mb-10">
                 <div className="flex flex-wrap justify-center lg:justify-between items-center gap-10 lg:gap-6 opacity-40 grayscale hover:grayscale-0 transition-all duration-500">
                    {data.brands.map(brand => (
                        <div key={brand.id}>
                            {brand.thumb_image ? (
                                <img src={brand.thumb_image} alt={brand.name} className="h-12 lg:h-16 object-contain" />
                            ) : (
                                <div className="text-xl lg:text-2xl font-bold tracking-[0.2em] uppercase font-serif text-gray-800">{brand.name}</div>
                            )}
                        </div>
                    ))}
                </div>
            </section>
        </div>
    );
}

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

    useEffect(() => {
        window.scrollTo(0, 0);
        fetchApi('api/shop.php').then(res => {
            if (res.success) setData(res.data);
            setLoading(false);
        });
    }, []);

    // Filter logic
    const { category, brands } = initialFilters;

    const filteredCategory = data.categories.find(c => c.slug === category) || null;
    let filteredProducts = data.products;

    // Recursive helper to get all child category IDs belonging to a parent
    const getDescendantCategoryIds = (catId, allCats) => {
        let ids = [parseInt(catId)];
        const children = allCats.filter(c => parseInt(c.parent_id) === parseInt(catId));
        children.forEach(child => {
            ids = ids.concat(getDescendantCategoryIds(child.id, allCats));
        });
        return ids;
    };

    const getRootAncestor = (cat, allCats) => {
        if (!cat) return null;
        if (!cat.parent_id || cat.parent_id === '0') return cat;
        const parent = allCats.find(c => parseInt(c.id) === parseInt(cat.parent_id));
        return getRootAncestor(parent, allCats);
    };

    if (filteredCategory) {
        const validCatIds = getDescendantCategoryIds(filteredCategory.id, data.categories);
        filteredProducts = filteredProducts.filter(p => validCatIds.includes(parseInt(p.category_id)));
    }

    const activeTopCategory = getRootAncestor(filteredCategory, data.categories);

    // Isolate top-level categories for the UI selector
    const topLevelCategories = data.categories.filter(c => !c.parent_id || c.parent_id === '0' || c.parent_id === '');

    const subCategoriesToDisplay = activeTopCategory 
        ? data.categories.filter(c => parseInt(c.parent_id) === parseInt(activeTopCategory.id))
        : [];

    // Extrapolate available brands to build the bottom bar filter
    const availableBrandIds = new Set(filteredProducts.map(p => parseInt(p.brand_id)));
    const availableBrands = data.brands.filter(b => availableBrandIds.has(parseInt(b.id)));

    // Actually apply brand filtering to the active products
    if (brands && brands.length > 0) {
        const brandIdsToKeep = data.brands.filter(b => brands.includes(b.slug)).map(b => parseInt(b.id));
        filteredProducts = filteredProducts.filter(p => brandIdsToKeep.includes(parseInt(p.brand_id)));
    }

    const selectCategory = (catSlug) => {
        if (category === catSlug) return;
        setView('shop', null, '', { category: catSlug, brands: [] });
    };

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

    const goToProduct = (prod) => {
        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 items-center justify-center text-gray-500 animate-pulse">Loading Catalog...</div>;

    return (
        <div className="pb-24 animate-fade-in relative min-h-screen bg-[#fcfcfc]">
            {/* Top Categories Horizontal Scroll */}
            <div className="bg-white border-b border-gray-100 shadow-sm">
                <div className="max-w-[1400px] mx-auto px-4 py-4 flex overflow-x-auto gap-6 hide-scrollbar snap-x">
                    <div onClick={() => setView('shop', null, '', { category: null, brands: [] })} 
                         className={`snap-center shrink-0 flex flex-col items-center cursor-pointer w-20 transition-opacity ${!category ? 'opacity-100' : 'opacity-40 hover:opacity-100'}`}>
                         <div className={`w-16 h-16 rounded-full flex items-center justify-center mb-2 shadow-sm border-2 ${!category ? 'border-black' : 'border-transparent bg-gray-50'}`}>
                             <i className="fa-solid fa-border-all text-xl"></i>
                         </div>
                         <span className="text-[10px] font-bold uppercase tracking-widest text-center">All</span>
                    </div>
                    {topLevelCategories.map(cat => {
                        const isActive = activeTopCategory && activeTopCategory.id === cat.id;
                        return (
                        <div key={cat.id} onClick={() => selectCategory(cat.slug)} 
                             className={`snap-center shrink-0 flex flex-col items-center cursor-pointer w-20 transition-opacity ${isActive ? 'opacity-100' : 'opacity-50 hover:opacity-100'}`}>
                             <div className={`w-16 h-16 rounded-full flex items-center justify-center mb-2 bg-[#f5f5f5] overflow-hidden shadow-sm border-2 ${isActive ? 'border-black' : 'border-transparent'}`}>
                                 {cat.thumb_image ? <img src={cat.thumb_image} className="object-cover w-full h-full mix-blend-multiply border border-gray-100 rounded-full" /> : <i className="fa-solid fa-tag"></i>}
                             </div>
                             <span className="text-[10px] font-bold uppercase tracking-widest text-center truncate w-full px-1">{cat.name}</span>
                        </div>
                    )})}
                </div>
            </div>

            {/* Product Grid */}
            <div className="max-w-[1400px] mx-auto px-6 lg:px-12 py-10">
                <div className="flex justify-between items-center mb-6">
                    <h1 className="text-2xl font-bold tracking-widest uppercase">{filteredCategory ? filteredCategory.name : 'All Products'}</h1>
                    <span className="text-sm font-medium text-gray-500">{filteredProducts.length} items</span>
                </div>

                {/* Sub-categories row */}
                {subCategoriesToDisplay.length > 0 && (
                    <div className="flex overflow-x-auto gap-3 hide-scrollbar mb-8 snap-x">
                        <button onClick={() => selectCategory(activeTopCategory.slug)} 
                            className={`snap-center shrink-0 px-4 py-2 rounded-full text-[11px] font-bold tracking-widest uppercase transition-all border ${filteredCategory.id === activeTopCategory.id ? 'bg-black text-white border-black' : 'bg-transparent text-gray-500 border-gray-200 hover:border-gray-400'}`}>
                            All {activeTopCategory.name}
                        </button>
                        {subCategoriesToDisplay.map(subCat => (
                            <button key={subCat.id} onClick={() => selectCategory(subCat.slug)}
                                className={`snap-center shrink-0 px-4 py-2 rounded-full text-[11px] font-bold tracking-widest uppercase transition-all border ${filteredCategory.id === subCat.id ? 'bg-black text-white border-black' : 'bg-transparent text-gray-500 border-gray-200 hover:border-gray-400'}`}>
                                {subCat.name}
                            </button>
                        ))}
                    </div>
                )}

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
                    {filteredProducts.map(prod => (
                        <div key={prod.id} className="text-center group flex flex-col h-full bg-white rounded-xl shadow-sm hover:shadow-xl transition-shadow border border-gray-100 overflow-hidden pb-4">
                            <div onClick={() => goToProduct(prod)} className="cursor-pointer bg-[#f7f7f7] relative w-full aspect-[4/5] flex items-center justify-center overflow-hidden">
                                {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-110 mix-blend-multiply" />
                                ) : (
                                    <i className="fa-solid fa-box text-4xl text-gray-300"></i>
                                )}
                            </div>
                            
                            <div className="px-4 pt-4 pb-2 cursor-pointer text-center" onClick={() => goToProduct(prod)}>
                                <h3 className="text-sm font-semibold text-gray-900 truncate">{prod.title}</h3>
                                <p className="text-sm font-bold text-gray-500 mt-1 mb-3">AED {parseFloat(prod.price).toFixed(2)}</p>
                                <a href={`https://wa.me/971551787454?text=${encodeURIComponent(`Hi, I am interested in ${prod.title}`)}`} target="_blank" className="inline-flex items-center space-x-1.5 bg-[#25D366] text-white px-4 py-1.5 rounded-full text-[11px] font-bold shadow-sm hover:bg-[#1ebe57] transition-colors" onClick={(e) => e.stopPropagation()}>
                                    <i className="fa-brands fa-whatsapp text-[14px]"></i>
                                    <span>Inquire</span>
                                </a>
                            </div>
                        </div>
                    ))}
                    {filteredProducts.length === 0 && <div className="col-span-full py-20 flex flex-col items-center justify-center text-gray-400"><i className="fa-solid fa-magnifying-glass text-4xl mb-4 opacity-50"></i><p>No products match your filters.</p></div>}
                </div>
            </div>

            {/* Fixed Bottom Brands Bar (Multi-select pill navigation) */}
            {availableBrands.length > 0 && (
                <div className="fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-md border-t border-gray-200 z-50 py-3 shadow-[0_-10px_40px_rgba(0,0,0,0.05)]">
                    <div className="max-w-[1400px] mx-auto flex overflow-x-auto gap-3 hide-scrollbar items-center px-4 snap-x">
                        <span className="text-[10px] font-bold uppercase tracking-widest text-gray-400 shrink-0 mr-1"><i className="fa-solid fa-filter mr-1"></i> Filter:</span>
                        {availableBrands.map(b => (
                            <button key={b.id} onClick={() => toggleBrand(b.slug)}
                                className={`snap-center shrink-0 px-5 py-2.5 rounded-full text-xs font-bold transition-all shadow-sm border ${brands && brands.includes(b.slug) ? 'bg-[#eb155b] text-white border-transparent shadow-lg shadow-[#eb155b]/30' : 'bg-gray-100 text-gray-600 border-gray-200 hover:bg-gray-200'}`}>
                                {b.name}
                            </button>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
}

function ProductDetail({ productId, setView }) {
    const [product, setProduct] = useState(null);
    const [loading, setLoading] = useState(true);
    const [activeImage, setActiveImage] = useState(0);

    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="min-h-screen flex items-center justify-center text-gray-500 animate-pulse">Loading Details...</div>;
    if (!product) return <div className="min-h-screen flex items-center justify-center">Product not found.</div>;

    const images = product.images || [];

    return (
        <div className="max-w-[1200px] mx-auto px-6 py-12 lg:py-20 animate-fade-in">
            {/* Top Breadcrumb */}
            <div className="text-xs text-gray-400 font-medium tracking-widest uppercase mb-10">
                <span className="cursor-pointer hover:text-black" onClick={() => setView('home')}>Home</span> 
                <span className="mx-2">/</span> 
                {product.category_name && <><span className="text-gray-800">{product.category_name}</span> <span className="mx-2">/</span></>} 
                <span className="text-gray-800">{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-lg overflow-hidden cursor-pointer border-2 transition-all ${activeImage === i ? 'border-black' : 'border-transparent opacity-60 hover:opacity-100'}`}>
                                <img src={img.image_url} className="w-full h-full object-cover mix-blend-multiply" alt="Thumb" />
                            </div>
                        ))}
                    </div>
                    <div className="w-full aspect-[4/5] bg-[#f7f7f7] rounded-2xl flex items-center justify-center overflow-hidden">
                        {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-gray-200"></i>
                        )}
                    </div>
                </div>

                {/* Info Section */}
                <div className="pt-2">
                    {product.brand_name && <p className="text-sm font-semibold tracking-widest uppercase text-gray-500 mb-2">{product.brand_name}</p>}
                    <h1 className="text-3xl lg:text-4xl font-bold text-gray-900 leading-tight mb-4">{product.title}</h1>
                    <p className="text-2xl font-bold text-gray-900 mb-8">AED {parseFloat(product.price).toFixed(2)}</p>

                    {/* Description HTML rendered safely */}
                    <div className="prose prose-sm lg:prose-base text-gray-600 mb-10 max-w-none" dangerouslySetInnerHTML={{__html: product.description}}></div>

                    <div className="pt-8 border-t border-gray-100 flex items-center space-x-4">
                        <a href={`https://wa.me/971551787454?text=${encodeURIComponent(`Hi, I am interested in buying ${product.title} (AED ${parseFloat(product.price).toFixed(2)}).`)}`} target="_blank" className="flex-1 bg-[#25D366] text-white py-4 rounded-xl flex items-center justify-center space-x-3 font-bold hover:bg-[#1ebe57] shadow-xl shadow-green-100 transition-all hover:-translate-y-1">
                            <i className="fa-brands fa-whatsapp text-2xl"></i>
                            <span className="text-sm tracking-wider uppercase">Inquire via WhatsApp</span>
                        </a>
                    </div>
                    
                    <div className="mt-10 bg-gray-50 p-6 rounded-xl flex items-start space-x-4">
                        <i className="fa-solid fa-truck-fast text-2xl text-gray-400 mt-1"></i>
                        <div>
                            <h4 className="font-bold text-sm text-gray-900 tracking-widest uppercase">Global Delivery</h4>
                            <p className="text-xs text-gray-500 mt-1">Securely tracked and fully insured shipping worldwide. Expected delivery times calculated upon inquiry.</p>
                        </div>
                    </div>

                    <div className="mt-4 bg-gray-50 p-6 rounded-xl flex items-start space-x-4">
                        <i className="fa-solid fa-money-bill-wave text-2xl text-gray-400 mt-1"></i>
                        <div>
                            <h4 className="font-bold text-sm text-gray-900 tracking-widest uppercase">Cash on Delivery</h4>
                            <p className="text-xs text-gray-500 mt-1">We offer Cash on Delivery (COD) services anywhere within the UAE.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

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

    // Dynamic Hash URL Routing
    useEffect(() => {
        const handleHashChange = () => {
            const hash = window.location.hash.replace('#', '');
            if (hash.startsWith('product/')) {
                const part = hash.replace('product/', '');
                const id = part.split('-')[0]; // Extract the ID before the dash
                setCurrentProductId(id);
                setView('product');
            } else if (hash.startsWith('shop')) {
                const urlParams = new URLSearchParams(hash.split('?')[1] || '');
                const cat = urlParams.get('category');
                const brs = urlParams.get('brands');
                setShopFilters({
                    category: cat || null,
                    brands: brs ? brs.split(',') : []
                });
                setView('shop');
            } else {
                setView('home');
            }
        };

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

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

    return (
        <div className="bg-white text-gray-900 antialiased font-poppins selection:bg-black selection:text-white">
            <style dangerouslySetInnerHTML={{__html: `
                .hide-scrollbar::-webkit-scrollbar { display: none; }
                .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
            `}} />
            <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>
            <Footer />
        </div>
    );
}

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