document.addEventListener('DOMContentLoaded', function () {
    const toggler = document.querySelector('.nav-toggle');
    const nav = document.querySelector('.site-nav');
    const navClose = document.querySelector('.nav-close');
    if (toggler && nav) {
        toggler.addEventListener('click', function () {
            const isOpen = nav.classList.toggle('nav-open');
            toggler.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
        });
    }
    if (navClose && nav) {
        navClose.addEventListener('click', function () {
            nav.classList.remove('nav-open');
            if (toggler) {
                toggler.setAttribute('aria-expanded', 'false');
            }
        });
    }
    document.querySelectorAll('.site-nav a').forEach(link => {
        link.addEventListener('click', () => nav.classList.remove('nav-open'));
    });

    const shopSearch = document.querySelector('#shop-search');
    const minPrice = document.querySelector('#min-price');
    const maxPrice = document.querySelector('#max-price');
    const applyFilters = document.querySelector('#apply-filters');
    const categoryLinks = document.querySelectorAll('#category-list a');
    const productGrid = document.querySelector('.product-grid');
    const cartItemsContainer = document.querySelector('#shop-cart-items');
    const cartTotalLabel = document.querySelector('#cart-total');
    const checkoutButton = document.querySelector('#checkout-whatsapp');
    const clearCartButton = document.querySelector('#clear-cart');
    const floatingCartButton = document.querySelector('#floating-cart-button');
    const floatingCartCount = document.querySelector('#floating-cart-count');
    const cartOverlay = document.querySelector('#cart-overlay');
    const cartPanel = document.querySelector('#cart-panel');
    const cartSuccessMessage = document.querySelector('#cart-success-message');
    const closeCartButton = document.querySelector('.cart-close-btn');
    const featuredTrack = document.querySelector('.featured-track');
    const prevBtn = document.querySelector('.slider-prev');
    const nextBtn = document.querySelector('.slider-next');
    const whatsappNumber = window.shopWhatsapp || '';
    const cartEndpoint = window.cartEndpoint || 'cart.php';

    let activeCategory = 0;
    categoryLinks.forEach(link => {
        if (link.classList.contains('active')) {
            activeCategory = parseInt(link.dataset.categoryId || '0', 10);
        }
    });

    const formatCurrency = (value) => {
        return 'Ksh ' + Number(value).toLocaleString('en-KE', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        });
    };

    const openCartOverlay = () => {
        if (cartOverlay) {
            cartOverlay.classList.add('open');
            cartOverlay.setAttribute('aria-hidden', 'false');
        }
    };

    const closeCartOverlay = () => {
        if (cartOverlay) {
            cartOverlay.classList.remove('open');
            cartOverlay.setAttribute('aria-hidden', 'true');
        }
    };

    const showCartNotice = (message) => {
        if (!cartSuccessMessage) {
            return;
        }
        cartSuccessMessage.textContent = message;
        cartSuccessMessage.classList.add('visible');
        window.clearTimeout(window.__cartNoticeTimeout);
        window.__cartNoticeTimeout = window.setTimeout(() => {
            cartSuccessMessage.classList.remove('visible');
        }, 2400);
    };

    const fetchCart = () => {
        return fetch(`${cartEndpoint}?action=get`, {
            credentials: 'same-origin',
            headers: { 'Accept': 'application/json' },
        }).then(res => res.json());
    };

    const updateCartUI = (cartData) => {
        if (floatingCartCount) {
            floatingCartCount.textContent = String(cartData.count || 0);
        }
        if (cartTotalLabel) {
            cartTotalLabel.textContent = formatCurrency(cartData.total || 0);
        }
        if (!cartItemsContainer) {
            return;
        }
        cartItemsContainer.innerHTML = '';

        if (!cartData.items || cartData.items.length === 0) {
            cartItemsContainer.innerHTML = '<p class="cart-empty">Add products to your cart to order them together.</p>';
            return;
        }

        cartData.items.forEach(item => {
            const cartItem = document.createElement('div');
            cartItem.className = 'cart-item';
            cartItem.innerHTML = `
                <div class="cart-item-info">
                    <div class="cart-item-name">${item.name}</div>
                    <div class="cart-item-meta">${item.quantity} × ${formatCurrency(item.price)} = ${formatCurrency(item.quantity * item.price)}</div>
                </div>
                <div class="cart-actions">
                    <button type="button" class="btn btn-outline small cart-remove" data-product-id="${item.id}">Remove</button>
                </div>
            `;
            cartItemsContainer.appendChild(cartItem);
        });
    };

    const postCartAction = (action, payload = {}) => {
        const body = new URLSearchParams({ action, ...payload });
        return fetch(cartEndpoint, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: body.toString(),
        }).then(res => res.json());
    };

    const addProductToCart = (productId) => {
        return postCartAction('add', { id: productId });
    };

    const removeCartItem = (productId) => {
        return postCartAction('remove', { id: productId });
    };

    const clearCart = () => {
        return postCartAction('clear');
    };

    const checkoutCart = () => {
        return fetchCart().then(data => {
            if (!whatsappNumber) {
                alert('WhatsApp number is not configured yet.');
                return;
            }
            if (!data.items || data.items.length === 0) {
                alert('Your cart is empty. Add products before checkout.');
                return;
            }
            const lines = data.items.map(item => `${item.quantity} x ${item.name} (${formatCurrency(item.price)}) = ${formatCurrency(item.quantity * item.price)}`);
            const message = `Hello Tumaini Cyber, I would like to order the following products:\n\n${lines.join('\n')}\n\nTotal: ${formatCurrency(data.total)}\n\nPlease let me know how to proceed.`;
            window.open(`https://wa.me/${whatsappNumber}?text=${encodeURIComponent(message)}`, '_blank');
        });
    };

    const handleAddToCartClick = (event) => {
        const button = event.target.closest('.add-cart-btn');
        if (!button) {
            return;
        }
        const productId = button.dataset.productId;
        if (!productId) {
            return;
        }

        addProductToCart(productId)
            .then(data => {
                if (data.success) {
                    updateCartUI(data);
                    showCartNotice('Added to cart successfully.');
                    openCartOverlay();
                }
            })
            .catch(() => {
                alert('Could not add product to cart. Please try again.');
            });
    };

    const handleCartMutation = (event) => {
        const removeButton = event.target.closest('.cart-remove');
        if (removeButton) {
            removeCartItem(removeButton.dataset.productId)
                .then(data => {
                    if (data.success) {
                        updateCartUI(data);
                    }
                });
            return;
        }

        if (event.target.matches('#clear-cart')) {
            clearCart().then(data => {
                if (data.success) {
                    updateCartUI(data);
                }
            });
            return;
        }

        if (event.target.matches('#checkout-whatsapp')) {
            checkoutCart();
            return;
        }

        if (event.target.closest('#floating-cart-button')) {
            event.preventDefault();
            openCartOverlay();
            return;
        }

        if (event.target.closest('.cart-close-btn')) {
            closeCartOverlay();
            return;
        }
    };

    if (productGrid && shopSearch) {
        let debounceTimer;

        const fetchShopProducts = (categoryId = activeCategory, query = '', min = '', max = '') => {
            const url = new URL(window.location.href);
            url.searchParams.set('ajax', '1');
            url.searchParams.set('q', query);
            if (categoryId) {
                url.searchParams.set('category_id', categoryId);
            } else {
                url.searchParams.delete('category_id');
            }
            if (min !== '') {
                url.searchParams.set('min_price', min);
            } else {
                url.searchParams.delete('min_price');
            }
            if (max !== '') {
                url.searchParams.set('max_price', max);
            } else {
                url.searchParams.delete('max_price');
            }

            fetch(url.toString(), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(response => response.json())
                .then(data => {
                    productGrid.innerHTML = data.html;
                });
        };

        const updateActiveCategory = (selectedId) => {
            categoryLinks.forEach(link => {
                if (link.dataset.categoryId === String(selectedId)) {
                    link.classList.add('active');
                } else {
                    link.classList.remove('active');
                }
            });
        };

        shopSearch.addEventListener('input', () => {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                fetchShopProducts(activeCategory, shopSearch.value.trim(), minPrice.value.trim(), maxPrice.value.trim());
            }, 300);
        });

        if (applyFilters) {
            applyFilters.addEventListener('click', () => {
                fetchShopProducts(activeCategory, shopSearch.value.trim(), minPrice.value.trim(), maxPrice.value.trim());
            });
        }

        categoryLinks.forEach(link => {
            link.addEventListener('click', (event) => {
                event.preventDefault();
                activeCategory = parseInt(link.dataset.categoryId || '0', 10);
                updateActiveCategory(activeCategory);
                fetchShopProducts(activeCategory, shopSearch.value.trim(), minPrice.value.trim(), maxPrice.value.trim());
            });
        });
    }

    const featuredSlides = featuredTrack ? featuredTrack.querySelectorAll('.spotlight-slide') : [];
    const progressContainer = document.querySelector('.featured-progress');
    let activeSlideIndex = 0;

    const updateProgressDots = () => {
        const dots = progressContainer ? Array.from(progressContainer.children) : [];
        dots.forEach((dot, index) => {
            dot.classList.toggle('active', index === activeSlideIndex);
        });
    };

    const updateActiveSlide = () => {
        if (!featuredTrack || featuredSlides.length === 0) return;
        const scrollLeft = featuredTrack.scrollLeft;
        const slideWidth = featuredSlides[0].offsetWidth + 24;
        activeSlideIndex = Math.round(scrollLeft / slideWidth);
        activeSlideIndex = Math.min(Math.max(activeSlideIndex, 0), featuredSlides.length - 1);
        updateProgressDots();
    };

    if (featuredTrack && prevBtn && nextBtn) {
        const scrollAmount = featuredTrack.clientWidth * 0.85;
        prevBtn.addEventListener('click', () => {
            featuredTrack.scrollBy({ left: -scrollAmount, behavior: 'smooth' });
        });
        nextBtn.addEventListener('click', () => {
            featuredTrack.scrollBy({ left: scrollAmount, behavior: 'smooth' });
        });

        if (progressContainer && featuredSlides.length > 0) {
            featuredSlides.forEach((_, idx) => {
                const dot = document.createElement('button');
                dot.type = 'button';
                dot.setAttribute('aria-label', `Go to featured slide ${idx + 1}`);
                dot.addEventListener('click', () => {
                    if (!featuredSlides[idx]) return;
                    featuredTrack.scrollTo({ left: featuredSlides[idx].offsetLeft, behavior: 'smooth' });
                });
                progressContainer.appendChild(dot);
            });
            updateProgressDots();
            featuredTrack.addEventListener('scroll', () => {
                window.requestAnimationFrame(updateActiveSlide);
            });
        }
    }

    document.body.addEventListener('click', (event) => {
        handleAddToCartClick(event);
        handleCartMutation(event);
    });

    if (closeCartButton) {
        closeCartButton.addEventListener('click', closeCartOverlay);
    }

    if (cartOverlay) {
        cartOverlay.addEventListener('click', (event) => {
            if (event.target === cartOverlay) {
                closeCartOverlay();
            }
        });
    }

    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape') {
            closeCartOverlay();
        }
    });

    fetchCart().then(data => {
        if (data.success) {
            updateCartUI(data);
        }
    });
});
