/**
 * Main Logic for Wellflow E-commerce
 */

document.addEventListener('DOMContentLoaded', () => {
    // Inject Components
    Components.initHeader();
    Components.initFooter();
    UI.initFlashSaleTimer();
    UI.initScrollAnimations();
    
    // Init Carousel if available
    if(typeof HeroCarousel !== 'undefined') HeroCarousel.init();
    if(typeof CategoryCarousel !== 'undefined') CategoryCarousel.init();

    // Check for Search/Category in URL
    const urlParams = new URLSearchParams(window.location.search);
    const searchQuery = urlParams.get('search');
    const categoryQuery = urlParams.get('category') || window.location.pathname.split('/').pop().replace('.html', '');

    // Global Catalog Grid (products.html)
    if (document.getElementById('product-grid')) {
        FilterSystem.init();
        
        let filtered = productsData;

        // Apply URL Search
        if (searchQuery) {
            filtered = filtered.filter(p => 
                p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                p.brand.toLowerCase().includes(searchQuery.toLowerCase())
            );
            const searchTitle = document.getElementById('category-title');
            if (searchTitle) searchTitle.innerText = `Search Results: "${searchQuery}"`;
        } 
        // Apply URL Category
        else if (['medicines', 'wellness', 'beauty', 'devices', 'mother-baby'].includes(categoryQuery)) {
            filtered = filtered.filter(p => p.category === categoryQuery);
            const catTitle = document.getElementById('category-title');
            if (catTitle) catTitle.innerHTML = `${categoryQuery.replace('-', ' & ').charAt(0).toUpperCase() + categoryQuery.replace('-', ' & ').slice(1)} <span class="text-[11px] font-bold text-gray-400 uppercase tracking-widest mt-1" id="product-count">(${filtered.length} items found)</span>`;
        } else {
            const catTitle = document.getElementById('product-count');
            if (catTitle) catTitle.innerText = `(${filtered.length} items discovered)`;
        }

        ProductRenderer.render('product-grid', filtered);
    }
    
    // Homepage Independent Sliders
    if (document.getElementById('flash-sales-grid')) {
        ProductRenderer.render('flash-sales-grid', productsData.filter(p => p.discount));
    }
    if (document.getElementById('top-selling-grid')) {
        ProductRenderer.render('top-selling-grid', productsData.filter(p => p.bestseller));
    }
    
    if (window.location.pathname.includes('product-detail.html')) {
        ProductDetail.init();
    }

    if (window.location.pathname.includes('favourite.html')) {
        FavouritePage.init();
    }
});

/**
 * FILTERING SYSTEM
 */
const FilterSystem = {
    activeConcerns: [],
    
    init() {
        // Listeners for manual input
        const minInput = document.getElementById('price-min');
        const maxInput = document.getElementById('price-max');
        if (minInput) minInput.oninput = () => this.apply();
        if (maxInput) maxInput.oninput = () => this.apply();
        
        // Initial count update
        this.apply();
    },

    toggleConcern(concern, btn) {
        const index = this.activeConcerns.indexOf(concern);
        if (index > -1) {
            this.activeConcerns.splice(index, 1);
            btn.classList.remove('border-primary/40', 'bg-primary/5', 'shadow-xl', 'shadow-primary/5');
            btn.classList.add('border-gray-100');
        } else {
            this.activeConcerns.push(concern);
            btn.classList.add('border-primary/40', 'bg-primary/5', 'shadow-xl', 'shadow-primary/5');
            btn.classList.remove('border-gray-100');
        }
        this.apply();
    },

    apply() {
        const minPrice = parseFloat(document.getElementById('price-min')?.value) || 0;
        const maxPrice = parseFloat(document.getElementById('price-max')?.value) || Infinity;
        
        const selectedBrands = Array.from(document.querySelectorAll('input[name="brand"]:checked')).map(cb => cb.value);

        let filtered = productsData;

        // 1. Category check (from URL/filename)
        const categoryQuery = window.location.pathname.split('/').pop().replace('.html', '');
        if (['medicines', 'wellness', 'beauty', 'devices', 'mother-baby'].includes(categoryQuery)) {
            filtered = filtered.filter(p => p.category === categoryQuery);
        }

        // 2. Price filter
        filtered = filtered.filter(p => p.price >= minPrice && p.price <= maxPrice);

        // 3. Brand filter
        if (selectedBrands.length > 0) {
            filtered = filtered.filter(p => selectedBrands.includes(p.brand));
        }

        // 4. Concern filter
        if (this.activeConcerns.length > 0) {
            filtered = filtered.filter(p => 
                p.concerns && p.concerns.some(c => this.activeConcerns.includes(c))
            );
        }

        ProductRenderer.render('product-grid', filtered);
        
        const countDisplay = document.getElementById('product-count');
        if (countDisplay) countDisplay.innerText = `(${filtered.length} medical items discovered)`;
    }
};

