document.addEventListener('DOMContentLoaded', function() {
    // ====== Mobile menu functionality (fixed) ======
    const menuBtn = document.getElementById('mobile-menu-button');
    const mobileNav = document.getElementById('mobile-nav');
    
    if(menuBtn && mobileNav) {
        // Create overlay if it doesn't exist
        let overlay = document.querySelector('.menu-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.className = 'menu-overlay';
            document.body.appendChild(overlay);
        }
        
        menuBtn.addEventListener('click', function() {
            mobileNav.classList.toggle('active');
            overlay.classList.toggle('active');
            document.body.classList.toggle('no-scroll');
            menuBtn.classList.toggle('active');
        });
        
        overlay.addEventListener('click', function() {
            mobileNav.classList.remove('active');
            overlay.classList.remove('active');
            document.body.classList.remove('no-scroll');
            menuBtn.classList.remove('active');
        });
        
        // Close button inside mobile nav
        const closeBtn = document.querySelector('.mobile-close-btn');
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                mobileNav.classList.remove('active');
                overlay.classList.remove('active');
                document.body.classList.remove('no-scroll');
                menuBtn.classList.remove('active');
            });
        }
    }
    
    // ====== Back to top button ======
    const backToTopButton = document.getElementById('back-to-top');
    
    if (backToTopButton) {
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                backToTopButton.classList.add('visible');
            } else {
                backToTopButton.classList.remove('visible');
            }
        });
        
        backToTopButton.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }
    
    // ====== Product page functionality ======
    if (document.querySelector('.product-section')) {
        // Quantity buttons
        const minusBtn = document.querySelector('.minus-btn');
        const plusBtn = document.querySelector('.plus-btn');
        const quantityInput = document.getElementById('product-quantity');
        
        if (minusBtn && plusBtn && quantityInput) {
            minusBtn.addEventListener('click', function() {
                let value = parseInt(quantityInput.value);
                if (value > 1) {
                    value--;
                    quantityInput.value = value;
                }
            });
            
            plusBtn.addEventListener('click', function() {
                let value = parseInt(quantityInput.value);
                value++;
                quantityInput.value = value;
            });
        }
        
        // Product thumbnails
        const thumbs = document.querySelectorAll('.thumb');
        const mainImage = document.getElementById('main-image');
        
        if (thumbs.length && mainImage) {
            thumbs.forEach(thumb => {
                thumb.addEventListener('click', function() {
                    // Remove active class from all thumbnails
                    thumbs.forEach(t => t.classList.remove('active'));
                    // Add active class to clicked thumbnail
                    this.classList.add('active');
                    // Change main image
                    mainImage.src = this.getAttribute('data-img');
                    mainImage.alt = this.querySelector('img').alt;
                });
            });
        }
        
        // Product tabs
        const tabLinks = document.querySelectorAll('.tab-link');
        const tabContents = document.querySelectorAll('.tab-content');
        
        if (tabLinks.length && tabContents.length) {
            tabLinks.forEach(link => {
                link.addEventListener('click', function() {
                    // Remove active class from all tabs
                    tabLinks.forEach(t => t.classList.remove('active'));
                    tabContents.forEach(t => t.classList.remove('active'));
                    
                    // Add active class to clicked tab
                    this.classList.add('active');
                    // Show corresponding content
                    document.getElementById(this.getAttribute('data-tab')).classList.add('active');
                });
            });
        }
        
        // Buy now button
        const addToCartBtn = document.getElementById('order-now');
        
        if (addToCartBtn) {
            addToCartBtn.addEventListener('click', function() {
                const productId = this.getAttribute('data-product-id');
                const quantity = document.getElementById('product-quantity').value;
                
fetch('/add-to-cart.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: `product_id=${productId}&quantity=${quantity}`
})
.then(response => {
    console.log('Full response:', response);
    // Provera statusa pre parsiranja
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.text(); // Prvo pročitaj kao tekst
})
.then(text => {
    console.log('Response text:', text);
    return JSON.parse(text); // Ručno parsiraj JSON
})
.then(data => {
    console.log('Parsed data:', data);
    // Dalja logika...
})
.catch(error => {
    console.error('Kompletan error:', error);
});


            });
        }
    }
    
    // ====== Checkout page functionality ======
    if (document.querySelector('.checkout-form')) {
        // Payment options
        const paymentOptions = document.querySelectorAll('.payment-option');
        
        if (paymentOptions.length) {
            paymentOptions.forEach(option => {
                option.addEventListener('click', function() {
                    paymentOptions.forEach(opt => opt.classList.remove('selected'));
                    this.classList.add('selected');
                });
            });
        }
        
        // Delivery options
        const deliveryOptions = document.querySelectorAll('.delivery-option');
        
        if (deliveryOptions.length) {
            deliveryOptions.forEach(option => {
                option.addEventListener('click', function() {
                    deliveryOptions.forEach(opt => opt.classList.remove('selected'));
                    this.classList.add('selected');
                    const radio = this.querySelector('input[type="radio"]');
                    radio.checked = true;
                });
            });
        }
        
        // Upsell products
        const upsellProducts = document.querySelectorAll('.upsell-product');
        
        if (upsellProducts.length) {
            upsellProducts.forEach(product => {
                product.addEventListener('click', function() {
                    this.classList.toggle('selected');
                    
                    const addBtn = this.querySelector('.upsell-add');
                    if (this.classList.contains('selected')) {
                        addBtn.innerHTML = '<span>✓</span>';
                    } else {
                        addBtn.innerHTML = '<span>+</span>';
                    }
                    
                    // Update total
                    updateCheckoutTotal();
                });
            });
        }
        
        // Function to update checkout total
        function updateCheckoutTotal() {
            // Get base price
            let basePrice = parseFloat(document.getElementById('base-price').value);
            
            // Get selected accessories
            let accessoriesTotal = 0;
            document.querySelectorAll('.upsell-product.selected').forEach(product => {
                const price = parseFloat(product.getAttribute('data-price'));
                accessoriesTotal += price;
            });
            
            // Update accessories total
            document.getElementById('accessories-total').textContent = formatPrice(accessoriesTotal);
            
            // Calculate grand total
            const grandTotal = basePrice + accessoriesTotal;
            document.getElementById('grand-total').textContent = formatPrice(grandTotal);
        }
        
        // Format price
        function formatPrice(price) {
            return price.toLocaleString('sr-RS').replace('.', ',') + ',00 rsd';
        }
        
        // Place order button
        const placeOrderBtn = document.getElementById('place-order');
        
        if (placeOrderBtn) {
            placeOrderBtn.addEventListener('click', function(e) {
                e.preventDefault();
                
                // Validate form
                if (!validateCheckoutForm()) {
                    return;
                }
                
                // Collect form data
                const formData = new FormData(document.getElementById('checkout-form'));
                
                // Add selected accessories
                const accessories = [];
                document.querySelectorAll('.upsell-product.selected').forEach(product => {
                    accessories.push(product.getAttribute('data-product-id'));
                });
                formData.append('accessories', JSON.stringify(accessories));
                
                // Submit order via AJAX
                fetch('/process-order.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = '/thank-you.php?order_id=' + data.order_id;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            });
        }
        
        // Validate checkout form
        function validateCheckoutForm() {
            const requiredFields = document.querySelectorAll('input[required], select[required], textarea[required]');
            let valid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    valid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            return valid;
        }
    }
    
    // ====== Cart page functionality ======
    if (document.querySelector('.cart-page')) {
        // Quantity update
        const quantityInputs = document.querySelectorAll('.cart-quantity input');
        
        if (quantityInputs.length) {
            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);
                    });
                });
            });
        }
        
        // Remove product from cart
        const removeButtons = document.querySelectorAll('.cart-remove');
        
        if (removeButtons.length) {
            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);
                    });
                });
            });
        }
        
        // Apply coupon
        const applyCouponBtn = document.getElementById('apply-coupon');
        
        if (applyCouponBtn) {
            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.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            });
        }
    }
    
    // ====== Remove product functionality (checkout page) ======
    const removeButtons = document.querySelectorAll('.remove-product-btn');
    
    if (removeButtons.length) {
        removeButtons.forEach(button => {
            button.addEventListener('click', function() {
                const productId = this.getAttribute('data-product-id');
                const productItem = this.closest('.product-item');
                
                // 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 item from UI
                        productItem.remove();
                        
                        // Update cart count in header
                        document.querySelector('.cart-count').textContent = data.cart_count;
                        
                        // Update totals
                        const cartSubtotal = document.getElementById('cart-subtotal');
                        if (cartSubtotal) cartSubtotal.textContent = data.cart_subtotal;
                        
                        document.getElementById('grand-total').textContent = data.cart_total;
                        
                        // If only one product left, reload page to hide remove buttons
                        const remainingItems = document.querySelectorAll('.product-item');
                        if (remainingItems.length <= 1) {
                            location.reload();
                        }
                        
                        // Redirect if cart is empty
                        if (data.cart_count === 0) {
                            window.location.href = '/cart.php';
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            });
        });
    }
    
    // ====== Handle quantity changes (checkout page) ======
    const quantityControls = document.querySelectorAll('.product-item .quantity');
    if (quantityControls.length) {
        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'));
            
            // Minus button click
            minusBtn.addEventListener('click', function() {
                let value = parseInt(input.value);
                if (value > 1) {
                    value--;
                    updateQuantity(productId, value, unitPrice, priceElement, input);
                }
            });
            
            // Plus button click
            plusBtn.addEventListener('click', function() {
                let value = parseInt(input.value);
                if (value < 10) {
                    value++;
                    updateQuantity(productId, value, unitPrice, priceElement, input);
                }
            });
        });
        
        function updateQuantity(productId, quantity, unitPrice, priceElement, inputElement) {
            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 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('.summary-line:first-child span:last-child');
                    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;
                    }
                    
                    // Force any other calculations that depend on totals
                    if (typeof updateCheckoutTotal === 'function') {
                        updateCheckoutTotal();
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    }
    
    // ====== Testimonial slider ======
    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 > 0) {
        let currentTestimonial = 0;
        const totalTestimonials = testimonialSlides.length;
        
        function 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');
            testimonialDots[index].classList.add('active');
            
            // Update current slide
            currentTestimonial = index;
        }
        
        function nextTestimonial() {
            showTestimonial((currentTestimonial + 1) % totalTestimonials);
        }
        
        function prevTestimonial() {
            showTestimonial((currentTestimonial - 1 + totalTestimonials) % totalTestimonials);
        }
        
        // Event listeners for controls
        if (prevTestimonialBtn) {
            prevTestimonialBtn.addEventListener('click', prevTestimonial);
        }
        
        if (nextTestimonialBtn) {
            nextTestimonialBtn.addEventListener('click', nextTestimonial);
        }
        
        // Event listeners for dots
        testimonialDots.forEach((dot, index) => {
            dot.addEventListener('click', () => {
                showTestimonial(index);
            });
        });
        
        // Auto rotation every 5 seconds
        let testimonialInterval = setInterval(nextTestimonial, 5000);
        
        // Pause auto rotation when hovering over the slider
        const testimonialSlider = document.querySelector('.testimonials-slider');
        if (testimonialSlider) {
            testimonialSlider.addEventListener('mouseenter', () => {
                clearInterval(testimonialInterval);
            });
            
            testimonialSlider.addEventListener('mouseleave', () => {
                testimonialInterval = setInterval(nextTestimonial, 5000);
            });
        }
    }
    
    // ====== Hero slider ======
    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 > 0) {
        let currentSlide = 0;
        const totalSlides = heroSlides.length;
        
        function 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');
            heroDots[index].classList.add('active');
            
            // Update current slide
            currentSlide = index;
        }
        
        function nextSlide() {
            showSlide((currentSlide + 1) % totalSlides);
        }
        
        function 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);
            });
        });
        
        // Auto rotation every 5 seconds
        let slideInterval = setInterval(nextSlide, 5000);
        
        // Pause auto rotation when hovering over the slider
        const heroSlider = document.querySelector('.hero-slider');
        if (heroSlider) {
            heroSlider.addEventListener('mouseenter', () => {
                clearInterval(slideInterval);
            });
            
            heroSlider.addEventListener('mouseleave', () => {
                slideInterval = setInterval(nextSlide, 5000);
            });
        }
    }
    
    // ====== Smooth scroll for anchor links ======
    const scrollLinks = document.querySelectorAll('.scroll-to');
    
    scrollLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 100,
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // ====== Active menu item highlighting ======
    const currentLocation = window.location.href;
    const menuItems = document.querySelectorAll('.nav-menu li a');
    
    menuItems.forEach(item => {
        if (currentLocation.includes(item.getAttribute('href'))) {
            item.parentElement.classList.add('active');
        }
    });
    
    // ====== Price Match form handling ======
    if (typeof $ !== 'undefined') {
        // File input custom behavior
        $('.custom-file-input').on('change', function() {
            let fileName = $(this).val().split('\\').pop();
            $(this).next('.custom-file-label').text(fileName);
        });
        
        // Form submission
        $('#priceMatchForm').on('submit', function(e) {
            e.preventDefault();
            
            var formData = new FormData(this);
            
            $.ajax({
                url: '/ajax/price-match.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.status === 'success') {
                        $('#priceMatchRequestModal').modal('hide');
                        alert(response.message);
                    } else {
                        alert('Greška: ' + response.message);
                    }
                },
                error: function() {
                    alert('Došlo je do greške. Molimo pokušajte ponovo.');
                }
            });
        });
    }
});







