/**
 * Shared UI Components for Wellflow
 * Handles Header, Footer, and Common UI injection
 */

const Components = {
    /**
     * Injects the standard header into any element with id="main-header"
     */
    initHeader() {
        const headerContainer = document.getElementById('main-header');
        if (!headerContainer) return;

        const cartCount = this.getCartCount();

        headerContainer.innerHTML = `
            <nav class="fixed top-0 w-full z-50 bg-white/95 backdrop-blur-md border-b border-gray-100 shadow-sm">
                <div class="flex items-center justify-between px-4 h-16 max-w-7xl mx-auto">
                    <!-- Logo & Desktop Nav -->
                    <div class="flex items-center gap-8">
                        <a href="index.html" class="flex items-center gap-2 group">
                            <span class="text-2xl font-black text-primary italic tracking-tight transition-transform group-hover:scale-105">Wellflow</span>
                        </a>
                        
                        <nav class="hidden lg:flex items-center gap-6 text-[13px] font-bold text-gray-700 h-full relative z-[60]">
                            <!-- Medicines Dropdown -->
                            <div class="group relative h-full flex items-center">
                                <a class="nav-link flex items-center gap-1 hover:text-primary transition-colors py-5 border-b-2 border-transparent cursor-pointer" href="medicines.html">
                                    Medicine <span class="material-symbols-outlined text-sm text-gray-400 group-hover:text-primary">expand_more</span>
                                </a>
                                <div class="absolute top-[80%] -left-4 w-[280px] bg-white border border-gray-100 shadow-xl opacity-0 invisible group-hover:visible group-hover:opacity-100 transition-all duration-300 translate-y-2 group-hover:translate-y-0 rounded-b-lg pointer-events-none group-hover:pointer-events-auto">
                                    <div class="absolute -top-2 left-8 w-0 h-0 border-l-[10px] border-r-[10px] border-b-[10px] border-transparent border-b-[#7AC334]"></div>
                                    <div class="py-2 bg-white rounded-b-lg w-full">
                                        <!-- Items -->
                                        ${['Derma', 'Gastro-Intestinal Tract', 'Circulatory System', 'Others', 'Endocrine System', 'Eyes , Nose , Ear', 'Urinary Tract System', 'Central Nervous System', 'Respiratory Tract System', 'Cardio-Vascular System', 'Oral Care'].map(item => `
                                            <div class="group/sub relative">
                                                <a href="medicines.html" class="flex items-center justify-between px-5 py-2.5 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 border-b border-gray-50 last:border-0 transition-colors">
                                                    ${item} <span class="material-symbols-outlined text-[#7AC334] text-lg">chevron_right</span>
                                                </a>
                                                <div class="absolute top-0 left-full -ml-1 w-[220px] bg-white border border-gray-100 shadow-xl opacity-0 invisible group-hover/sub:visible group-hover/sub:opacity-100 transition-all duration-300 translate-x-3 group-hover/sub:translate-x-0 rounded-lg pointer-events-none group-hover/sub:pointer-events-auto z-50">
                                                    <div class="py-2 w-full">
                                                        <a href="products.html" class="flex items-center px-5 py-2 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 transition-colors">All ${item}</a>
                                                        <a href="products.html" class="flex items-center px-5 py-2 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 transition-colors">Top Brands</a>
                                                        <a href="products.html" class="flex items-center px-5 py-2 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 transition-colors">Prescription</a>
                                                    </div>
                                                </div>
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            </div>

                            <!-- Baby & Mother Care Dropdown -->
                            <div class="group relative h-full flex items-center">
                                <a class="nav-link flex items-center gap-1 hover:text-primary transition-colors py-5 border-b-2 border-transparent cursor-pointer" href="mother-baby.html">
                                    Baby & Mother Care <span class="material-symbols-outlined text-sm text-gray-400 group-hover:text-primary">expand_more</span>
                                </a>
                                <div class="absolute top-[80%] left-0 w-[240px] bg-white border border-gray-100 shadow-xl opacity-0 invisible group-hover:visible group-hover:opacity-100 transition-all duration-300 translate-y-2 group-hover:translate-y-0 rounded-b-lg pointer-events-none group-hover:pointer-events-auto">
                                    <div class="absolute -top-2 left-16 w-0 h-0 border-l-[10px] border-r-[10px] border-b-[10px] border-transparent border-b-[#7AC334]"></div>
                                    <div class="py-2 bg-white rounded-b-lg w-full">
                                        ${['Baby Diapers & Wipes', 'Baby Bath & Body', 'New Mommy Aids', 'Baby Food & Milk', 'Baby Appliances', 'Baby Essentials'].map(item => `
                                            <a href="mother-baby.html" class="flex items-center justify-between px-5 py-2.5 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 border-b border-gray-50 last:border-0 transition-colors">
                                                ${item}
                                            </a>
                                        `).join('')}
                                    </div>
                                </div>
                            </div>

                            <!-- Devices & Support Dropdown -->
                            <div class="group relative h-full flex items-center">
                                <a class="nav-link flex items-center gap-1 hover:text-primary transition-colors py-5 border-b-2 border-transparent cursor-pointer" href="devices.html">
                                    Devices & Support <span class="material-symbols-outlined text-sm text-gray-400 group-hover:text-primary">expand_more</span>
                                </a>
                                <div class="absolute top-[80%] left-0 w-[260px] bg-white border border-gray-100 shadow-xl opacity-0 invisible group-hover:visible group-hover:opacity-100 transition-all duration-300 translate-y-2 group-hover:translate-y-0 rounded-b-lg pointer-events-none group-hover:pointer-events-auto">
                                    <div class="absolute -top-2 left-14 w-0 h-0 border-l-[10px] border-r-[10px] border-b-[10px] border-transparent border-b-[#7AC334]"></div>
                                    <div class="py-2 bg-white rounded-b-lg w-full">
                                        ${['Cells & Batteries', 'Other Appliances', 'BP Monitors', 'Diabetes Apparatus', 'Supports & Braces', 'Mobility Equipments', 'Medicine Accessories', 'Thermometer', 'Steamers, Nebulizers & Vaporizers', 'Body Massagers', 'Weighing Scales'].map(item => `
                                            <a href="devices.html" class="flex items-center justify-between px-5 py-2.5 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 border-b border-gray-50 last:border-0 transition-colors">
                                                ${item}
                                            </a>
                                        `).join('')}
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Wellness Dropdown -->
                            <div class="group relative h-full flex items-center">
                                <a class="nav-link flex items-center gap-1 hover:text-primary transition-colors py-5 border-b-2 border-transparent cursor-pointer" href="wellness.html">
                                    Wellness <span class="material-symbols-outlined text-sm text-gray-400 group-hover:text-primary">expand_more</span>
                                </a>
                                <div class="absolute top-[80%] -left-8 w-[240px] bg-white border border-gray-100 shadow-xl opacity-0 invisible group-hover:visible group-hover:opacity-100 transition-all duration-300 translate-y-2 group-hover:translate-y-0 rounded-b-lg pointer-events-none group-hover:pointer-events-auto">
                                    <div class="absolute -top-2 left-14 w-0 h-0 border-l-[10px] border-r-[10px] border-b-[10px] border-transparent border-b-[#7AC334]"></div>
                                    <div class="py-2 bg-white rounded-b-lg w-full">
                                        ${[
                                            {name: 'Vitamins & Supplements', sub: true},
                                            {name: 'Immunity Boosters', sub: false},
                                            {name: 'Bone & Joint Health', sub: true},
                                            {name: 'Stress & Sleep Aids', sub: false},
                                            {name: 'Weight Management', sub: true},
                                            {name: 'Herbal Remedies', sub: false}
                                        ].map(item => `
                                            <div class="${item.sub ? 'group/sub relative' : ''}">
                                                <a href="wellness.html" class="flex items-center justify-between px-5 py-2.5 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 border-b border-gray-50 last:border-0 transition-colors">
                                                    ${item.name} ${item.sub ? '<span class="material-symbols-outlined text-[#7AC334] text-lg">chevron_right</span>' : ''}
                                                </a>
                                                ${item.sub ? `
                                                <div class="absolute top-0 left-full -ml-1 w-[220px] bg-white border border-gray-100 shadow-xl opacity-0 invisible group-hover/sub:visible group-hover/sub:opacity-100 transition-all duration-300 translate-x-3 group-hover/sub:translate-x-0 rounded-lg pointer-events-none group-hover/sub:pointer-events-auto z-50">
                                                    <div class="py-2 w-full">
                                                        <a href="products.html" class="flex items-center px-5 py-2 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 transition-colors">All ${item.name}</a>
                                                        <a href="products.html" class="flex items-center px-5 py-2 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 transition-colors">Premium Brands</a>
                                                    </div>
                                                </div>
                                                ` : ''}
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            </div>

                            <!-- Beauty Dropdown -->
                            <div class="group relative h-full flex items-center">
                                <a class="nav-link flex items-center gap-1 hover:text-primary transition-colors py-5 border-b-2 border-transparent cursor-pointer" href="beauty.html">
                                    Beauty <span class="material-symbols-outlined text-sm text-gray-400 group-hover:text-primary">expand_more</span>
                                </a>
                                <div class="absolute top-[80%] -left-12 w-[220px] bg-white border border-gray-100 shadow-xl opacity-0 invisible group-hover:visible group-hover:opacity-100 transition-all duration-300 translate-y-2 group-hover:translate-y-0 rounded-b-lg pointer-events-none group-hover:pointer-events-auto">
                                    <div class="absolute -top-2 left-16 w-0 h-0 border-l-[10px] border-r-[10px] border-b-[10px] border-transparent border-b-[#7AC334]"></div>
                                    <div class="py-2 bg-white rounded-b-lg w-full">
                                        ${[
                                            {name: 'Clinical Skincare', sub: true},
                                            {name: 'Acne Treatments', sub: false},
                                            {name: 'Anti-Aging Serums', sub: true},
                                            {name: 'Sun Protection', sub: false},
                                            {name: 'Hair Growth Solutions', sub: true}
                                        ].map(item => `
                                            <div class="${item.sub ? 'group/sub relative' : ''}">
                                                <a href="beauty.html" class="flex items-center justify-between px-5 py-2.5 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 border-b border-gray-50 last:border-0 transition-colors">
                                                    ${item.name} ${item.sub ? '<span class="material-symbols-outlined text-[#7AC334] text-lg">chevron_right</span>' : ''}
                                                </a>
                                                ${item.sub ? `
                                                <div class="absolute top-0 left-full -ml-1 w-[220px] bg-white border border-gray-100 shadow-xl opacity-0 invisible group-hover/sub:visible group-hover/sub:opacity-100 transition-all duration-300 translate-x-3 group-hover/sub:translate-x-0 rounded-lg pointer-events-none group-hover/sub:pointer-events-auto z-50">
                                                    <div class="py-2 w-full">
                                                        <a href="products.html" class="flex items-center px-5 py-2 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 transition-colors">All ${item.name}</a>
                                                        <a href="products.html" class="flex items-center px-5 py-2 text-sm text-gray-800 hover:text-[#7AC334] hover:bg-gray-50 transition-colors">Top Products</a>
                                                    </div>
                                                </div>
                                                ` : ''}
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            </div>
                        </nav>
                    </div>

                    <!-- Search & Actions -->
                    <div class="flex items-center gap-4">
                        <!-- Desktop Search -->
                        <div class="hidden md:flex items-center bg-gray-100 rounded-full px-4 py-1.5 w-64 focus-within:ring-1 focus-within:ring-primary/40 focus-within:bg-white border border-transparent focus-within:border-gray-200 transition-all">
                            <input id="global-search" class="bg-transparent border-none focus:ring-0 text-xs w-full placeholder:text-gray-500" placeholder="Search medicines..." type="text">
                            <span class="material-symbols-outlined text-gray-400 text-sm cursor-pointer hover:text-primary">search</span>
                        </div>

                        <div class="flex items-center gap-3">
                             <a href="login.html" class="flex flex-col items-center gap-0.5 text-gray-600 hover:text-primary transition-all">
                                <span class="material-symbols-outlined text-[20px]">person</span>
                                <span class="text-[9px] font-black uppercase tracking-tighter">Login</span>
                            </a>

                            <a href="favourite.html" class="relative group flex flex-col items-center gap-0.5 text-gray-600 hover:text-primary transition-all">
                                <span class="material-symbols-outlined text-[20px]">favorite</span>
                                <span class="text-[9px] font-black uppercase tracking-tighter">Wishlist</span>
                                <span id="favourite-badge" class="absolute -top-1 -right-1 bg-primary text-white text-[9px] font-bold w-4 h-4 flex items-center justify-center rounded-full border-2 border-white transition-transform group-hover:scale-110">${this.getFavouriteCount()}</span>
                            </a>
                            
                            <div class="relative flex flex-col items-center gap-0.5 text-gray-600 hover:text-primary transition-all cursor-pointer" id="cart-trigger" onclick="UI.toggleCart()">
                                <span class="material-symbols-outlined text-[20px]">shopping_cart</span>
                                <span class="text-[9px] font-black uppercase tracking-tighter">Cart</span>
                                <span id="cart-badge" class="absolute -top-1 -right-1 bg-tertiary text-white text-[9px] font-bold w-4 h-4 flex items-center justify-center rounded-full border-2 border-white transition-transform">0</span>
                                
                                <!-- Cart Preview Dropdown -->
                                <div id="cart-dropdown" class="absolute top-full right-0 mt-2 w-72 bg-white rounded-xl shadow-2xl border border-gray-100 opacity-0 invisible transition-all duration-300 translate-y-2 z-[60]">
                                    <div class="p-4">
                                        <h4 class="text-sm font-black text-gray-800 mb-3 uppercase tracking-wide">Your Cart</h4>
                                        <div id="cart-preview-items" class="max-h-60 overflow-y-auto space-y-3 custom-scrollbar">
                                            <!-- Items injected via JS -->
                                            <p class="text-[11px] text-gray-500 text-center py-4">Loading cart...</p>
                                        </div>
                                        <div class="mt-4 pt-3 border-t border-gray-100">
                                            <div class="flex justify-between mb-3">
                                                <span class="text-xs font-bold text-gray-500">Total</span>
                                                <span id="cart-preview-total" class="text-sm font-black text-primary">Rs. 0.00</span>
                                            </div>
                                            <button onclick="window.location.href='checkout.html'" class="w-full bg-primary text-white py-2 rounded-lg text-xs font-bold hover:opacity-90 transition-all active:scale-[0.98]">Checkout Now</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Mobile Menu Toggle -->
                            <button class="lg:hidden text-gray-600 hover:text-primary" id="mobile-menu-toggle">
                                <span class="material-symbols-outlined text-2xl">menu</span>
                            </button>
                        </div>
                    </div>
                </div>
            </nav>

            <!-- Mobile Navigation Drawer -->
            <div id="mobile-nav" class="fixed inset-0 z-[100] invisible pointer-events-none transition-all duration-300">
                <div id="mobile-nav-overlay" class="absolute inset-0 bg-black/40 opacity-0 transition-opacity duration-300"></div>
                <div id="mobile-nav-content" class="absolute top-0 right-0 h-full w-4/5 max-w-[300px] bg-white translate-x-full transition-transform duration-300 shadow-2xl flex flex-col">
                    <div class="p-6 border-b border-gray-100 flex items-center justify-between">
                        <span class="text-xl font-black text-primary italic">Wellflow</span>
                        <button id="mobile-nav-close" class="text-gray-400 hover:text-primary transition-colors">
                            <span class="material-symbols-outlined text-2xl">close</span>
                        </button>
                    </div>
                    <div class="flex-1 overflow-y-auto p-6 space-y-6">
                        <div class="space-y-4">
                            <h4 class="text-[11px] font-black text-gray-400 uppercase tracking-widest">Shop Categories</h4>
                            <nav class="flex flex-col gap-4">
                                <a class="text-lg font-bold text-gray-800 hover:text-primary transition-colors" href="medicines.html">Medicines</a>
                                <a class="text-lg font-bold text-gray-800 hover:text-primary transition-colors" href="wellness.html">Wellness</a>
                                <a class="text-lg font-bold text-gray-800 hover:text-primary transition-colors" href="beauty.html">Beauty</a>
                                <a class="text-lg font-bold text-gray-800 hover:text-primary transition-colors" href="devices.html">Devices</a>
                                <a class="text-lg font-bold text-gray-800 hover:text-primary transition-colors" href="mother-baby.html">Mother & Baby</a>
                            </nav>
                        </div>
                        <div class="pt-6 border-t border-gray-100 space-y-4">
                             <a href="login.html" class="flex items-center gap-3 text-gray-800 font-bold hover:text-primary transition-colors">
                                <span class="material-symbols-outlined">person</span>
                                Login / Register
                            </a>
                        </div>
                    </div>
                    <div class="p-6 bg-gray-50 border-t border-gray-100">
                        <p class="text-[10px] text-gray-400 text-center font-bold uppercase tracking-widest">© 2024 Wellflow Clinical</p>
                    </div>
                </div>
            </div>
        `;

        this.highlightActiveLink();
        this.initSearch();
        this.initMobileNav();
        this.updateCartPreview();
        this.updateFavouritePreview();
    },

    /**
     * Injects the standard footer into any element with id="main-footer"
     */
    initFooter() {
        const footerContainer = document.getElementById('main-footer');
        if (!footerContainer) return;

        footerContainer.innerHTML = `
            <footer class="bg-white border-t border-gray-100 mt-20">
                <div class="max-w-7xl mx-auto px-4 py-16 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-12">
                    <div class="space-y-6">
                        <a href="index.html" class="inline-block">
                            <span class="text-2xl font-black text-primary italic">Wellflow</span>
                        </a>
                        <p class="text-gray-500 text-sm leading-relaxed max-w-xs">
                            The Clinical Authority in Wellness. Providing trusted medical and healthcare solutions directly to your doorstep with expert oversight.
                        </p>
                        <div class="flex gap-4">
                            <a href="#" class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-primary/10 hover:text-primary transition-all">
                                <span class="material-symbols-outlined text-[18px]">verified_user</span>
                            </a>
                            <a href="#" class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-primary/10 hover:text-primary transition-all">
                                <span class="material-symbols-outlined text-[18px]">public</span>
                            </a>
                        </div>
                    </div>

                    <div>
                        <h4 class="text-[11px] font-black uppercase tracking-widest text-gray-800 mb-6">Customer Care</h4>
                        <ul class="space-y-3 text-[13px] font-semibold text-gray-500">
                            <li><a href="#" class="hover:text-primary transition-colors">Help Center</a></li>
                            <li><a href="#" class="hover:text-primary transition-colors">Shipping & Delivery</a></li>
                            <li><a href="#" class="hover:text-primary transition-colors">Returns & Refunds</a></li>
                            <li><a href="#" class="hover:text-primary transition-colors">Track Order</a></li>
                        </ul>
                    </div>

                    <div>
                        <h4 class="text-[11px] font-black uppercase tracking-widest text-gray-800 mb-6">Quick Links</h4>
                        <ul class="space-y-3 text-[13px] font-semibold text-gray-500">
                            <li><a href="medicines.html" class="hover:text-primary transition-colors">Medicines</a></li>
                            <li><a href="wellness.html" class="hover:text-primary transition-colors">Wellness Products</a></li>
                            <li><a href="beauty.html" class="hover:text-primary transition-colors">Dermatological Care</a></li>
                            <li><a href="devices.html" class="hover:text-primary transition-colors">Medical Devices</a></li>
                        </ul>
                    </div>

                    <div>
                        <h4 class="text-[11px] font-black uppercase tracking-widest text-gray-800 mb-6">Join Community</h4>
                        <p class="text-xs text-gray-500 mb-4 font-medium">Get expert advice and exclusive health offers.</p>
                        <div class="flex flex-col gap-2">
                            <input class="bg-gray-50 border border-gray-100 rounded-lg px-4 py-2 text-xs focus:bg-white focus:ring-1 focus:ring-primary/40 focus:border-primary/40 outline-none transition-all" placeholder="Enter your email" type="email">
                            <button class="bg-primary text-white py-2 rounded-lg text-xs font-bold hover:brightness-95 transition-all active:scale-[0.98]">Subscribe</button>
                        </div>
                    </div>
                </div>
                <div class="border-t border-gray-100 py-8 text-center bg-gray-50/50">
                    <p class="text-gray-400 text-[10px] font-black uppercase tracking-[0.2em]">© 2024 WELLFLOW CLINICAL. ALL RIGHTS RESERVED.</p>
                </div>
            </footer>
        `;
    },

    /**
     * Initializes the Mobile Navigation Drawer logic as per standardization guide
     */
    initMobileNav() {
        const toggle = document.getElementById('mobile-menu-toggle');
        const close = document.getElementById('mobile-nav-close');
        const overlay = document.getElementById('mobile-nav-overlay');
        const drawer = document.getElementById('mobile-nav');
        const content = document.getElementById('mobile-nav-content');

        const openNav = () => {
            drawer.classList.remove('invisible');
            drawer.classList.add('pointer-events-auto');
            overlay.classList.add('opacity-100');
            content.classList.remove('translate-x-full');
            document.body.style.overflow = 'hidden';
        };

        const closeNav = () => {
             content.classList.add('translate-x-full');
             overlay.classList.remove('opacity-100');
             setTimeout(() => {
                drawer.classList.add('invisible');
                drawer.classList.remove('pointer-events-auto');
                document.body.style.overflow = '';
             }, 300);
        };

        if (toggle) toggle.onclick = openNav;
        if (close) close.onclick = closeNav;
        if (overlay) overlay.onclick = closeNav;
    },

    /**
     * Highlights the current active navigation link
     */
    highlightActiveLink() {
        const path = window.location.pathname.split('/').pop() || 'index.html';
        const links = document.querySelectorAll('.nav-link');
        links.forEach(link => {
            if (link.getAttribute('href') === path) {
                link.classList.add('text-primary', 'border-primary');
                link.classList.remove('text-gray-700', 'border-transparent');
            }
        });
    },

    /**
     * Search functionality logic
     */
    initSearch() {
        const searchInput = document.getElementById('global-search');
        if (!searchInput) return;

        searchInput.onkeypress = (e) => {
            if (e.key === 'Enter') {
                const query = searchInput.value.trim();
                if (query) {
                    window.location.href = `products.html?search=${encodeURIComponent(query)}`;
                }
            }
        };
    },

    /**
     * Cart Data Management
     */
    getCartCount() {
        const cartStr = localStorage.getItem('wellflow-cart');
        if (!cartStr) return 0;
        try {
            const cart = JSON.parse(cartStr);
            return cart.reduce((acc, item) => acc + (parseInt(item.quantity) || 0), 0);
        } catch(e) { return 0; }
    },

    updateCartPreview() {
        const cart = JSON.parse(localStorage.getItem('wellflow-cart') || '[]');
        const container = document.getElementById('cart-preview-items');
        const totalEl = document.getElementById('cart-preview-total');
        const badge = document.getElementById('cart-badge');

        if (!container) return;

        if (cart.length === 0) {
            container.innerHTML = '<p class="text-[11px] text-gray-500 text-center py-6">Your cart is empty.</p>';
            totalEl.innerText = 'Rs. 0.00';
            if (badge) badge.innerText = '0';
            return;
        }

        let total = 0;
        let count = 0;
        container.innerHTML = cart.map(item => {
            const itemQty = parseInt(item.quantity) || 0;
            const itemPrice = parseFloat(item.price) || 0;
            total += itemPrice * itemQty;
            count += itemQty;
            return `
                <div class="flex gap-3 items-center group/item">
                    <picture>
                        <source srcset="${item.image.replace('assets/', 'optimized/resized/')}" type="image/webp">
                        <img src="${item.image}" class="w-10 h-10 object-contain bg-gray-50 rounded p-1" loading="lazy">
                    </picture>
                    <div class="flex-1 min-w-0">
                        <h5 class="text-[11px] font-bold text-gray-800 truncate">${item.name}</h5>
                        <p class="text-[9px] text-gray-500">${itemQty} x Rs. ${itemPrice.toFixed(2)}</p>
                    </div>
                    <button onclick="Cart.removeItem(${item.id})" class="text-gray-300 hover:text-tertiary transition-colors">
                        <span class="material-symbols-outlined text-sm">close</span>
                    </button>
                </div>
            `;
        }).join('');

        totalEl.innerText = `Rs. ${total.toFixed(2)}`;
        if (badge) badge.innerText = count;
    },

    getFavouriteCount() {
        const favsStr = localStorage.getItem('wellflow-favourites');
        if (!favsStr) return 0;
        try {
            const favs = JSON.parse(favsStr);
            return favs.length;
        } catch(e) { return 0; }
    },

    updateFavouritePreview() {
        const badge = document.getElementById('favourite-badge');
        if (badge) {
            badge.innerText = this.getFavouriteCount();
        }
    },

    /**
     * Toast Notification System
     */
    showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `fixed bottom-6 left-1/2 -translate-x-1/2 z-[200] px-6 py-3 rounded-xl shadow-2xl flex items-center gap-3 animate-slide-up bg-white border border-gray-100 min-w-[280px]`;
        
        const icon = type === 'success' ? 'check_circle' : 'error';
        const color = type === 'success' ? 'text-primary' : 'text-tertiary';

        toast.innerHTML = `
            <span class="material-symbols-outlined ${color} text-xl">${icon}</span>
            <span class="text-xs font-black text-gray-800 uppercase tracking-wide">${message}</span>
        `;

        document.body.appendChild(toast);
        setTimeout(() => {
            toast.classList.add('opacity-0', '-translate-y-2');
            setTimeout(() => toast.remove(), 400);
        }, 2500);
    },

    /**
     * Quick View Modal
     */
    openQuickView(productId) {
        const product = productsData.find(p => p.id === productId);
        if (!product) return;

        const modalOverlay = document.createElement('div');
        modalOverlay.id = 'quick-view-modal';
        modalOverlay.className = 'fixed inset-0 z-[150] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 animate-fade-in';
        
        modalOverlay.innerHTML = `
            <div class="bg-white w-full max-w-4xl rounded-2xl shadow-3xl overflow-hidden relative animate-scale-up flex flex-col md:flex-row max-h-[90vh]">
                <button onclick="document.getElementById('quick-view-modal').remove()" class="absolute top-4 right-4 z-20 w-8 h-8 bg-white/80 backdrop-blur rounded-full flex items-center justify-center text-gray-800 hover:scale-110 transition-all border border-gray-100">
                    <span class="material-symbols-outlined text-xl">close</span>
                </button>
                
                <div class="w-full md:w-1/2 bg-gray-50 flex items-center justify-center p-8">
                    <img src="${product.image}" class="max-h-full max-w-full object-contain">
                </div>
                
                <div class="w-full md:w-1/2 p-8 md:p-12 overflow-y-auto">
                    <span class="text-[10px] font-black text-primary uppercase tracking-widest mb-2 block">${product.brand}</span>
                    <h2 class="text-2xl font-black text-gray-900 leading-tight mb-4">${product.name}</h2>
                    
                    <div class="flex items-center gap-3 mb-6">
                        <span class="text-3xl font-black text-primary">Rs. ${product.price.toFixed(2)}</span>
                        ${product.oldPrice ? `<span class="text-lg text-gray-400 line-through font-bold">Rs. ${product.oldPrice.toFixed(2)}</span>` : ''}
                        ${product.discount ? `<span class="bg-tertiary/10 text-tertiary text-[10px] font-black px-2 py-0.5 rounded tracking-tighter">SAVE ${product.discount}%</span>` : ''}
                    </div>
                    
                    <p class="text-gray-500 text-sm leading-relaxed mb-8 font-medium">
                        ${product.description}
                    </p>
                    
                    <div class="space-y-4">
                        <div class="flex items-center gap-4">
                            <div class="flex items-center border border-gray-200 rounded-lg overflow-hidden">
                                <button onclick="this.nextElementSibling.innerText = Math.max(1, parseInt(this.nextElementSibling.innerText) - 1)" class="px-3 py-2 hover:bg-gray-50 transition-colors">
                                    <span class="material-symbols-outlined text-sm">remove</span>
                                </button>
                                <span class="px-4 py-2 text-xs font-black min-w-[40px] text-center border-x border-gray-200" id="qv-qty">1</span>
                                <button onclick="this.previousElementSibling.innerText = parseInt(this.previousElementSibling.innerText) + 1" class="px-3 py-2 hover:bg-gray-50 transition-colors">
                                    <span class="material-symbols-outlined text-sm">add</span>
                                </button>
                            </div>
                            <button onclick="Cart.addItem(${product.id}, parseInt(document.getElementById('qv-qty').innerText)); document.getElementById('quick-view-modal').remove()" class="btn-pro-wellflow flex-1 py-3 text-[11px]">
                                <span class="btn-text">Add to Cart</span>
                                <svg class="btn-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"></path><line x1="3" y1="6" x2="21" y2="6"></line><path d="M16 10a4 4 0 0 1-8 0"></path></svg>
                            </button>
                        </div>
                        <button onclick="window.location.href='product-detail.html?id=${product.id}'" class="btn-pro-wellflow w-full py-2.5 text-[9px] border-none shadow-none bg-gray-50 hover:bg-primary">
                            <span class="btn-text">View Full Details</span>
                            <svg class="btn-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
                        </button>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(modalOverlay);
        modalOverlay.onclick = (e) => { if (e.target === modalOverlay) modalOverlay.remove(); };
    }
};

/**
 * GLOBAL UI CONTROLLER (Extended)
 */
window.UI = {
    ...window.UI,
    toggleCart() {
        const dropdown = document.getElementById('cart-dropdown');
        if (!dropdown) return;
        dropdown.classList.toggle('opacity-0');
        dropdown.classList.toggle('invisible');
        dropdown.classList.toggle('translate-y-0');
    },

    applyCoupon() {
        const input = document.getElementById('coupon-input');
        if (!input || !input.value.trim()) {
            Components.showToast('Please enter a clinical coupon code', 'error');
            return;
        }
        Components.showToast(`Coupon "${input.value.toUpperCase()}" applied successfully!`, 'success');
        input.value = '';
    }
};

window.Components = Components;