/**
 * PRODUCT RENDERER (High-End Clinical)
 */
const ProductRenderer = {
    render(containerId, products) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        if (products.length === 0) {
            container.innerHTML = `
                <div class="col-span-full py-20 text-center animate-fade-in bg-white rounded-3xl border border-dashed border-gray-100">
                    <span class="material-symbols-outlined text-5xl text-gray-200 mb-4 animate-pulse">clinical_notes</span>
                    <p class="text-gray-400 font-black uppercase tracking-widest text-[10px]">No medical records found match your criteria</p>
                </div>
            `;
            return;
        }

        container.innerHTML = products.map(product => `
            <div class="group bg-white rounded-3xl border border-gray-50 p-4 transition-all duration-500 hover:shadow-2xl hover:shadow-primary/5 flex flex-col animate-fade-in relative">
                <!-- Badges -->
                <div class="absolute top-6 left-6 z-10 flex flex-col gap-1.5 pointer-events-none">
                    ${product.discount ? `<span class="bg-tertiary text-white text-[10px] font-black px-2.5 py-1 rounded-lg">-${product.discount}% OFF</span>` : ''}
                    ${product.bestseller ? `<span class="bg-gray-900 text-white text-[10px] font-black px-2.5 py-1 rounded-lg">RECOMMENDED</span>` : ''}
                </div>

                <!-- Favorite Button -->
                <button onclick="UI.toggleFavorite(this, ${product.id})" class="absolute top-6 right-6 z-10 w-9 h-9 bg-white/80 backdrop-blur rounded-full border border-gray-100 flex items-center justify-center text-gray-400 hover:text-tertiary transition-all active:scale-90 shadow-xl shadow-black/5">
                    <span class="material-symbols-outlined text-xl ${Favourite.isFavorited(product.id) ? 'fill-current text-tertiary text-[20px] !important' : 'text-[20px]'}">favorite</span>
                </button>

                <!-- Image Area -->
                <div class="relative aspect-square bg-gray-50 rounded-2xl mb-5 overflow-hidden flex items-center justify-center p-8">
                    <img src="${product.image}" class="w-full h-full object-contain transition-transform duration-700 group-hover:scale-110" alt="${product.name}">
                    
                    <!-- Hover Effect: View Details Button Overlay -->
                    <div class="absolute inset-0 bg-primary/20 opacity-0 group-hover:opacity-100 transition-all duration-500 flex flex-col items-center justify-center gap-3 p-6 backdrop-blur-[2px]">
                        <button onclick="window.location.href='product-detail.html?id=${product.id}'" class="w-full bg-white text-gray-900 py-3.5 rounded-xl text-[11px] font-black uppercase tracking-widest shadow-2xl translate-y-4 opacity-0 group-hover:translate-y-0 group-hover:opacity-100 transition-all duration-500 active:scale-95">Full Details</button>
                        <button onclick="Components.openQuickView(${product.id})" class="w-full bg-primary text-white py-3.5 rounded-xl text-[11px] font-black uppercase tracking-widest shadow-2xl translate-y-4 opacity-0 group-hover:translate-y-0 group-hover:opacity-100 transition-all duration-500 delay-100 active:scale-95">Quick Actions</button>
                    </div>
                </div>

                <!-- Content Area -->
                <div class="flex flex-col flex-1 px-1">
                    <span class="text-[10px] font-black text-primary uppercase tracking-widest mb-1 shadow-sm px-2 py-0.5 bg-primary/5 rounded inline-block w-fit">${product.brand}</span>
                    <h3 class="text-sm font-black text-gray-900 leading-tight mb-3 line-clamp-2 h-10 group-hover:text-primary transition-colors cursor-pointer" onclick="window.location.href='product-detail.html?id=${product.id}'">${product.name}</h3>
                    
                    <div class="mt-auto pt-4 border-t border-gray-50 flex items-center justify-between">
                        <div class="flex flex-col">
                            <span class="text-lg font-black text-gray-900">Rs. ${product.price.toFixed(2)}</span>
                            ${product.oldPrice ? `<span class="text-[11px] text-gray-400 line-through font-bold">Rs. ${product.oldPrice.toFixed(2)}</span>` : ''}
                        </div>
                        <button onclick="Cart.addItem(${product.id})" class="w-12 h-12 bg-gray-900 rounded-xl flex items-center justify-center text-white hover:bg-primary transition-all active:scale-90 shadow-xl shadow-black/5">
                            <span class="material-symbols-outlined text-[20px]">add_shopping_cart</span>
                        </button>
                    </div>
                </div>
            </div>
        `).join('');
    }
};