// Add this to your script.js file

document.addEventListener('DOMContentLoaded', function() {
    // Mobile Navigation Toggle
    const menuToggle = document.getElementById('mobile-menu-toggle');
    const mobileDrawer = document.getElementById('mobile-nav-drawer');
    const drawerClose = document.getElementById('drawer-close');
    const overlay = document.getElementById('mobile-nav-overlay');
    
    if (menuToggle && mobileDrawer && overlay) {
        menuToggle.addEventListener('click', function() {
            mobileDrawer.classList.add('active');
            document.body.classList.add('drawer-open');
        });
        
        drawerClose.addEventListener('click', function() {
            mobileDrawer.classList.remove('active');
            document.body.classList.remove('drawer-open');
        });
        
        overlay.addEventListener('click', function() {
            mobileDrawer.classList.remove('active');
            document.body.classList.remove('drawer-open');
        });
    }
    
    // Mobile Sticky CTA
    const stickyAddToCart = document.querySelector('.sticky-add-to-cart');
    if (stickyAddToCart) {
        stickyAddToCart.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            const quantity = document.getElementById('product-quantity') ? 
                document.getElementById('product-quantity').value : 1;
            
            // Add product to cart via AJAX
            fetch('/add-to-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 cart count in header
                    const cartCounts = document.querySelectorAll('.cart-count');
                    cartCounts.forEach(element => {
                        element.textContent = data.cart_count;
                    });
                    
                    // Redirect to cart
                    window.location.href = '/cart.php';
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });
    }
    
    // Make sure existing product page JavaScript still works
    // ... (your existing product page JavaScript)
});




