/**
 * HugongShop - Main JavaScript
 * Consolidated version of all JS functionality
 * Version: 2.0.0
 * Date: 2025-03-21
 */

document.addEventListener('DOMContentLoaded', function() {
    // Global app object to store all modules and utils
    const HugongShop = {
        // Cache for DOM elements
        elements: {},
        
        // Configuration options
        config: {
            // CSRF token for AJAX requests
            csrfToken: document.getElementById('csrf-token') ? document.getElementById('csrf-token').value : '',
            // Site URL for AJAX paths
            siteUrl: window.location.origin,
            // Animation durations
            animationSpeed: 300
        },

        /**
         * Initialize the entire application
         */
        init: function() {
            this.cacheElements();
            this.initCommonElements();
            this.initPageSpecific();

            // Log initialization complete
            console.log('HugongShop JS initialized');
        },

        /**
         * Cache DOM elements for faster access
         */
        cacheElements: function() {
            // Mobile menu elements
            this.elements.menuToggle = document.getElementById('mobile-menu-toggle');
            this.elements.menuDrawer = document.getElementById('mobile-drawer');
            this.elements.menuOverlay = document.getElementById('mobile-menu-overlay');
            
            // Back to top button
            this.elements.backToTop = document.getElementById('back-to-top');
            
            // Cart count elements
            this.elements.cartCount = document.querySelectorAll('.cart-count');
        },

        /**
         * Initialize elements common to all pages
         */
        initCommonElements: function() {
            this.initMobileMenu();
            this.initBackToTop();
            this.handleUrlHash();
        },

        /**
         * Handle URL hash links for tabs, etc.
         */
        handleUrlHash: function() {
            if (location.hash) {
                const hash = location.hash.substring(1);
                const tabBtn = document.getElementById(`tab-${hash}-btn`);
                if (tabBtn) {
                    setTimeout(() => tabBtn.click(), 100);
                } else {
                    const element = document.getElementById(hash);
                    if (element) {
                        setTimeout(() => {
                            element.scrollIntoView({ behavior: 'smooth' });
                        }, 100);
                    }
                }
            }
        },

        /**
         * Mobile menu initialization
         */
        initMobileMenu: function() {
            const menuToggle = this.elements.menuToggle;
            const menuDrawer = this.elements.menuDrawer;
            const menuOverlay = this.elements.menuOverlay;
            
            if (!menuToggle || !menuDrawer || !menuOverlay) {
                console.warn('Mobile menu elements not found, skipping initialization');
                return;
            }
            
            // Create close button if it doesn't exist
            let closeButton = menuDrawer.querySelector('.menu-close');
            if (!closeButton) {
                closeButton = document.createElement('button');
                closeButton.className = 'menu-close';
                closeButton.innerHTML = '&times;';
                closeButton.style.cssText = `
                    position: absolute;
                    top: 15px;
                    right: 15px;
                    background: none;
                    border: none;
                    font-size: 28px;
                    color: #333;
                    cursor: pointer;
                    z-index: 10;
                `;
                
                if (menuDrawer.firstChild) {
                    menuDrawer.insertBefore(closeButton, menuDrawer.firstChild);
                } else {
                    menuDrawer.appendChild(closeButton);
                }
            }
            
            // Open menu
            menuToggle.addEventListener('click', () => {
                menuDrawer.classList.add('active');
                menuOverlay.classList.add('active');
                document.body.classList.add('menu-open');
            });
            
            // Close menu on X button click
            closeButton.addEventListener('click', () => {
                this.closeMobileMenu();
            });
            
            // Close menu on overlay click
            menuOverlay.addEventListener('click', () => {
                this.closeMobileMenu();
            });
            
            // Close menu on escape key
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && menuDrawer.classList.contains('active')) {
                    this.closeMobileMenu();
                }
            });
        },
        
        /**
         * Close mobile menu
         */
        closeMobileMenu: function() {
            const menuDrawer = this.elements.menuDrawer;
            const menuOverlay = this.elements.menuOverlay;
            
            if (menuDrawer) menuDrawer.classList.remove('active');
            if (menuOverlay) menuOverlay.classList.remove('active');
            document.body.classList.remove('menu-open');
        },
        
        /**
         * Back to top button initialization
         */
        initBackToTop: function() {
            const backToTopBtn = this.elements.backToTop;
            
            if (!backToTopBtn) return;
            
            window.addEventListener('scroll', () => {
                if (window.pageYOffset > 300) {
                    backToTopBtn.classList.add('visible');
                } else {
                    backToTopBtn.classList.remove('visible');
                }
            });
            
            backToTopBtn.addEventListener('click', () => {
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });
        },

        /**
         * Initialize page-specific functionality based on page elements
         */
        initPageSpecific: function() {
            // Product page
            if (document.querySelector('.product-container')) {
                this.ProductPage.init();
            }
            
            // Checkout page
            if (document.querySelector('.checkout-content')) {
                this.CheckoutPage.init();
            }
            
            // Cart page
            if (document.querySelector('.cart-page')) {
                this.CartPage.init();
            }
            
            // Home page (hero slider, testimonials)
            if (document.querySelector('.hero-slider') || document.querySelector('.testimonials-slider')) {
                this.HomePage.init();
            }
        },

        /**
         * Format price with Serbian format
         * @param {number} price - Price to format
         * @return {string} Formatted price
         */
        formatPrice: function(price) {
            return new Intl.NumberFormat('sr-RS', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            }).format(price) + ' rsd';
        },

        /**
         * Update cart count in header
         * @param {number} quantity - Quantity to add to current count
         */
        updateCartCount: function(quantity) {
            const cartCountElements = this.elements.cartCount;
            
            cartCountElements.forEach(element => {
                let currentCount = parseInt(element.textContent) || 0;
                element.textContent = currentCount + quantity;
            });
        },

        /**
         * Add to cart via AJAX
         * @param {number} productId - Product ID
         * @param {number} quantity - Quantity to add
         * @param {boolean} goToCheckout - Whether to redirect to checkout after adding
         * @param {boolean} isMultiple - Whether multiple products are being added
         * @return {Promise} Promise that resolves with cart data
         */
        addToCart: function(productId, quantity, goToCheckout = false, isMultiple = false) {
            return new Promise((resolve, reject) => {
                const formData = new FormData();
                formData.append('product_id', productId);
                formData.append('quantity', quantity);
                
                if (this.config.csrfToken) {
                    formData.append('csrf_token', this.config.csrfToken);
                }
                
                fetch('/ajax/add-to-cart.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        this.updateCartCount(parseInt(quantity));
                        
                        if (goToCheckout) {
                            window.location.href = '/checkout';
                        } else if (!isMultiple) {
                            this.openModal('cart-success-modal');
                        }
                        
                        resolve(data);
                    } else {
                        alert(data.message || 'Došlo je do greške prilikom dodavanja proizvoda u korpu.');
                        reject(data.message);
                    }
                })
                .catch(error => {
                    console.error('Error adding to cart:', error);
                    alert('Došlo je do greške prilikom komunikacije sa serverom. Molimo pokušajte ponovo.');
                    reject(error);
                });
            });
        },
        
        /**
         * Add multiple products to cart
         * @param {Array} products - Array of products with id and quantity
         * @return {Promise} Promise that resolves with cart data
         */
        addMultipleToCart: function(products) {
            return new Promise((resolve, reject) => {
                fetch('/ajax/add-multiple-to-cart.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        products: products,
                        csrf_token: this.config.csrfToken
                    })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        this.openModal('cart-success-modal');
                        
                        // Calculate total quantity added
                        const totalQuantity = products.reduce((sum, product) => sum + parseInt(product.quantity), 0);
                        this.updateCartCount(totalQuantity);
                        
                        resolve(data);
                    } else {
                        alert(data.message || 'Došlo je do greške prilikom dodavanja proizvoda u korpu.');
                        reject(data.message);
                    }
                })
                .catch(error => {
                    console.error('Error adding multiple products to cart:', error);
                    alert('Došlo je do greške prilikom komunikacije sa serverom. Molimo pokušajte ponovo.');
                    reject(error);
                });
            });
        },
        
        /**
         * Open modal
         * @param {string} modalId - ID of the modal to open
         */
        openModal: function(modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.add('active');
                document.body.style.overflow = 'hidden';
            }
        },
        
        /**
         * Close modal
         * @param {string} modalId - ID of the modal to close
         */
        closeModal: function(modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.remove('active');
                document.body.style.overflow = '';
            }
        },

        /**
         * Product page specific functionality
         */
        ProductPage: {
            // Reference to parent object
            parent: null,
            
            // Cache of DOM elements
            elements: {},
            
            /**
             * Initialize product page functionality
             */
            init: function() {
                this.parent = HugongShop;
                this.cacheElements();
                
                this.initImageGallery();
                this.initTabs();
                this.initQuantityControls();
                this.initAccordions();
                this.initModals();
                this.initSimilarProducts();
                this.initStickyCart();
                this.initAddToCart();
                this.initFrequentlyBoughtTogether();
                this.initReviewForm();
                this.initAskQuestionForm();
            },
            
            /**
             * Cache product page DOM elements
             */
            cacheElements: function() {
                // Image gallery
                this.elements.mainImage = document.getElementById('main-product-image');
                this.elements.thumbnails = document.querySelectorAll('.thumbnail');
                this.elements.zoomTrigger = document.querySelector('.image-zoom-trigger');
                
                // Tabs
                this.elements.tabButtons = document.querySelectorAll('.tab-btn');
                this.elements.tabContents = document.querySelectorAll('.tab-content');
                
                // Quantity controls
                this.elements.quantityInput = document.getElementById('quantity');
                this.elements.minusBtn = document.querySelector('.quantity-btn.minus');
                this.elements.plusBtn = document.querySelector('.quantity-btn.plus');
                
                // Add to cart buttons
                this.elements.addToCartBtn = document.getElementById('add-to-cart-btn');
                this.elements.buyNowBtn = document.getElementById('buy-now-btn');
                this.elements.stickyBuyBtn = document.querySelector('.sticky-buy-btn');
                
                // Frequently bought together
                this.elements.fbtCheckboxes = document.querySelectorAll('.fbt-checkbox input');
                this.elements.addAllBtn = document.getElementById('add-all-to-cart');
                
                // Triggers
                this.elements.priceMatchTrigger = document.querySelector('.price-match-trigger');
                this.elements.paymentOptionsTrigger = document.getElementById('payment-options-trigger');
                this.elements.scrollToReviews = document.querySelector('.scroll-to-reviews');
            },
            
            /**
             * Initialize product image gallery
             */
            initImageGallery: function() {
                if (!this.elements.mainImage || !this.elements.thumbnails.length) return;
                
                // Thumbnail click
                this.elements.thumbnails.forEach(thumb => {
                    thumb.addEventListener('click', () => {
                        // Update main image
                        this.elements.mainImage.src = thumb.getAttribute('data-image');
                        this.elements.mainImage.setAttribute('data-zoom-src', thumb.getAttribute('data-zoom-src'));
                        
                        // Update active thumbnail
                        this.elements.thumbnails.forEach(t => t.classList.remove('active'));
                        thumb.classList.add('active');
                    });
                });
                
                // Image zoom
                if (this.elements.zoomTrigger) {
                    this.elements.zoomTrigger.addEventListener('click', () => {
                        const zoomSrc = this.elements.mainImage.getAttribute('data-zoom-src') || this.elements.mainImage.src;
                        const zoomedImage = document.getElementById('zoomed-image');
                        if (zoomedImage) {
                            zoomedImage.src = zoomSrc;
                            this.parent.openModal('image-modal');
                        }
                    });
                }
            },
            
            /**
             * Initialize tabs system
             */
            initTabs: function() {
                if (!this.elements.tabButtons.length || !this.elements.tabContents.length) return;
                
                this.elements.tabButtons.forEach(button => {
                    button.addEventListener('click', () => {
                        const tabId = button.getAttribute('data-tab');
                        
                        // Remove active class from all tabs
                        this.elements.tabButtons.forEach(btn => {
                            btn.classList.remove('active');
                            btn.setAttribute('aria-selected', 'false');
                        });
                        
                        this.elements.tabContents.forEach(content => {
                            content.classList.remove('active');
                        });
                        
                        // Activate selected tab
                        button.classList.add('active');
                        button.setAttribute('aria-selected', 'true');
                        
                        const activeTab = document.getElementById(tabId);
                        if (activeTab) {
                            activeTab.classList.add('active');
                            
                            // Initialize accordions if warranty tab
                            if (tabId === 'tab-warranty') {
                                this.initAccordions('#tab-warranty');
                            }
                        }
                    });
                });
            },
            
            /**
             * Initialize quantity controls
             */
            initQuantityControls: function() {
                if (!this.elements.quantityInput || !this.elements.minusBtn || !this.elements.plusBtn) return;
                
                this.elements.minusBtn.addEventListener('click', () => {
                    const currentValue = parseInt(this.elements.quantityInput.value);
                    if (currentValue > 1) {
                        this.elements.quantityInput.value = currentValue - 1;
                    }
                });
                
                this.elements.plusBtn.addEventListener('click', () => {
                    const currentValue = parseInt(this.elements.quantityInput.value);
                    const maxValue = parseInt(this.elements.quantityInput.getAttribute('max') || 999);
                    
                    if (currentValue < maxValue) {
                        this.elements.quantityInput.value = currentValue + 1;
                    }
                });
                
                // Validate input
                this.elements.quantityInput.addEventListener('change', () => {
                    let value = parseInt(this.elements.quantityInput.value);
                    const min = parseInt(this.elements.quantityInput.getAttribute('min') || 1);
                    const max = parseInt(this.elements.quantityInput.getAttribute('max') || 999);
                    
                    if (isNaN(value) || value < min) {
                        this.elements.quantityInput.value = min;
                    } else if (value > max) {
                        this.elements.quantityInput.value = max;
                    }
                });
            },
            
            /**
             * Initialize accordions
             * @param {string} selector - Optional selector to limit scope
             */
            initAccordions: function(selector = '') {
                const accordionButtons = selector 
                    ? document.querySelectorAll(`${selector} .accordion-btn`)
                    : document.querySelectorAll('.accordion-btn');
                
                accordionButtons.forEach(button => {
                    // Remove existing event listener to prevent duplicates
                    button.removeEventListener('click', this.handleAccordionClick);
                    
                    // Add new event listener
                    button.addEventListener('click', this.handleAccordionClick);
                });
            },
            
            /**
             * Handle accordion click
             */
            handleAccordionClick: function() {
                const expanded = this.getAttribute('aria-expanded') === 'true';
                const faqItem = this.closest('.faq-item');
                const faqAnswer = faqItem.querySelector('.faq-answer');
                
                // Toggle expanded state
                this.setAttribute('aria-expanded', !expanded);
                
                // Toggle display
                if (faqAnswer) {
                    if (expanded) {
                        faqAnswer.style.display = 'none';
                        faqAnswer.hidden = true;
                    } else {
                        faqAnswer.style.display = 'block';
                        faqAnswer.hidden = false;
                    }
                }
                
                // Rotate icon
                const icon = this.querySelector('.accordion-icon');
                if (icon) {
                    icon.style.transform = expanded ? '' : 'rotate(180deg)';
                }
            },
            
            /**
             * Initialize modals
             */
            initModals: function() {
                // Close modal on overlay click
                const modalOverlays = document.querySelectorAll('.modal-overlay');
                modalOverlays.forEach(overlay => {
                    overlay.addEventListener('click', () => {
                        const modal = overlay.closest('.modal');
                        this.parent.closeModal(modal.id);
                    });
                });
                
                // Close modal on X or cancel button click
                const closeButtons = document.querySelectorAll('.modal-close, .modal-cancel');
                closeButtons.forEach(button => {
                    button.addEventListener('click', () => {
                        const modal = button.closest('.modal');
                        this.parent.closeModal(modal.id);
                    });
                });
                
                // ESC to close modals
                document.addEventListener('keydown', (e) => {
                    if (e.key === 'Escape') {
                        const activeModals = document.querySelectorAll('.modal.active');
                        activeModals.forEach(modal => this.parent.closeModal(modal.id));
                    }
                });
                
                // Price match modal
                if (this.elements.priceMatchTrigger) {
                    this.elements.priceMatchTrigger.addEventListener('click', (e) => {
                        e.preventDefault();
                        this.parent.openModal('price-match-modal');
                    });
                    
                    // Custom file input
                    const fileInput = document.getElementById('proof_file');
                    const fileLabel = document.querySelector('.custom-file-label');
                    
                    if (fileInput && fileLabel) {
                        fileInput.addEventListener('change', function() {
                            const fileName = this.value.split('\\').pop();
                            fileLabel.textContent = fileName || 'Izaberite fajl';
                        });
                    }
                }
                
                // Payment options modal
                if (this.elements.paymentOptionsTrigger) {
                    this.elements.paymentOptionsTrigger.addEventListener('click', (e) => {
                        e.preventDefault();
                        this.parent.openModal('payment-options-modal');
                    });
                }
                
                // Scroll to reviews
                if (this.elements.scrollToReviews) {
                    this.elements.scrollToReviews.addEventListener('click', (e) => {
                        e.preventDefault();
                        document.getElementById('tab-reviews-btn').click();
                        
                        setTimeout(() => {
                            document.getElementById('tab-reviews').scrollIntoView({
                                behavior: 'smooth'
                            });
                        }, 100);
                    });
                }
            },
            
            /**
             * Initialize review form
             */
            initReviewForm: function() {
                const writeReviewBtn = document.getElementById('write-review-btn');
                const reviewForm = document.getElementById('review-form-container');
                const cancelReviewBtn = document.getElementById('cancel-review');
                
                if (writeReviewBtn && reviewForm) {
                    writeReviewBtn.addEventListener('click', function() {
                        reviewForm.style.display = 'block';
                        this.style.display = 'none';
                    });
                    
                    if (cancelReviewBtn) {
                        cancelReviewBtn.addEventListener('click', function() {
                            reviewForm.style.display = 'none';
                            writeReviewBtn.style.display = 'block';
                        });
                    }
                }
                
                // Rating input handling
                const ratingInputs = document.querySelectorAll('.rating-input input');
                if (ratingInputs.length) {
                    ratingInputs.forEach(input => {
                        input.addEventListener('change', function() {
                            const value = this.value;
                            const labels = this.closest('.rating-input').querySelectorAll('label');
                            
                            labels.forEach(label => {
                                const labelValue = label.getAttribute('for').replace('star', '');
                                if (labelValue <= value) {
                                    label.classList.add('filled');
                                } else {
                                    label.classList.remove('filled');
                                }
                            });
                        });
                    });
                }
            },
            
            /**
             * Initialize ask question form
             */
            initAskQuestionForm: function() {
                const showQuestionFormBtn = document.getElementById('show-question-form');
                const questionFormContainer = document.getElementById('question-form-container');
                const cancelQuestionBtn = document.getElementById('cancel-question');
                
                if (showQuestionFormBtn && questionFormContainer) {
                    showQuestionFormBtn.addEventListener('click', function() {
                        questionFormContainer.style.display = 'block';
                        this.style.display = 'none';
                    });
                    
                    if (cancelQuestionBtn) {
                        cancelQuestionBtn.addEventListener('click', function() {
                            questionFormContainer.style.display = 'none';
                            showQuestionFormBtn.style.display = 'block';
                        });
                    }
                }
            },
            
            /**
             * Initialize similar products slider
             */
            initSimilarProducts: function() {
                const container = document.querySelector('.recommended-products-scroll');
                const leftBtn = document.querySelector('.scroll-hint.left');
                const rightBtn = document.querySelector('.scroll-hint.right');
                
                if (!container || !leftBtn || !rightBtn) return;
                
                // Function to update arrow visibility
                const updateScrollButtons = () => {
                    leftBtn.classList.toggle('active', container.scrollLeft > 0);
                    rightBtn.classList.toggle('active', container.scrollLeft < container.scrollWidth - container.clientWidth - 10);
                };
                
                // Initial update
                updateScrollButtons();
                
                // Update on scroll
                container.addEventListener('scroll', updateScrollButtons);
                
                // Scroll left button
                leftBtn.addEventListener('click', () => {
                    container.scrollBy({
                        left: -300,
                        behavior: 'smooth'
                    });
                });
                
                // Scroll right button
                rightBtn.addEventListener('click', () => {
                    container.scrollBy({
                        left: 300,
                        behavior: 'smooth'
                    });
                });
                
                // Quick add functionality
                const quickAddButtons = document.querySelectorAll('.btn-quick-add');
                quickAddButtons.forEach(button => {
                    button.addEventListener('click', (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        const productId = button.getAttribute('data-product-id');
                        this.parent.addToCart(productId, 1);
                    });
                });
            },
            
            /**
             * Initialize sticky cart (for mobile devices)
             */
            initStickyCart: function() {
                const stickyCart = document.querySelector('.sticky-cart');
                const productInfo = document.querySelector('.product-info-section');
                
                if (!stickyCart || !productInfo) return;
                
                // Show sticky cart when scrolled past product info
                window.addEventListener('scroll', function() {
                    const rect = productInfo.getBoundingClientRect();
                    
                    if (rect.bottom < 0 && window.innerWidth < 768) {
                        stickyCart.classList.add('visible');
                    } else {
                        stickyCart.classList.remove('visible');
                    }
                });
                
                // Sticky buy button
                if (this.elements.stickyBuyBtn) {
                    this.elements.stickyBuyBtn.addEventListener('click', () => {
                        if (this.elements.stickyBuyBtn.disabled) return;
                        
                        const productId = this.elements.stickyBuyBtn.getAttribute('data-product-id');
                        const quantity = document.getElementById('quantity').value;
                        
                        this.parent.addToCart(productId, quantity);
                    });
                }
            },
            
            /**
             * Initialize add to cart functionality
             */
            initAddToCart: function() {
                if (this.elements.addToCartBtn) {
                    this.elements.addToCartBtn.addEventListener('click', () => {
                        if (this.elements.addToCartBtn.disabled) return;
                        
                        const productId = this.elements.addToCartBtn.getAttribute('data-product-id');
                        const quantity = this.elements.quantityInput.value;
                        
                        this.parent.addToCart(productId, quantity);
                    });
                }
                
                if (this.elements.buyNowBtn) {
                    this.elements.buyNowBtn.addEventListener('click', () => {
                        if (this.elements.buyNowBtn.disabled) return;
                        
                        const productId = this.elements.buyNowBtn.getAttribute('data-product-id');
                        const quantity = this.elements.quantityInput.value;
                        
                        this.parent.addToCart(productId, quantity, true);
                    });
                }
            },
            
            /**
             * Initialize frequently bought together section
             */
            initFrequentlyBoughtTogether: function() {
                if (!this.elements.fbtCheckboxes.length || !this.elements.addAllBtn) return;
                
                // Update total price when checkboxes change
                this.elements.fbtCheckboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', () => this.updateFBTTotal());
                });
                
                // Add all selected products to cart
                this.elements.addAllBtn.addEventListener('click', () => {
                    const addToCartBtn = document.getElementById('add-to-cart-btn');
                    if (!addToCartBtn) return;
                    
                    const mainProduct = addToCartBtn.getAttribute('data-product-id');
                    const quantity = document.getElementById('quantity').value;
                    const selectedProducts = [];
                    
                    // Collect selected products
                    this.elements.fbtCheckboxes.forEach(checkbox => {
                        if (checkbox.checked) {
                            selectedProducts.push({
                                id: checkbox.value,
                                quantity: 1
                            });
                        }
                    });
                    
                    // Add main product
                    this.parent.addToCart(mainProduct, quantity, false, true)
                        .then(() => {
                            // Add other products
                            if (selectedProducts.length > 0) {
                                setTimeout(() => {
                                    this.parent.addMultipleToCart(selectedProducts);
                                }, 300);
                            }
                        })
                        .catch(error => console.error('Error adding main product:', error));
                });
                
                // Initial calculation
                this.updateFBTTotal();
            },
            
            /**
             * Update "Frequently Bought Together" total price
             */
            updateFBTTotal: function() {
                const mainPriceElem = document.querySelector('.current-price');
                const mainPrice = this.getProductPrice(mainPriceElem);
                let totalPrice = mainPrice;
                
                this.elements.fbtCheckboxes.forEach(checkbox => {
                    if (checkbox.checked) {
                        const priceElem = checkbox.closest('.fbt-product').querySelector('.fbt-product-price');
                        const price = this.getProductPrice(priceElem);
                        totalPrice += price;
                    }
                });
                
                // Apply bundle discount (5%)
                const discountedPrice = totalPrice * 0.95;
                const savings = totalPrice - discountedPrice;
                
                // Update display
                const totalAmountElem = document.getElementById('fbt-total-amount');
                const saveAmountElem = document.getElementById('fbt-save-amount');
                
                if (totalAmountElem) totalAmountElem.textContent = this.formatPrice(discountedPrice);
                if (saveAmountElem) saveAmountElem.textContent = this.formatPrice(savings);
            },
            
            /**
             * Get product price from HTML element
             * @param {Element} element - Element containing price
             * @return {number} Price as number
             */
            getProductPrice: function(element) {
                if (!element) return 0;
                
                // Try to get price from data attribute first
                if (element.hasAttribute('data-price')) {
                    return parseFloat(element.getAttribute('data-price'));
                }
                
                // If no data attribute, parse from text
                const priceText = element.textContent.trim();
                const price = parseFloat(priceText.replace(/[^0-9]/g, ''));
                return !isNaN(price) ? price : 0;
            },
            
            /**
             * Format price with Serbian formatting
             * @param {number} price - Price to format
             * @return {string} Formatted price
             */
            formatPrice: function(price) {
                return new Intl.NumberFormat('sr-RS').format(Math.round(price)) + ' RSD';
            }
        },

        /**
         * Checkout page specific functionality
         */
        CheckoutPage: {
            // Reference to parent object
            parent: null,
            
            // Elements cache
            elements: {},
            
            /**
             * Initialize checkout page
             */
            init: function() {
                this.parent = HugongShop;
                this.cacheElements();
                
                this.initPaymentOptions();
                this.initDeliveryOptions();
                this.initQuantityControls();
                this.initUpsellProducts();
                this.initRemoveProduct();
                this.initPlaceOrder();
                this.initFormValidation();
            },
            
            /**
             * Cache checkout page DOM elements
             */
            cacheElements: function() {
                // Payment options
                this.elements.paymentOptions = document.querySelectorAll('.payment-option');
                
                // Delivery options
                this.elements.deliveryOptions = document.querySelectorAll('.delivery-option');
                
                // Product quantity
                this.elements.quantityControls = document.querySelectorAll('.product-item .quantity');
                
                // Upsell products
                this.elements.upsellProducts = document.querySelectorAll('.upsell-product');
                
                // Remove buttons
                this.elements.removeButtons = document.querySelectorAll('.remove-product-btn');
                
                // Form and submit button
                this.elements.checkoutForm = document.getElementById('checkout-form');
                this.elements.placeOrderBtn = document.getElementById('place-order');
                
                // Email input for validation
                this.elements.emailInput = document.getElementById('email');
            },
            
            /**
             * Initialize payment options
             */
            initPaymentOptions: function() {
                if (!this.elements.paymentOptions.length) return;
                
                this.elements.paymentOptions.forEach(option => {
                    option.addEventListener('click', function() {
                        // Remove selected class from all options
                        document.querySelectorAll('.payment-option').forEach(opt => {
                            opt.classList.remove('selected');
                            const radio = opt.querySelector('input[type="radio"]');
                            if (radio) radio.checked = false;
                        });
                        
                        // Add selected class to clicked option
                        this.classList.add('selected');
                        
                        // Check radio button
                        const radio = this.querySelector('input[type="radio"]');
                        if (radio) radio.checked = true;
                    });
                });
            },
            
            /**
             * Initialize delivery options
             */
            initDeliveryOptions: function() {
                if (!this.elements.deliveryOptions.length) return;
                
                this.elements.deliveryOptions.forEach(option => {
                    option.addEventListener('click', function() {
                        // Remove selected class from all options
                        document.querySelectorAll('.delivery-option').forEach(opt => {
                            opt.classList.remove('selected');
                            const radio = opt.querySelector('input[type="radio"]');
                            if (radio) radio.checked = false;
                        });
                        
                        // Add selected class to clicked option
                        this.classList.add('selected');
                        
                        // Check radio button
                        const radio = this.querySelector('input[type="radio"]');
                        if (radio) radio.checked = true;
                    });
                });
            },
            
            /**
             * Initialize quantity controls
             */
            initQuantityControls: function() {
                if (!this.elements.quantityControls.length) return;
                
                this.elements.quantityControls.forEach(control => {
                    const minusBtn = control.querySelector('.minus-btn');
                    const plusBtn = control.querySelector('.plus-btn');
                    const input = control.querySelector('.quantity-input');
                    const productItem = control.closest('.product-item');
                    const productId = productItem.getAttribute('data-product-id');
                    const priceElement = productItem.querySelector('.product-price');
                    const unitPrice = parseFloat(priceElement.getAttribute('data-unit-price') || 0);
                    
                    // Minus button click
                    if (minusBtn) {
                        minusBtn.addEventListener('click', () => {
                            let value = parseInt(input.value);
                            if (value > 1) {
                                value--;
                                this.updateQuantity(productId, value, unitPrice, priceElement, input);
                            }
                        });
                    }
                    
                    // Plus button click
                    if (plusBtn) {
                        plusBtn.addEventListener('click', () => {
                            let value = parseInt(input.value);
                            value++;
                            this.updateQuantity(productId, value, unitPrice, priceElement, input);
                        });
                    }
                });
            },
            
            /**
             * Update quantity via AJAX
             */
            updateQuantity: function(productId, quantity, unitPrice, priceElement, inputElement) {
                const formData = new FormData();
                formData.append('product_id', productId);
                formData.append('quantity', quantity);
                
                if (this.parent.config.csrfToken) {
                    formData.append('csrf_token', this.parent.config.csrfToken);
                }
                
                fetch('/update-cart.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // Update displayed quantity
                        inputElement.value = quantity;
                        
                        // Update product subtotal
                        priceElement.textContent = data.subtotal;
                        
                        // Update cart count
                        const cartCountElements = document.querySelectorAll('.cart-count');
                        cartCountElements.forEach(el => {
                            el.textContent = data.cart_count;
                        });
                        
                        // Update summary amounts
                        const productsTotal = document.querySelector('#cart-subtotal');
                        if (productsTotal) productsTotal.textContent = data.cart_subtotal;
                        
                        // Update grand total
                        const grandTotal = document.getElementById('grand-total');
                        if (grandTotal) grandTotal.textContent = data.cart_total;
                        
                        // Update base price hidden input
                        const basePrice = document.getElementById('base-price');
                        if (basePrice) {
                            const numericTotal = parseFloat(data.cart_subtotal.replace(/[^\d,]/g, '').replace(',', '.'));
                            basePrice.value = numericTotal;
                        }
                        
                        // Update totals
                        this.updateCheckoutTotal();
                    }
                })
                .catch(error => {
                    console.error('Error updating quantity:', error);
                });
            },
            
            /**
             * Initialize upsell products
             */
            initUpsellProducts: function() {
                if (!this.elements.upsellProducts.length) return;
                
                this.elements.upsellProducts.forEach(product => {
                    // Allow clicking on entire product
                    product.addEventListener('click', () => {
                        this.toggleUpsellProduct(product);
                    });
                    
                    // Dedicated event listener for button
                    const addBtn = product.querySelector('.upsell-add');
                    if (addBtn) {
                        addBtn.addEventListener('click', (e) => {
                            e.stopPropagation(); // Prevent propagation to parent
                            this.toggleUpsellProduct(product);
                        });
                    }
                });
            },
            
            /**
             * Toggle upsell product selection
             */
            toggleUpsellProduct: function(product) {
                product.classList.toggle('selected');
                
                const addBtn = product.querySelector('.upsell-add');
                if (product.classList.contains('selected')) {
                    addBtn.innerHTML = '<span>✓</span>';
                } else {
                    addBtn.innerHTML = '<span>+</span>';
                }
                
                // Update totals
                this.updateCheckoutTotal();
            },
            
            /**
             * Initialize remove product buttons
             */
            initRemoveProduct: function() {
                if (!this.elements.removeButtons.length) return;
                
                this.elements.removeButtons.forEach(button => {
                    button.addEventListener('click', () => {
                        const productId = button.getAttribute('data-product-id');
                        if (!productId) {
                            console.error('Product ID not found!');
                            return;
                        }
                        
                        const formData = new FormData();
                        formData.append('product_id', productId);
                        
                        if (this.parent.config.csrfToken) {
                            formData.append('csrf_token', this.parent.config.csrfToken);
                        }
                        
                        fetch('/remove-from-cart.php', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`HTTP error! status: ${response.status}`);
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data.success) {
                                // Either reload the page or remove the item from DOM
                                window.location.reload();
                            } else {
                                console.error('Error removing item:', data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Error removing item:', error);
                        });
                    });
                });
            },
            
            /**
             * Initialize place order button
             */
            initPlaceOrder: function() {
                if (!this.elements.placeOrderBtn || !this.elements.checkoutForm) return;
                
                this.elements.placeOrderBtn.addEventListener('click', (e) => {
                    e.preventDefault();

                    // Form validation
                    if (!this.validateForm()) {
                        return;
                    }

                    // Add selected accessories as hidden fields
                    const selectedAccessories = document.querySelectorAll('.upsell-product.selected');
                    if (selectedAccessories.length > 0) {
                        const accessoriesArray = [];
                        selectedAccessories.forEach(product => {
                            accessoriesArray.push(product.getAttribute('data-product-id'));
                        });
                        
                        const accessoriesInput = document.createElement('input');
                        accessoriesInput.type = 'hidden';
                        accessoriesInput.name = 'accessories';
                        accessoriesInput.value = JSON.stringify(accessoriesArray);
                        this.elements.checkoutForm.appendChild(accessoriesInput);
                    }
                    
                    // Submit form
                    this.elements.checkoutForm.submit();
                });
            },
            
            /**
             * Initialize form validation
             */
            initFormValidation: function() {
                // Email validation
                if (this.elements.emailInput) {
                    let emailWasFocused = false;
                    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    
                    // Track if email field has been focused
                    this.elements.emailInput.addEventListener('focus', function() {
                        emailWasFocused = true;
                    });
                    
                    // Validate on blur
                    this.elements.emailInput.addEventListener('blur', () => {
                        this.validateEmail(emailWasFocused, emailPattern);
                    });
                    
                    // Validate on input if already marked invalid
                    this.elements.emailInput.addEventListener('input', () => {
                        if (this.elements.emailInput.classList.contains('is-invalid') || emailWasFocused) {
                            this.validateEmail(emailWasFocused, emailPattern);
                        }
                    });
                }
            },
            
            /**
             * Validate email field
             */
            validateEmail: function(emailWasFocused, emailPattern) {
                const email = this.elements.emailInput.value.trim();
                
                // If empty and never focused, don't show error
                if (email === '' && !emailWasFocused) {
                    this.elements.emailInput.classList.remove('is-invalid');
                    this.elements.emailInput.classList.remove('is-valid');
                    
                    // Remove error message if exists
                    const errorEl = this.elements.emailInput.nextElementSibling;
                    if (errorEl && errorEl.classList.contains('error-message')) {
                        errorEl.remove();
                    }
                    return true;
                }
                
                // If was focused and now empty, treat as error
                if (email === '' && emailWasFocused) {
                    this.elements.emailInput.classList.remove('is-valid');
                    this.elements.emailInput.classList.add('is-invalid');
                    
                    // Add error message if doesn't exist
                    let errorEl = this.elements.emailInput.nextElementSibling;
                    if (!errorEl || !errorEl.classList.contains('error-message')) {
                        errorEl = document.createElement('div');
                        errorEl.classList.add('error-message');
                        errorEl.innerHTML = 'Molimo unesite email adresu';
                        this.elements.emailInput.parentNode.insertBefore(errorEl, this.elements.emailInput.nextSibling);
                    } else {
                        errorEl.innerHTML = 'Molimo unesite email adresu';
                    }
                    return false;
                }
                
                // Check email format
                if (emailPattern.test(email)) {
                    this.elements.emailInput.classList.remove('is-invalid');
                    this.elements.emailInput.classList.add('is-valid');
                    
                    // Remove error message if exists
                    const errorEl = this.elements.emailInput.nextElementSibling;
                    if (errorEl && errorEl.classList.contains('error-message')) {
                        errorEl.remove();
                    }
                    return true;
                } else {
                    this.elements.emailInput.classList.remove('is-valid');
                    this.elements.emailInput.classList.add('is-invalid');
                    
                    // Add error message if doesn't exist
                    let errorEl = this.elements.emailInput.nextElementSibling;
                    if (!errorEl || !errorEl.classList.contains('error-message')) {
                        errorEl = document.createElement('div');
                        errorEl.classList.add('error-message');
                        errorEl.innerHTML = 'Unesite ispravnu email adresu';
                        this.elements.emailInput.parentNode.insertBefore(errorEl, this.elements.emailInput.nextSibling);
                    } else {
                        errorEl.innerHTML = 'Unesite ispravnu email adresu';
                    }
                    return false;
                }
            },
            
            /**
             * Validate entire form
             */
            validateForm: function() {
                const requiredFields = this.elements.checkoutForm.querySelectorAll('[required]');
                let isValid = true;
                let firstInvalidField = null;
                
                // Check required fields
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        field.classList.add('is-invalid');
                        
                        // Add error message if doesn't exist
                        let errorEl = field.nextElementSibling;
                        if (!errorEl || !errorEl.classList.contains('error-message')) {
                            errorEl = document.createElement('div');
                            errorEl.classList.add('error-message');
                            errorEl.innerHTML = 'Ovo polje je obavezno';
                            field.parentNode.insertBefore(errorEl, field.nextSibling);
                        }
                        
                        if (!firstInvalidField) {
                            firstInvalidField = field;
                        }
                        
                        isValid = false;
                    } else {
                        field.classList.remove('is-invalid');
                        
                        // Remove error message if exists
                        const errorEl = field.nextElementSibling;
                        if (errorEl && errorEl.classList.contains('error-message')) {
                            errorEl.remove();
                        }
                    }
                });
                
                // Validate email if present
                if (this.elements.emailInput && !this.validateEmail(true, /^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
                    isValid = false;
                    if (!firstInvalidField) {
                        firstInvalidField = this.elements.emailInput;
                    }
                }
                
                // If there are errors, scroll to first invalid field
                if (firstInvalidField) {
                    this.scrollToElement(firstInvalidField);
                    firstInvalidField.focus();
                }

                return isValid;
            },
            
            /**
             * Scroll to element
             */
            scrollToElement: function(element) {
                // Calculate position relative to document
                const elementRect = element.getBoundingClientRect();
                const absoluteElementTop = elementRect.top + window.pageYOffset;
                
                // Scroll to element (slightly above for better visibility)
                window.scrollTo({
                    top: absoluteElementTop - 100,
                    behavior: 'smooth'
                });
            },
            
            /**
             * Update checkout total
             */
            updateCheckoutTotal: function() {
                // Calculate products total
                let cartSubtotal = 0;
                document.querySelectorAll('.product-item').forEach(item => {
                    const priceElement = item.querySelector('.product-price');
                    const quantityInput = item.querySelector('.quantity-input');
                    const unitPrice = parseFloat(priceElement.getAttribute('data-unit-price') || 0);
                    const quantity = parseInt(quantityInput.value || 1);
                    
                    // Calculate subtotal for this product
                    const itemSubtotal = unitPrice * quantity;
                    
                    // Update displayed price for this product
                    priceElement.textContent = this.formatPrice(itemSubtotal);
                    
                    cartSubtotal += itemSubtotal;
                });
                
                // Calculate accessories price
                let accessoriesTotal = 0;
                document.querySelectorAll('.upsell-product.selected').forEach(product => {
                    const price = parseFloat(product.getAttribute('data-price') || 0);
                    accessoriesTotal += price;
                });
                
                // Update displayed prices
                const cartSubtotalElement = document.getElementById('cart-subtotal');
                const accessoriesTotalElement = document.getElementById('accessories-total');
                const grandTotalElement = document.getElementById('grand-total');
                
                if (cartSubtotalElement) {
                    cartSubtotalElement.textContent = this.formatPrice(cartSubtotal);
                }
                
                if (accessoriesTotalElement) {
                    accessoriesTotalElement.textContent = this.formatPrice(accessoriesTotal);
                }
                
                if (grandTotalElement) {
                    const grandTotal = cartSubtotal + accessoriesTotal;
                    grandTotalElement.textContent = this.formatPrice(grandTotal);
                }
                
                // Update base price input
                const basePriceInput = document.getElementById('base-price');
                if (basePriceInput) {
                    basePriceInput.value = cartSubtotal;
                }
            },
            
            /**
             * Format price
             */
            formatPrice: function(price) {
                return price.toFixed(2).replace('.', ',') + ' RSD';
            }
        },

        /**
         * Cart page specific functionality
         */
        CartPage: {
            // Reference to parent object
            parent: null,
            
            /**
             * Initialize cart page
             */
            init: function() {
                this.parent = HugongShop;
                
                this.initQuantityUpdates();
                this.initRemoveButtons();
                this.initCouponCode();
            },
            
            /**
             * Initialize quantity update
             */
            initQuantityUpdates: function() {
                const quantityInputs = document.querySelectorAll('.cart-quantity input');
                
                if (!quantityInputs.length) return;
                
                quantityInputs.forEach(input => {
                    input.addEventListener('change', function() {
                        const productId = this.getAttribute('data-product-id');
                        const quantity = this.value;
                        
                        if (quantity < 1) {
                            this.value = 1;
                            return;
                        }
                        
                        // Update cart via AJAX
                        fetch('/update-cart.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: `product_id=${productId}&quantity=${quantity}`
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // Update subtotal
                                document.getElementById(`subtotal-${productId}`).textContent = data.subtotal;
                                
                                // Update cart totals
                                document.getElementById('cart-subtotal').textContent = data.cart_subtotal;
                                document.getElementById('cart-total').textContent = data.cart_total;
                                
                                // Update cart count in header
                                document.querySelector('.cart-count').textContent = data.cart_count;
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                    });
                });
            },
            
            /**
             * Initialize remove buttons
             */
            initRemoveButtons: function() {
                const removeButtons = document.querySelectorAll('.cart-remove');
                
                if (!removeButtons.length) return;
                
                removeButtons.forEach(button => {
                    button.addEventListener('click', function() {
                        const productId = this.getAttribute('data-product-id');
                        
                        // Remove product via AJAX
                        fetch('/remove-from-cart.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: `product_id=${productId}`
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // Remove product row
                                this.closest('tr').remove();
                                
                                // Update cart totals
                                document.getElementById('cart-subtotal').textContent = data.cart_subtotal;
                                document.getElementById('cart-total').textContent = data.cart_total;
                                
                                // Update cart count in header
                                document.querySelector('.cart-count').textContent = data.cart_count;
                                
                                // Show empty cart message if no products left
                                if (data.cart_count === 0) {
                                    document.querySelector('.cart-table').style.display = 'none';
                                    document.querySelector('.cart-actions').style.display = 'none';
                                    document.querySelector('.cart-summary').style.display = 'none';
                                    document.querySelector('.cart-page').innerHTML = '<div class="empty-cart"><h2>Vaša korpa je prazna</h2><p>Nemate proizvode u korpi. <a href="/">Nastavite kupovinu</a>.</p></div>';
                                }
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                    });
                });
            },
            
            /**
             * Initialize coupon code
             */
            initCouponCode: function() {
                const applyCouponBtn = document.getElementById('apply-coupon');
                
                if (!applyCouponBtn) return;
                
                applyCouponBtn.addEventListener('click', function() {
                    const couponCode = document.getElementById('coupon-code').value.trim();
                    
                    if (!couponCode) {
                        return;
                    }
                    
                    // Apply coupon via AJAX
                    fetch('/apply-coupon.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: `coupon_code=${couponCode}`
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Update cart totals
                            document.getElementById('cart-subtotal').textContent = data.cart_subtotal;
                            document.getElementById('cart-discount').textContent = data.cart_discount;
                            document.getElementById('cart-total').textContent = data.cart_total;
                            
                            // Show success message
                            alert('Kupon je uspešno primenjen.');
                        } else {
                            alert(data.message || 'Neispravan kupon kod.');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Došlo je do greške prilikom primene kupona.');
                    });
                });
            }
        },

        /**
         * Home page specific functionality
         */
        HomePage: {
            // Reference to parent object
            parent: null,
            
            /**
             * Initialize home page
             */
            init: function() {
                this.parent = HugongShop;
                
                this.initHeroSlider();
                this.initTestimonialSlider();
            },
            
            /**
             * Initialize hero slider
             */
            initHeroSlider: function() {
                const heroSlides = document.querySelectorAll('.hero-slide');
                const heroDots = document.querySelectorAll('.hero-dots .dot');
                const heroPrev = document.querySelector('.hero-prev');
                const heroNext = document.querySelector('.hero-next');
                
                if (!heroSlides.length) return;
                
                let currentSlide = 0;
                const totalSlides = heroSlides.length;
                let slideInterval;
                
                const showSlide = (index) => {
                    // Hide all slides
                    heroSlides.forEach(slide => {
                        slide.classList.remove('active');
                    });
                    
                    // Deactivate all dots
                    heroDots.forEach(dot => {
                        dot.classList.remove('active');
                    });
                    
                    // Show the selected slide
                    heroSlides[index].classList.add('active');
                    if (heroDots[index]) heroDots[index].classList.add('active');
                    
                    // Update current slide
                    currentSlide = index;
                };
                
                const nextSlide = () => {
                    showSlide((currentSlide + 1) % totalSlides);
                };
                
                const prevSlide = () => {
                    showSlide((currentSlide - 1 + totalSlides) % totalSlides);
                };
                
                // Event listeners for controls
                if (heroPrev) {
                    heroPrev.addEventListener('click', prevSlide);
                }
                
                if (heroNext) {
                    heroNext.addEventListener('click', nextSlide);
                }
                
                // Event listeners for dots
                heroDots.forEach((dot, index) => {
                    dot.addEventListener('click', () => {
                        showSlide(index);
                        resetInterval();
                    });
                });
                
                // Auto rotation
                const startInterval = () => {
                    slideInterval = setInterval(nextSlide, 5000);
                };
                
                const resetInterval = () => {
                    clearInterval(slideInterval);
                    startInterval();
                };
                
                startInterval();
                
                // Pause auto rotation when hovering over the slider
                const heroSlider = document.querySelector('.hero-slider');
                if (heroSlider) {
                    heroSlider.addEventListener('mouseenter', () => {
                        clearInterval(slideInterval);
                    });
                    
                    heroSlider.addEventListener('mouseleave', startInterval);
                }
            },
            
            /**
             * Initialize testimonial slider
             */
            initTestimonialSlider: function() {
                const testimonialSlides = document.querySelectorAll('.testimonial-slide');
                const testimonialDots = document.querySelectorAll('.testimonial-dots .dot');
                const prevTestimonialBtn = document.querySelector('.testimonial-prev');
                const nextTestimonialBtn = document.querySelector('.testimonial-next');
                
                if (!testimonialSlides.length) return;
                
                let currentTestimonial = 0;
                const totalTestimonials = testimonialSlides.length;
                let testimonialInterval;
                
                const showTestimonial = (index) => {
                    // Hide all slides
                    testimonialSlides.forEach(slide => {
                        slide.classList.remove('active');
                    });
                    
                    // Deactivate all dots
                    testimonialDots.forEach(dot => {
                        dot.classList.remove('active');
                    });
                    
                    // Show the selected slide
                    testimonialSlides[index].classList.add('active');
                    if (testimonialDots[index]) testimonialDots[index].classList.add('active');
                    
                    // Update current slide
                    currentTestimonial = index;
                };
                
                const nextTestimonial = () => {
                    showTestimonial((currentTestimonial + 1) % totalTestimonials);
                };
                
                const prevTestimonial = () => {
                    showTestimonial((currentTestimonial - 1 + totalTestimonials) % totalTestimonials);
                };
                
                // Event listeners for controls
                if (prevTestimonialBtn) {
                    prevTestimonialBtn.addEventListener('click', () => {
                        prevTestimonial();
                        resetInterval();
                    });
                }
                
                if (nextTestimonialBtn) {
                    nextTestimonialBtn.addEventListener('click', () => {
                        nextTestimonial();
                        resetInterval();
                    });
                }
                
                // Event listeners for dots
                testimonialDots.forEach((dot, index) => {
                    dot.addEventListener('click', () => {
                        showTestimonial(index);
                        resetInterval();
                    });
                });
                
                // Auto rotation
                const startInterval = () => {
                    testimonialInterval = setInterval(nextTestimonial, 5000);
                };
                
                const resetInterval = () => {
                    clearInterval(testimonialInterval);
                    startInterval();
                };
                
                startInterval();
                
                // Pause auto rotation when hovering over the slider
                const testimonialSlider = document.querySelector('.testimonials-slider');
                if (testimonialSlider) {
                    testimonialSlider.addEventListener('mouseenter', () => {
                        clearInterval(testimonialInterval);
                    });
                    
                    testimonialSlider.addEventListener('mouseleave', startInterval);
                }
            }
        },
    };

    // Initialize the application
    HugongShop.init();
    
    // Expose functions for global use
    window.HugongShop = HugongShop;
    window.openModal = HugongShop.openModal.bind(HugongShop);
    window.closeModal = HugongShop.closeModal.bind(HugongShop);
});