/**
 * PRODUCT DETAIL LOGIC
 */
const ProductDetail = {
    init() {
        const urlParams = new URLSearchParams(window.location.search);
        const productId = parseInt(urlParams.get('id'));
        if (!productId) return;

        const product = productsData.find(p => p.id === productId);
        if (!product) {
            this.renderNotFound();
            return;
        }
        this.render(product);
    },
    render(product) {
        document.getElementById('product-brand').innerText = product.brand;
        document.getElementById('product-name').innerText = product.name;
        document.getElementById('product-price').innerText = `Rs. ${product.price.toFixed(2)}`;
        document.getElementById('main-product-image').src = product.image;
        document.getElementById('product-description').innerText = product.description;
        document.getElementById('product-detailed-specs').innerText = product.details;
        document.getElementById('product-technical-specs').innerText = product.specs;
        document.getElementById('product-shipping-info').innerText = product.shipping;
        document.getElementById('breadcrumb-current-product').innerText = product.name;
        
        const catLink = document.getElementById('breadcrumb-category-link');
        if (catLink) {
            catLink.innerText = product.category;
            catLink.href = `${product.category}.html`;
        }
        
        const addBtn = document.getElementById('add-to-cart-btn');
        if (addBtn) {
            addBtn.onclick = () => Cart.addItem(product.id, 1);
        }

        const exploreBtn = document.getElementById('explore-similar-btn');
        if (exploreBtn) exploreBtn.onclick = () => window.location.href = `${product.category}.html`;

        const favBtn = document.querySelector('[onclick="UI.toggleFavorite(this)"]');
        if (favBtn) {
            favBtn.onclick = () => UI.toggleFavorite(favBtn, product.id);
            if (Favourite.isFavorited(product.id)) {
                favBtn.querySelector('span').classList.add('fill-current', 'text-tertiary');
            }
        }
        initZoom('#main-product-image', '#product-zoom');
    },
    renderNotFound() {
        const container = document.getElementById('product-detail-container');
        if (container) {
            container.innerHTML = `<div class="py-40 text-center"><h2 class="text-3xl font-black text-gray-900 mb-4">DATA ARCHIVE NOT FOUND</h2><a href="index.html" class="bg-primary text-white px-10 py-4 rounded-2xl font-black text-xs uppercase tracking-widest hover:brightness-105 transition-all shadow-2xl shadow-primary/20">Return to Pharmacopeia</a></div>`;
        }
    }
};

/**
 * FAQS & FAVOURITES
 */
const FavouritePage = {
    init() {
        const favItems = Favourite.getItems();
        ProductRenderer.render('favourite-grid', favItems);
    }
};

/**
 * CART SYSTEM
 */
const Cart = {
    addItem(productId, quantity = 1) {
        const product = productsData.find(p => p.id === productId);
        if (!product) return;
        let cart = JSON.parse(localStorage.getItem('wellflow-cart') || '[]');
        const existing = cart.find(item => item.id === productId);
        if (existing) {
            existing.quantity += quantity;
        } else {
            cart.push({ ...product, quantity });
        }
        localStorage.setItem('wellflow-cart', JSON.stringify(cart));
        Components.updateCartPreview();
        Components.showToast('Item Logged in Prescription Cart', 'success');
    },
    removeItem(productId) {
        let cart = JSON.parse(localStorage.getItem('wellflow-cart') || '[]');
        cart = cart.filter(item => item.id !== productId);
        localStorage.setItem('wellflow-cart', JSON.stringify(cart));
        Components.updateCartPreview();
        Components.showToast('Item Removed from Archive', 'error');
    }
};

