// Product Detail Page Functionality
class ProductDetailManager {
    constructor() {
        this.productPrice = 0;
        this.maxQuantity = 0;
        this.stickyCartBar = null;
        this.productSection = null;
        this.isVisible = false;
        
        this.init();
    }
    
    init() {
        this.stickyCartBar = document.getElementById('stickyCartBar');
        this.productSection = document.querySelector('.product-purchase-section');
        
        if (!this.stickyCartBar || !this.productSection) return;
        
        this.extractProductData();
        this.setupQuantityControls();
        this.setupStickyCart();
        this.setupFormSubmission();
        this.setupPriceCalculation();
    }
    
    extractProductData() {
        // Extract product price from the page
        const priceElement = document.querySelector('#total-price');
        if (priceElement) {
            const priceText = priceElement.textContent.replace(/[^\d.]/g, '');
            this.productPrice = parseFloat(priceText) || 0;
        }
        
        // Extract max quantity
        const quantityInput = document.querySelector('.quantity-input');
        if (quantityInput) {
            this.maxQuantity = parseInt(quantityInput.getAttribute('max')) || 99;
        }
    }
    
    setupQuantityControls() {
        // Main quantity controls
        this.setupQuantityButtons('.quantity-btn', '.quantity-input');
        
        // Sticky bar quantity controls
        this.setupQuantityButtons('.quantity-btn-mini', '.quantity-input-mini');
        
        // Sync quantity between main and sticky forms
        this.syncQuantityInputs();
    }
    
    setupQuantityButtons(buttonSelector, inputSelector) {
        const buttons = document.querySelectorAll(buttonSelector);
        
        buttons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                const action = button.getAttribute('data-action');
                const container = button.closest('form') || button.closest('.quantity-selector') || button.closest('.quantity-selector-mini');
                const input = container.querySelector(inputSelector);
                
                if (!input) return;
                
                let currentValue = parseInt(input.value) || 1;
                
                if (action === 'increase' && currentValue < this.maxQuantity) {
                    currentValue++;
                } else if (action === 'decrease' && currentValue > 1) {
                    currentValue--;
                }
                
                input.value = currentValue;
                this.updateTotalPrice(currentValue);
                this.syncQuantityValues(currentValue);
            });
        });
    }
    
    syncQuantityInputs() {
        const mainInput = document.querySelector('.quantity-input');
        const stickyInput = document.querySelector('.quantity-input-mini');
        
        if (mainInput) {
            mainInput.addEventListener('input', (e) => {
                const value = Math.max(1, Math.min(this.maxQuantity, parseInt(e.target.value) || 1));
                e.target.value = value;
                this.updateTotalPrice(value);
                this.syncQuantityValues(value);
            });
        }
        
        if (stickyInput) {
            stickyInput.addEventListener('input', (e) => {
                const value = Math.max(1, Math.min(this.maxQuantity, parseInt(e.target.value) || 1));
                e.target.value = value;
                this.updateTotalPrice(value);
                this.syncQuantityValues(value);
            });
        }
    }
    
    syncQuantityValues(value) {
        const mainInput = document.querySelector('.quantity-input');
        const stickyInput = document.querySelector('.quantity-input-mini');
        
        if (mainInput && mainInput.value != value) {
            mainInput.value = value;
        }
        
        if (stickyInput && stickyInput.value != value) {
            stickyInput.value = value;
        }
    }
    
    updateTotalPrice(quantity) {
        const totalPriceElement = document.getElementById('total-price');
        if (totalPriceElement && this.productPrice > 0) {
            const total = this.productPrice * quantity;
            totalPriceElement.textContent = `KES ${total.toFixed(2)}`;
            
            // Add animation
            totalPriceElement.classList.add('price-updated');
            setTimeout(() => {
                totalPriceElement.classList.remove('price-updated');
            }, 500);
        }
    }
    
    setupStickyCart() {
        let ticking = false;
        
        const updateStickyCart = () => {
            if (!this.productSection || !this.stickyCartBar) return;
            
            const rect = this.productSection.getBoundingClientRect();
            const windowHeight = window.innerHeight;
            
            // Show sticky cart when original purchase section is out of view
            const shouldShow = rect.bottom < 0;
            
            if (shouldShow && !this.isVisible) {
                this.showStickyCart();
            } else if (!shouldShow && this.isVisible) {
                this.hideStickyCart();
            }
            
            ticking = false;
        };
        
        const onScroll = () => {
            if (!ticking) {
                requestAnimationFrame(updateStickyCart);
                ticking = true;
            }
        };
        
        window.addEventListener('scroll', onScroll);
        window.addEventListener('resize', onScroll);
        
        // Initial check
        updateStickyCart();
    }
    
    showStickyCart() {
        if (this.stickyCartBar && !this.isVisible) {
            this.stickyCartBar.classList.remove('d-none');
            this.stickyCartBar.classList.add('show');
            this.isVisible = true;
            
            // Add entrance animation
            setTimeout(() => {
                this.stickyCartBar.style.transform = 'translateY(0)';
            }, 10);
        }
    }
    
    hideStickyCart() {
        if (this.stickyCartBar && this.isVisible) {
            this.stickyCartBar.classList.remove('show');
            this.isVisible = false;
            
            setTimeout(() => {
                this.stickyCartBar.classList.add('d-none');
            }, 300);
        }
    }
    
    setupFormSubmission() {
        const forms = document.querySelectorAll('.add-to-cart-form, .sticky-cart-form');
        
        forms.forEach(form => {
            form.addEventListener('submit', (e) => {
                const button = form.querySelector('button[type="submit"]');
                if (button) {
                    this.addLoadingState(button);
                    
                    // Reset after submission
                    setTimeout(() => {
                        this.removeLoadingState(button);
                        this.showSuccessState(button);
                    }, 2000);
                }
            });
        });
    }
    
    addLoadingState(button) {
        const originalText = button.innerHTML;
        button.setAttribute('data-original-text', originalText);
        button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Adding...';
        button.disabled = true;
        button.classList.add('loading');
    }
    
    removeLoadingState(button) {
        const originalText = button.getAttribute('data-original-text');
        if (originalText) {
            button.innerHTML = originalText;
        }
        button.disabled = false;
        button.classList.remove('loading');
    }
    
    showSuccessState(button) {
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-check me-2"></i>Added!';
        button.classList.add('cart-success');
        
        setTimeout(() => {
            button.innerHTML = originalText;
            button.classList.remove('cart-success');
        }, 2000);
    }
    
    setupPriceCalculation() {
        // Update cart counter if available
        const updateCartCounter = () => {
            const cartBadge = document.querySelector('.cart-badge');
            if (cartBadge) {
                const currentCount = parseInt(cartBadge.textContent) || 0;
                cartBadge.textContent = currentCount + 1;
                
                // Animation
                cartBadge.style.transform = 'scale(1.3)';
                setTimeout(() => {
                    cartBadge.style.transform = 'scale(1)';
                }, 200);
            }
        };
        
        // Listen for successful cart additions
        document.addEventListener('cartItemAdded', updateCartCounter);
    }
}