// Mobile Menu Toggle
document.addEventListener('DOMContentLoaded', function() {
    const menuToggle = document.getElementById('mobile-menu-toggle');
    const menuPanel = document.getElementById('mobile-menu-panel');
    const menuOverlay = document.getElementById('mobile-menu-overlay');
    
    if (menuToggle && menuPanel && menuOverlay) {
        // Open menu
        menuToggle.addEventListener('click', function() {
            menuPanel.classList.add('active');
            document.body.classList.add('menu-open');
        });
        
        // Close menu when clicking overlay
        menuOverlay.addEventListener('click', function() {
            menuPanel.classList.remove('active');
            document.body.classList.remove('menu-open');
        });
    }
});


document.addEventListener('DOMContentLoaded', function() {
    // Product Image Gallery
    const mainImage = document.getElementById('main-image');
    const thumbs = document.querySelectorAll('.thumb');
    
    if (mainImage && thumbs.length) {
        // Image zoom on click
        mainImage.addEventListener('click', function() {
            const imageUrl = this.src;
            openImageModal(imageUrl);
        });
        
        // Thumbnail click handling
        thumbs.forEach(thumb => {
            thumb.addEventListener('click', function() {
                // Remove active class from all thumbs
                thumbs.forEach(t => t.classList.remove('active'));
                // Add active class to clicked thumb
                this.classList.add('active');
                // Update main image
                mainImage.src = this.getAttribute('data-img');
            });
        });
        
        // Swipe functionality for mobile
        let touchStartX = 0;
        let touchEndX = 0;
        
        mainImage.addEventListener('touchstart', function(e) {
            touchStartX = e.changedTouches[0].screenX;
        }, false);
        
        mainImage.addEventListener('touchend', function(e) {
            touchEndX = e.changedTouches[0].screenX;
            handleSwipe();
        }, false);
        
        function handleSwipe() {
            if (touchEndX < touchStartX - 50) {
                // Swipe left - next image
                let activeIndex = Array.from(thumbs).findIndex(thumb => thumb.classList.contains('active'));
                let nextIndex = (activeIndex + 1) % thumbs.length;
                thumbs[nextIndex].click();
            }
            
            if (touchEndX > touchStartX + 50) {
                // Swipe right - previous image
                let activeIndex = Array.from(thumbs).findIndex(thumb => thumb.classList.contains('active'));
                let prevIndex = (activeIndex - 1 + thumbs.length) % thumbs.length;
                thumbs[prevIndex].click();
            }
        }
    }
    
    // Image Modal
    function openImageModal(imageUrl) {
        const modal = document.createElement('div');
        modal.className = 'image-modal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <button class="modal-close">×</button>
                <img src="${imageUrl}" alt="Uvećana slika">
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // Prevent scrolling
        document.body.style.overflow = 'hidden';
        
        // Close modal functionality
        const closeBtn = modal.querySelector('.modal-close');
        const overlay = modal.querySelector('.modal-overlay');
        
        closeBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', closeModal);
        
        function closeModal() {
            document.body.style.overflow = '';
            modal.remove();
        }
    }
    
    // Product Tabs
    const tabLinks = document.querySelectorAll('.tab-link');
    const tabContents = document.querySelectorAll('.tab-content');
    
    if (tabLinks.length && tabContents.length) {
        tabLinks.forEach(link => {
            link.addEventListener('click', function() {
                // Remove active class from all tabs
                tabLinks.forEach(t => t.classList.remove('active'));
                tabContents.forEach(t => t.classList.remove('active'));
                
                // Add active class to clicked tab
                this.classList.add('active');
                
                // Show corresponding content
                document.getElementById(this.getAttribute('data-tab')).classList.add('active');
            });
        });
    }
    
    // Review Form Toggle
    const reviewTrigger = document.getElementById('write-review-trigger');
    const reviewForm = document.getElementById('write-review-form');
    const cancelReview = document.getElementById('cancel-review');
    
    if (reviewTrigger && reviewForm) {
        reviewTrigger.addEventListener('click', function() {
            reviewForm.style.display = 'block';
            reviewTrigger.style.display = 'none';
            
            // Scroll to form
            reviewForm.scrollIntoView({ behavior: 'smooth', block: 'center' });
        });
        
        if (cancelReview) {
            cancelReview.addEventListener('click', function() {
                reviewForm.style.display = 'none';
                reviewTrigger.style.display = 'block';
            });
        }
    }
    
    // Recently Viewed Products
    const currentProductId = document.querySelector('[data-product-id]')?.getAttribute('data-product-id');
    
    if (currentProductId) {
        // Get existing recently viewed products from localStorage
        let recentlyViewed = JSON.parse(localStorage.getItem('recentlyViewed') || '[]');
        
        // Remove the current product if it's already in the list
        recentlyViewed = recentlyViewed.filter(id => id !== currentProductId);
        
        // Add current product to the beginning of the array
        recentlyViewed.unshift(currentProductId);
        
        // Keep only the last 5 products
        recentlyViewed = recentlyViewed.slice(0, 5);
        
        // Save back to localStorage
        localStorage.setItem('recentlyViewed', JSON.stringify(recentlyViewed));
        
        // If we have IDs, fetch the products and display them
        if (recentlyViewed.length > 1) {
            // Remove current product
            const otherProducts = recentlyViewed.slice(1);
            
            // Only show section if there are other products
            if (otherProducts.length > 0) {
                fetchRecentlyViewed(otherProducts);
            } else {
                // Hide recently viewed section
                const recentlyViewedSection = document.querySelector('.recently-viewed');
                if (recentlyViewedSection) {
                    recentlyViewedSection.style.display = 'none';
                }
            }
        } else {
            // Hide recently viewed section
            const recentlyViewedSection = document.querySelector('.recently-viewed');
            if (recentlyViewedSection) {
                recentlyViewedSection.style.display = 'none';
            }
        }
    }
    
    function fetchRecentlyViewed(productIds) {
        // This would normally be an AJAX call to your server
        // For simplicity, we're mocking this function
        // You would replace this with actual API call
        
        // Example placeholder - in real implementation, fetch data from server
        const recentProductsContainer = document.getElementById('recently-viewed-products');
        
        if (recentProductsContainer) {
            // This is where you would make an API call like:
            // fetch('/api/products?ids=' + productIds.join(','))
            //     .then(response => response.json())
            //     .then(products => {
            //         // Render the products
            //     });
            
            // For now, just show a placeholder message
            recentProductsContainer.innerHTML = '<div class="placeholder-message">Proizvodi koje ste nedavno pregledali će biti prikazani ovde.</div>';
        }
    }
    
    // Sticky Add to Cart button
    const stickyAddToCart = document.querySelector('.sticky-add-to-cart');
    const regularAddToCart = document.getElementById('order-now');
    
    if (stickyAddToCart && regularAddToCart) {
        stickyAddToCart.addEventListener('click', function() {
            // Trigger the regular add to cart button
            regularAddToCart.click();
        });
    }
});


<script src="/assets/js/mobile-nav.js"></script>