/**
 * FAVOURITE SYSTEM
 */
const Favourite = {
    getItems() { return JSON.parse(localStorage.getItem('wellflow-favourites') || '[]'); },
    toggle(productId) {
        const product = productsData.find(p => p.id === productId);
        let favs = this.getItems();
        const index = favs.findIndex(p => p.id === productId);
        if (index > -1) {
            favs.splice(index, 1);
            localStorage.setItem('wellflow-favourites', JSON.stringify(favs));
            return false;
        } else {
            favs.push(product);
            localStorage.setItem('wellflow-favourites', JSON.stringify(favs));
            return true;
        }
    },
    isFavorited(productId) { return this.getItems().some(p => p.id === productId); }
};

/**
 * GLOBAL UI CONTROLLER (Extended)
 */
const UI = {
    ...window.UI,
    initFlashSaleTimer() {
        const updateDisplay = () => {
            const now = new Date();
            const tomorrow = new Date(now);
            tomorrow.setHours(24, 0, 0, 0);
            const diff = tomorrow.getTime() - now.getTime();
            const h = Math.floor(diff / (1000 * 60 * 60));
            const m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
            const s = Math.floor((diff % (1000 * 60)) / 1000);
            const display = `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
            document.querySelectorAll('.flash-sale-timer').forEach(el => el.innerText = display);
        };
        setInterval(updateDisplay, 1000);
        updateDisplay();
    },
    initScrollAnimations() {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animate-slide-up');
                    observer.unobserve(entry.target);
                }
            });
        }, { threshold: 0.1 });
        document.querySelectorAll('.scroll-reveal').forEach(el => observer.observe(el));
    },
    toggleFavorite(btn, productId) {
        const icon = btn.querySelector('span');
        const isFav = Favourite.toggle(productId);
        if (isFav) {
            icon.classList.add('fill-current', 'text-tertiary');
            Components.showToast('Added to Clinical Favourites', 'success');
        } else {
            icon.classList.remove('fill-current', 'text-tertiary');
            Components.showToast('Removed from Archives', 'error');
        }
        Components.updateFavouritePreview();
    }
};

/**
 * ZOOM FEATURE
 */
const initZoom = (targetImg, targetZoom) => {
    const img = (typeof targetImg === 'string') ? document.querySelector(targetImg) : targetImg;
    const zoom = (typeof targetZoom === 'string') ? document.querySelector(targetZoom) : targetZoom;
    if(!img || !zoom) return;
    let lens = img.parentElement.querySelector('.zoom-lens') || document.createElement('div');
    if(!lens.parentElement) { lens.className = 'zoom-lens'; img.parentElement.appendChild(lens); }
    let isLocked = false;
    const magFactor = 2.3;
    const updateZoom = (e) => {
        if (window.innerWidth < 992) return;
        const rect = img.getBoundingClientRect();
        const parentRect = img.parentElement.getBoundingClientRect();
        const lensW = rect.width / magFactor, lensH = rect.height / magFactor;
        lens.style.width = lensW + 'px'; lens.style.height = lensH + 'px';
        let x = e.clientX - parentRect.left - (lensW / 2), y = e.clientY - parentRect.top - (lensH / 2);
        const imgRelX = rect.left - parentRect.left, imgRelY = rect.top - parentRect.top;
        if(x > imgRelX + rect.width - lensW) x = imgRelX + rect.width - lensW;
        if(x < imgRelX) x = imgRelX;
        if(y > imgRelY + rect.height - lensH) y = imgRelY + rect.height - lensH;
        if(y < imgRelY) y = imgRelY;
        lens.style.left = x + 'px'; lens.style.top = y + 'px';
        zoom.style.top = rect.top + 'px'; zoom.style.left = (rect.right + 20) + 'px'; zoom.style.height = rect.height + 'px';
        const ratioX = (x - imgRelX) / (rect.width - lensW), ratioY = (y - imgRelY) / (rect.height - lensH);
        zoom.style.backgroundImage = `url("${img.src}")`; zoom.style.backgroundPosition = `${ratioX * 100}% ${ratioY * 100}%`;
        zoom.style.backgroundSize = `${rect.width * magFactor}px ${rect.height * magFactor}px`;
        zoom.classList.add('active'); lens.classList.add('active');
    };
    img.addEventListener('mousemove', (e) => { if (!isLocked) updateZoom(e); });
    img.addEventListener('mouseleave', () => { if(!isLocked) { zoom.classList.remove('active'); lens.classList.remove('active'); } });
    img.addEventListener('click', () => { if (window.innerWidth < 992) return; isLocked = !isLocked; zoom.classList.toggle('locked', isLocked); });
};

/**
 * TABS SYSTEM
 */
const TabSystem = {
    switch(btn, tabId) {
        document.querySelectorAll('.tab-btn').forEach(b => { b.classList.remove('text-primary', 'border-primary', 'border-b-2'); b.classList.add('text-gray-400'); });
        btn.classList.add('text-primary', 'border-primary', 'border-b-2'); btn.classList.remove('text-gray-400');
        document.querySelectorAll('.tab-content').forEach(c => { c.classList.add('hidden', 'opacity-0'); c.classList.remove('opacity-100'); });
        const activeContent = document.getElementById(`tab-content-${tabId}`);
        activeContent.classList.remove('hidden'); setTimeout(() => activeContent.classList.add('opacity-100'), 50);
    }
};

window.TabSystem = TabSystem;
window.UI = UI;
window.Cart = Cart;
window.Favourite = Favourite;
window.FavouritePage = FavouritePage;
window.FilterSystem = FilterSystem;
window.ProductRenderer = ProductRenderer;

/**
 * HERO CAROUSEL LOGIC
 */
const HeroCarousel = {
    index: 0,
    total: 4,
    interval: null,
    
    init() {
        const track = document.getElementById('carousel-track');
        if (!track) return;
        
        this.update();
        this.play();

        const carousel = document.getElementById('hero-carousel');
        if (carousel) {
            carousel.addEventListener('mouseenter', () => this.pause());
            carousel.addEventListener('mouseleave', () => this.play());
        }
        
        window.addEventListener('resize', () => { this.update(); });
    },
    
    play() {
        this.pause();
        this.interval = setInterval(() => this.next(), 1400); // 1.4s
    },
    
    pause() {
        if (this.interval) clearInterval(this.interval);
    },
    
    next() {
        this.index = (this.index + 1) % this.total;
        this.update();
    },
    
    prev() {
        this.index = (this.index - 1 + this.total) % this.total;
        this.update();
    },
    
    goTo(idx) {
        this.index = idx;
        this.update();
    },
    
    update() {
        const track = document.getElementById('carousel-track');
        if (!track) return;
        
        const slides = track.querySelectorAll('.slide');
        if (slides.length === 0) return;
        
        const containerWidth = track.parentElement.offsetWidth;
        const slideWidth = slides[0].offsetWidth;
        const gap = 16;
        
        const shift = this.index * (slideWidth + gap);
        const centerPadding = (containerWidth - slideWidth) / 2;
        
        track.style.transform = `translateX(${-shift + centerPadding}px)`;
        
        slides.forEach((slide, i) => {
            if (i === this.index) {
                slide.classList.remove('opacity-50', 'scale-95');
                slide.classList.add('opacity-100', 'scale-100', 'shadow-2xl', 'z-10');
            } else {
                slide.classList.remove('opacity-100', 'scale-100', 'shadow-2xl', 'z-10');
                slide.classList.add('opacity-50', 'scale-95');
            }
        });
        
        const dots = document.querySelectorAll('#carousel-dots button');
        dots.forEach((dot, i) => {
            if (i === this.index) {
                dot.classList.add('w-6', 'bg-white');
                dot.classList.remove('bg-white/50');
            } else {
                dot.classList.remove('w-6', 'bg-white');
                dot.classList.add('bg-white/50');
            }
        });
    }
};

window.HeroCarousel = HeroCarousel;

// Register Service Worker
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js');
}

/**
 * CATEGORY CAROUSEL LOGIC
 */
const CategoryCarousel = {
    interval: null,
    isTransitioning: false,
    currentDirection: -1,
    categories: [
        { name: 'Medicine', img: 'create_similar_picture_202603311347.webp' },
        { name: 'Multivitamins', img: 'create_similar_picture_202603311347 (1).webp' },
        { name: 'Intimate Essentials', img: 'create_similar_picture_202603311347 (2).webp' },
        { name: 'Nebulizer', img: 'create_similar_picture_202603311347 (3).webp' },
        { name: 'Derma', img: 'create_similar_picture_202603311347 (4).webp' },
        { name: 'A to Z Medicine', img: 'create_similar_picture_202603311347 (5).webp' },
        { name: 'Surgicals', img: 'create_similar_picture_202603311347 (6).webp' },
        { name: 'Baby Care', img: 'create_similar_picture_202603311348.webp' },
        { name: 'Nutrition', img: 'create_similar_picture_202603311348 (1).webp' },
        { name: 'Dental', img: 'create_similar_picture_202603311348 (2).webp' },
        { name: 'First Aid', img: 'create_similar_picture_202603311348 (3).webp' },
        { name: 'Personal Care', img: 'create_similar_picture_202603311348 (4).webp' }
    ],

    init() {
        const track = document.getElementById('cat-carousel-track');
        if (!track) return;
        
        let html = '';
        this.categories.forEach(cat => {
            html += this.getSlideHTML(cat);
        });
        track.innerHTML = html;

        this.play();

        const carousel = document.getElementById('category-carousel');
        if (carousel) {
            carousel.addEventListener('mouseenter', () => this.pause());
            carousel.addEventListener('mouseleave', () => this.play());
        }

        track.addEventListener('transitionend', () => {
            if (!this.isTransitioning) return;
            this.isTransitioning = false;
            
            track.style.transition = 'none';
            if (this.currentDirection === -1) {
                // Moved left (next), pop first to end
                track.appendChild(track.firstElementChild);
            }
            track.style.transform = `translateX(0px)`;
        });
    },

    getSlideHTML(cat) {
        return `
        <div class="group relative flex-none w-[170px] bg-white rounded-xl border border-gray-100 hover:border-[#7AC334] transition-colors duration-300 pb-10 pt-6 px-4 cursor-pointer text-center cat-slide shadow-sm hover:shadow-md" onclick="window.location.href='products.html?category=${cat.name.split(' ')[0].toLowerCase()}'">
            <div class="h-28 w-full flex items-center justify-center mb-6">
                <img src="assets/categories/${cat.img}" class="max-h-full max-w-full object-contain" alt="${cat.name}">
            </div>
            <h3 class="text-[14px] font-bold text-gray-900 group-hover:text-[#62B22E] transition-colors line-clamp-2">${cat.name}</h3>
            
            <!-- Hover Action Button at Bottom Edge -->
            <div class="absolute left-1/2 -bottom-5 -translate-x-1/2 w-10 h-10 bg-[#7AC334] text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transform translate-y-4 group-hover:-translate-y-0 shadow-lg shadow-[#7AC334]/30 transition-all duration-[400ms] pointer-events-none z-10 border-2 border-white">
                <span class="material-symbols-outlined text-[24px]">chevron_right</span>
            </div>
        </div>`;
    },

    play() {
        this.pause();
        // 1700ms requested
        this.interval = setInterval(() => this.next(), 1700);
    },

    pause() {
        if (this.interval) clearInterval(this.interval);
    },

    next() {
        if (this.isTransitioning) return;
        const track = document.getElementById('cat-carousel-track');
        const slide = track.querySelector('.cat-slide');
        if (!slide || !track) return;
        
        this.isTransitioning = true;
        this.currentDirection = -1;
        
        // Tailwind gap-5 is 20px
        const shiftX = slide.offsetWidth + 20; 
        
        track.style.transition = 'transform 500ms ease-in-out';
        track.style.transform = `translateX(-${shiftX}px)`;
    },

    prev() {
        if (this.isTransitioning) return;
        const track = document.getElementById('cat-carousel-track');
        const slide = track.querySelector('.cat-slide');
        if (!slide || !track) return;
        
        this.isTransitioning = true;
        this.currentDirection = 1;
        
        // Instantly move last to front
        track.style.transition = 'none';
        track.insertBefore(track.lastElementChild, track.firstElementChild);
        
        const shiftX = slide.offsetWidth + 20; 
        track.style.transform = `translateX(-${shiftX}px)`;
        
        void track.offsetWidth; // reflow
        
        track.style.transition = 'transform 500ms ease-in-out';
        track.style.transform = `translateX(0px)`;
    }
};

window.CategoryCarousel = CategoryCarousel;
