document.addEventListener('DOMContentLoaded', function() {
    // Inicijalizacija svih komponenti
    initImageGallery();
    initTabs();
    initQuantityControls();
    initAccordions();
    initModals();
    initSimilarProducts();
    initStickyCart();
    initAddToCart();
    initFrequentlyBoughtTogether();
    
    // Provera hash-a za otvaranje specifičnog taba
    if(location.hash) {
        const tabId = location.hash.substring(1);
        const tabBtn = document.getElementById(`tab-${tabId}-btn`);
        if(tabBtn) tabBtn.click();
    }
    
    /**
     * Galerija slika proizvoda
     */
    function initImageGallery() {
        const mainImage = document.getElementById('main-product-image');
        const thumbnails = document.querySelectorAll('.thumbnail');
        
        if(!mainImage) return;
        
        // Klik na thumbnail
        thumbnails.forEach(thumb => {
            thumb.addEventListener('click', function() {
                // Ažuriranje glavne slike
                mainImage.src = this.getAttribute('data-image');
                mainImage.setAttribute('data-zoom-src', this.getAttribute('data-zoom-src'));
                
                // Ažuriranje aktivnog thumbnail-a
                thumbnails.forEach(t => t.classList.remove('active'));
                this.classList.add('active');
            });
        });
        
        // Uvećanje slike
        const zoomTrigger = document.querySelector('.image-zoom-trigger');
        if(zoomTrigger) {
            zoomTrigger.addEventListener('click', function() {
                const zoomSrc = mainImage.getAttribute('data-zoom-src') || mainImage.src;
                const zoomedImage = document.getElementById('zoomed-image');
                zoomedImage.src = zoomSrc;
                openModal('image-modal');
            });
        }
    }
    
    /**
     * Tabovi
     */
    function initTabs() {
        const tabButtons = document.querySelectorAll('.tab-btn');
        const tabContents = document.querySelectorAll('.tab-content');
        
        tabButtons.forEach(button => {
            button.addEventListener('click', function() {
                const tabId = this.getAttribute('data-tab');
                
                // Uklanjanje aktivne klase sa svih tabova
                tabButtons.forEach(btn => {
                    btn.classList.remove('active');
                    btn.setAttribute('aria-selected', 'false');
                });
                
                tabContents.forEach(content => {
                    content.classList.remove('active');
                });
                
                // Aktiviranje izabranog taba
                this.classList.add('active');
                this.setAttribute('aria-selected', 'true');
                
                const activeTab = document.getElementById(tabId);
                if(activeTab) activeTab.classList.add('active');
            });
        });
    }
    
    /**
     * Kontrole za količinu
     */
    function initQuantityControls() {
        const minusBtn = document.querySelector('.quantity-btn.minus');
        const plusBtn = document.querySelector('.quantity-btn.plus');
        const quantityInput = document.getElementById('quantity');
        
        if(!minusBtn || !plusBtn || !quantityInput) return;
        
        minusBtn.addEventListener('click', function() {
            const currentValue = parseInt(quantityInput.value);
            if(currentValue > 1) {
                quantityInput.value = currentValue - 1;
            }
        });
        
        plusBtn.addEventListener('click', function() {
            const currentValue = parseInt(quantityInput.value);
            const maxValue = parseInt(quantityInput.getAttribute('max') || 999);
            
            if(currentValue < maxValue) {
                quantityInput.value = currentValue + 1;
            }
        });
        
        // Validacija unosa
        quantityInput.addEventListener('change', function() {
            let value = parseInt(this.value);
            const min = parseInt(this.getAttribute('min') || 1);
            const max = parseInt(this.getAttribute('max') || 999);
            
            if(isNaN(value) || value < min) {
                this.value = min;
            } else if(value > max) {
                this.value = max;
            }
        });
    }
    
    /**
     * Accordioni (za FAQ, garanciju itd.)
     */
    function initAccordions() {
        const accordionButtons = document.querySelectorAll('.accordion-btn');
        
        accordionButtons.forEach(button => {
            button.addEventListener('click', function() {
                const expanded = this.getAttribute('aria-expanded') === 'true';
                const content = this.closest('.faq-question').nextElementSibling;
                
                this.setAttribute('aria-expanded', !expanded);
                content.hidden = expanded;
                
                // Rotacija ikonice
                const icon = this.querySelector('.accordion-icon');
                if(icon) {
                    icon.style.transform = expanded ? '' : 'rotate(180deg)';
                }
            });
        });
    }
    
    /**
     * Modali (zoom slike, opcije plaćanja, itd.)
     */
    function initModals() {
        // Zatvaranje modala klikom na overlay
        document.querySelectorAll('.modal-overlay').forEach(overlay => {
            overlay.addEventListener('click', function() {
                const modal = this.closest('.modal');
                closeModal(modal.id);
            });
        });
        
        // Zatvaranje modala klikom na "X"
        document.querySelectorAll('.modal-close').forEach(closeBtn => {
            closeBtn.addEventListener('click', function() {
                const modal = this.closest('.modal');
                closeModal(modal.id);
            });
        });
        
        // Zatvaranje modala klikom na dugme "Odustani"
        document.querySelectorAll('.modal-cancel').forEach(cancelBtn => {
            cancelBtn.addEventListener('click', function() {
                const modal = this.closest('.modal');
                closeModal(modal.id);
            });
        });
        
        // ESC za zatvaranje modala
        document.addEventListener('keydown', function(e) {
            if(e.key === 'Escape') {
                const activeModals = document.querySelectorAll('.modal.active');
                activeModals.forEach(modal => closeModal(modal.id));
            }
        });
        
        // Pokretanje modala za "Našli ste jeftinije"
        const priceMatchTrigger = document.querySelector('.price-match-trigger');
        if(priceMatchTrigger) {
            priceMatchTrigger.addEventListener('click', function(e) {
                e.preventDefault();
                openModal('price-match-modal');
            });
        }
        
        // Opcije plaćanja
        const paymentOptionsTrigger = document.getElementById('payment-options-trigger');
        if(paymentOptionsTrigger) {
            paymentOptionsTrigger.addEventListener('click', function(e) {
                e.preventDefault();
                openModal('payment-options-modal');
            });
        }
        
        // Recenzije
        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';
                });
            }
        }
        
        // Scroll to recenzije
        const scrollToReviews = document.querySelector('.scroll-to-reviews');
        if(scrollToReviews) {
            scrollToReviews.addEventListener('click', function(e) {
                e.preventDefault();
                document.getElementById('tab-reviews-btn').click();
                
                setTimeout(() => {
                    document.getElementById('tab-reviews').scrollIntoView({
                        behavior: 'smooth'
                    });
                }, 100);
            });
        }
        
        // Postavljanje pitanja
        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';
                });
            }
        }
    }
    
    /**
     * Slični proizvodi - slajder
     */
    function initSimilarProducts() {
        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;
        
        // Pokazivanje/sakrivanje strelica kada je potrebno
        const updateScrollButtons = function() {
            leftBtn.classList.toggle('active', container.scrollLeft > 0);
            rightBtn.classList.toggle('active', container.scrollLeft < container.scrollWidth - container.clientWidth - 10);
        };
        
        // Inicijalno ažuriranje
        updateScrollButtons();
        
        // Ažuriranje pri skrolovanja
        container.addEventListener('scroll', updateScrollButtons);
        
        // Klik na levo dugme
        leftBtn.addEventListener('click', function() {
            container.scrollBy({
                left: -300,
                behavior: 'smooth'
            });
        });
        
        // Klik na desno dugme
        rightBtn.addEventListener('click', function() {
            container.scrollBy({
                left: 300,
                behavior: 'smooth'
            });
        });
        
        // Quick Add klikovi
        const quickAddButtons = document.querySelectorAll('.btn-quick-add');
        quickAddButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                const productId = this.getAttribute('data-product-id');
                addToCart(productId, 1);
            });
        });
    }
    
    /**
     * Sticky korpa (na mobilnim uređajima)
     */
    function initStickyCart() {
        const stickyCart = document.querySelector('.sticky-cart');
        const productInfo = document.querySelector('.product-info-section');
        
        if(!stickyCart || !productInfo) return;
        
        // Prikazivanje sticky carta kada se skroluje ispod informacija o proizvodu
        window.addEventListener('scroll', function() {
            const rect = productInfo.getBoundingClientRect();
            
            if(rect.bottom < 0 && window.innerWidth < 768) {
                stickyCart.classList.add('visible');
            } else {
                stickyCart.classList.remove('visible');
            }
        });
        
        // Klik na sticky dugme
        const stickyBuyBtn = document.querySelector('.sticky-buy-btn');
        if(stickyBuyBtn) {
            stickyBuyBtn.addEventListener('click', function() {
                if(this.disabled) return;
                
                const productId = this.getAttribute('data-product-id');
                const quantity = document.getElementById('quantity').value;
                
                addToCart(productId, quantity);
            });
        }
    }
    
    /**
     * Dodavanje u korpu
     */
    function initAddToCart() {
        const addToCartBtn = document.getElementById('add-to-cart-btn');
        const buyNowBtn = document.getElementById('buy-now-btn');
        
        if(addToCartBtn) {
            addToCartBtn.addEventListener('click', function() {
                if(this.disabled) return;
                
                const productId = this.getAttribute('data-product-id');
                const quantity = document.getElementById('quantity').value;
                
                addToCart(productId, quantity);
            });
        }
        
        if(buyNowBtn) {
            buyNowBtn.addEventListener('click', function() {
                if(this.disabled) return;
                
                const productId = this.getAttribute('data-product-id');
                const quantity = document.getElementById('quantity').value;
                
                addToCart(productId, quantity, true);
            });
        }
    }
    
    /**
     * Često se kupuje zajedno
     */
    function initFrequentlyBoughtTogether() {
        const fbtCheckboxes = document.querySelectorAll('.fbt-checkbox input');
        const addAllBtn = document.getElementById('add-all-to-cart');
        
        if(!fbtCheckboxes.length || !addAllBtn) return;
        
        // Ažuriranje ukupne cene pri promeni izbora
        fbtCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', updateFBTTotal);
        });
        
        // Dodavanje svih izabranih proizvoda u korpu
        addAllBtn.addEventListener('click', function() {
            const mainProduct = document.getElementById('add-to-cart-btn').getAttribute('data-product-id');
            const quantity = document.getElementById('quantity').value;
            const selectedProducts = [];
            
            // Sakupljanje izabranih proizvoda
            fbtCheckboxes.forEach(checkbox => {
                if(checkbox.checked) {
                    selectedProducts.push({
                        id: checkbox.value,
                        quantity: 1
                    });
                }
            });
            
            // Dodaj glavni proizvod
            addToCart(mainProduct, quantity, false, true);
            
            // Dodaj ostale proizvode
            if(selectedProducts.length > 0) {
                setTimeout(() => {
                    addMultipleToCart(selectedProducts);
                }, 300);
            }
        });
        
        // Ažuriranje ukupne cene
        function updateFBTTotal() {
            const mainPrice = getProductPrice(document.querySelector('.current-price'));
            let totalPrice = mainPrice;
            
            fbtCheckboxes.forEach(checkbox => {
                if(checkbox.checked) {
                    const priceElem = checkbox.closest('.fbt-product').querySelector('.fbt-product-price');
                    const price = getProductPrice(priceElem);
                    totalPrice += price;
                }
            });
            
            // Primena popusta za bundle
            const discountedPrice = totalPrice * 0.95; // 5% popusta
            const savings = totalPrice - discountedPrice;
            
            // Ažuriranje prikaza
            document.getElementById('fbt-total-amount').textContent = formatPrice(discountedPrice);
            document.getElementById('fbt-save-amount').textContent = formatPrice(savings);
        }
        
        // Pomoćna funkcija za dobijanje cene iz HTML elementa
        function getProductPrice(element) {
            if(!element) return 0;
            const priceText = element.textContent.trim();
            const price = parseFloat(priceText.replace(/[^0-9]/g, ''));
            return !isNaN(price) ? price : 0;
        }
        
        // Pomoćna funkcija za formatiranje cene
        function formatPrice(price) {
            return new Intl.NumberFormat('sr-RS').format(Math.round(price)) + ' RSD';
        }
        
        // Inicijalno izračunavanje
        updateFBTTotal();
    }
    
    /**
     * Dodavanje proizvoda u korpu
     */
    function addToCart(productId, quantity, goToCheckout = false, isMultiple = false) {
        // AJAX zahtev za dodavanje u korpu
        fetch('/ajax/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) {
                updateCartCount(parseInt(quantity));
                
                if(goToCheckout) {
                    window.location.href = '/checkout';
                } else if(!isMultiple) {
                    openModal('cart-success-modal');
                }
            } else {
                alert(data.message || 'Došlo je do greške prilikom dodavanja proizvoda u korpu.');
            }
        })
        .catch(error => {
            console.error('Greška:', error);
            alert('Došlo je do greške prilikom komunikacije sa serverom.');
        });
    }
    
    /**
     * Dodavanje više proizvoda u korpu odjednom
     */
    function addMultipleToCart(products) {
        fetch('/ajax/add-multiple-to-cart.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ products: products })
        })
        .then(response => response.json())
        .then(data => {
            if(data.success) {
                openModal('cart-success-modal');
                
                // Ažuriranje broja stavki u korpi
                const totalQuantity = products.reduce((sum, product) => sum + parseInt(product.quantity), 0);
                updateCartCount(totalQuantity);
            } else {
                alert(data.message || 'Došlo je do greške prilikom dodavanja proizvoda u korpu.');
            }
        })
        .catch(error => {
            console.error('Greška:', error);
        });
    }
    
    /**
     * Ažuriranje broja proizvoda u korpi
     */
    function updateCartCount(quantity) {
        const cartCountElements = document.querySelectorAll('.cart-count');
        
        cartCountElements.forEach(element => {
            let currentCount = parseInt(element.textContent) || 0;
            element.textContent = currentCount + quantity;
        });
    }
    
    /**
     * Otvaranje modala
     */
    function openModal(modalId) {
        const modal = document.getElementById(modalId);
        if(modal) {
            modal.classList.add('active');
            document.body.style.overflow = 'hidden';
        }
    }
    
    /**
     * Zatvaranje modala
     */
    function closeModal(modalId) {
        const modal = document.getElementById(modalId);
        if(modal) {
            modal.classList.remove('active');
            document.body.style.overflow = '';
        }
    }
    
    // Izlaganje funkcija globalno
    window.openModal = openModal;
    window.closeModal = closeModal;
});