// Product Image Zoom functionality
class ProductImageZoom {
    constructor() {
        this.init();
    }
    
    init() {
        const productImage = document.querySelector('.product-image img');
        if (productImage) {
            this.setupImageZoom(productImage);
        }
    }
    
    setupImageZoom(image) {
        image.addEventListener('click', () => {
            this.openImageModal(image.src, image.alt);
        });
        
        // Add zoom cursor
        image.style.cursor = 'zoom-in';
    }
    
    openImageModal(src, alt) {
        // Create modal for image zoom
        const modal = document.createElement('div');
        modal.className = 'image-zoom-modal';
        modal.innerHTML = `
            <div class="image-zoom-backdrop" onclick="this.parentElement.remove()">
                <div class="image-zoom-container">
                    <img src="${src}" alt="${alt}" class="zoomed-image">
                    <button class="close-zoom" onclick="this.closest('.image-zoom-modal').remove()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        // Add modal styles
        const style = document.createElement('style');
        style.textContent = `
            .image-zoom-modal {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                z-index: 9999;
                animation: fadeIn 0.3s ease;
            }
            .image-zoom-backdrop {
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.9);
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            }
            .image-zoom-container {
                position: relative;
                max-width: 90vw;
                max-height: 90vh;
            }
            .zoomed-image {
                max-width: 100%;
                max-height: 100%;
                object-fit: contain;
                border-radius: 8px;
            }
            .close-zoom {
                position: absolute;
                top: 10px;
                right: 10px;
                background: rgba(0,0,0,0.7);
                color: white;
                border: none;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: background 0.3s ease;
            }
            .close-zoom:hover {
                background: rgba(0,0,0,0.9);
            }
            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }
        `;
        
        document.head.appendChild(style);
        document.body.appendChild(modal);
        
        // Close on Escape key
        const closeOnEscape = (e) => {
            if (e.key === 'Escape') {
                modal.remove();
                document.removeEventListener('keydown', closeOnEscape);
            }
        };
        document.addEventListener('keydown', closeOnEscape);
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    window.productDetailManager = new ProductDetailManager();
    window.productImageZoom = new ProductImageZoom();
});

// Clean up on page unload
window.addEventListener('beforeunload', () => {
    // Clean up any event listeners or timers if needed
});

// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { ProductDetailManager, ProductImageZoom };
}