// Responsive Cart Management - No Automatic Price Updates
class CartManager {
    constructor() {
        this.isUpdating = false;
        this.updateTimeout = null;
        this.init();
    }

    init() {
        this.setupQuantityControls();
        this.setupRemoveButtons();
        this.setupFormSubmissions();
    }

    setupQuantityControls() {
        // Handle quantity increase buttons
        document.querySelectorAll('.quantity-increase').forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                const itemId = button.dataset.itemId;
                const input = document.querySelector(`.quantity-input[data-item-id="${itemId}"]`);
                this.increaseQuantity(input, button);
            });
        });

        // Handle quantity decrease buttons
        document.querySelectorAll('.quantity-decrease').forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                const itemId = button.dataset.itemId;
                const input = document.querySelector(`.quantity-input[data-item-id="${itemId}"]`);
                this.decreaseQuantity(input, button);
            });
        });

        // Handle direct input changes (if input becomes editable)
        document.querySelectorAll('.quantity-input').forEach(input => {
            input.addEventListener('change', (e) => {
                this.validateQuantity(input);
            });

            input.addEventListener('blur', (e) => {
                this.validateQuantity(input);
            });
        });
    }

    increaseQuantity(input, button) {
        if (!input || this.isUpdating) return;

        const currentValue = parseInt(input.value) || 1;
        const maxValue = parseInt(input.getAttribute('max')) || 99;
        const itemId = input.dataset.itemId;

        if (currentValue < maxValue) {
            const newValue = currentValue + 1;
            input.value = newValue;
            
            // Add visual feedback
            this.addQuantityFeedback(input, 'increase');
            
            // Auto-submit after a short delay to prevent multiple rapid updates
            this.scheduleUpdate(itemId);
        } else {
            this.showQuantityError(input, `Maximum quantity is ${maxValue}`);
        }

        // Update button states
        this.updateButtonStates(input);
    }

    decreaseQuantity(input, button) {
        if (!input || this.isUpdating) return;

        const currentValue = parseInt(input.value) || 1;
        const minValue = parseInt(input.getAttribute('min')) || 1;
        const itemId = input.dataset.itemId;

        if (currentValue > minValue) {
            const newValue = currentValue - 1;
            input.value = newValue;
            
            // Add visual feedback
            this.addQuantityFeedback(input, 'decrease');
            
            // Auto-submit after a short delay to prevent multiple rapid updates
            this.scheduleUpdate(itemId);
        } else {
            this.showQuantityError(input, `Minimum quantity is ${minValue}`);
        }

        // Update button states
        this.updateButtonStates(input);
    }

    validateQuantity(input) {
        const value = parseInt(input.value) || 1;
        const min = parseInt(input.getAttribute('min')) || 1;
        const max = parseInt(input.getAttribute('max')) || 99;

        if (value < min) {
            input.value = min;
            this.showQuantityError(input, `Minimum quantity is ${min}`);
        } else if (value > max) {
            input.value = max;
            this.showQuantityError(input, `Maximum quantity is ${max}`);
        } else {
            this.clearQuantityError(input);
        }

        this.updateButtonStates(input);
    }

    updateButtonStates(input) {
        const itemId = input.dataset.itemId;
        const value = parseInt(input.value) || 1;
        const min = parseInt(input.getAttribute('min')) || 1;
        const max = parseInt(input.getAttribute('max')) || 99;

        const decreaseBtn = document.querySelector(`.quantity-decrease[data-item-id="${itemId}"]`);
        const increaseBtn = document.querySelector(`.quantity-increase[data-item-id="${itemId}"]`);

        if (decreaseBtn) {
            decreaseBtn.disabled = value <= min;
        }

        if (increaseBtn) {
            increaseBtn.disabled = value >= max;
        }
    }

    scheduleUpdate(itemId) {
        // Clear any existing timeout
        if (this.updateTimeout) {
            clearTimeout(this.updateTimeout);
        }

        // Schedule update after 1 second of inactivity
        this.updateTimeout = setTimeout(() => {
            this.submitQuantityUpdate(itemId);
        }, 1000);
    }

    submitQuantityUpdate(itemId) {
        if (this.isUpdating) return;

        const form = document.querySelector(`.cart-update-form[action*="${itemId}"]`);
        const input = document.querySelector(`.quantity-input[data-item-id="${itemId}"]`);
        
        if (!form || !input) return;

        this.isUpdating = true;
        this.addUpdatingState(input);

        // Submit the form
        const formData = new FormData(form);
        const url = form.getAttribute('action');

        fetch(url, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (response.ok) {
                return response.text();
            }
            throw new Error('Update failed');
        })
        .then(html => {
            // Success - reload the page to show updated totals
            window.location.reload();
        })
        .catch(error => {
            console.error('Error updating cart:', error);
            this.showQuantityError(input, 'Update failed. Please try again.');
            this.removeUpdatingState(input);
            this.isUpdating = false;
        });
    }

    addQuantityFeedback(input, type) {
        const controlGroup = input.closest('.quantity-control-group');
        if (controlGroup) {
            controlGroup.classList.add('quantity-updated');
            setTimeout(() => {
                controlGroup.classList.remove('quantity-updated');
            }, 500);
        }
    }

    addUpdatingState(input) {
        const controlGroup = input.closest('.quantity-control-group');
        const cardBody = input.closest('.card-body');
        
        if (controlGroup) {
            controlGroup.classList.add('updating');
        }
        
        if (cardBody) {
            cardBody.classList.add('quantity-updating');
        }

        // Disable all buttons in this control group
        const itemId = input.dataset.itemId;
        const buttons = document.querySelectorAll(`[data-item-id="${itemId}"]`);
        buttons.forEach(btn => {
            if (btn.tagName === 'BUTTON') {
                btn.disabled = true;
            }
        });
    }

    removeUpdatingState(input) {
        const controlGroup = input.closest('.quantity-control-group');
        const cardBody = input.closest('.card-body');
        
        if (controlGroup) {
            controlGroup.classList.remove('updating');
        }
        
        if (cardBody) {
            cardBody.classList.remove('quantity-updating');
        }

        // Re-enable buttons and update their states
        this.updateButtonStates(input);
    }

    showQuantityError(input, message) {
        this.clearQuantityError(input);
        
        const controlGroup = input.closest('.quantity-control-group');
        if (controlGroup) {
            controlGroup.classList.add('quantity-error');
            
            // Create error message
            const errorMsg = document.createElement('div');
            errorMsg.className = 'quantity-error-message show';
            errorMsg.textContent = message;
            controlGroup.parentNode.appendChild(errorMsg);
            
            // Remove error after 3 seconds
            setTimeout(() => {
                this.clearQuantityError(input);
            }, 3000);
        }
    }

    clearQuantityError(input) {
        const controlGroup = input.closest('.quantity-control-group');
        if (controlGroup) {
            controlGroup.classList.remove('quantity-error');
            
            // Remove error message
            const errorMsg = controlGroup.parentNode.querySelector('.quantity-error-message');
            if (errorMsg) {
                errorMsg.remove();
            }
        }
    }

    setupRemoveButtons() {
        document.querySelectorAll('.remove-btn').forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                
                if (confirm('Are you sure you want to remove this item from your cart?')) {
                    const href = button.getAttribute('href');
                    window.location.href = href;
                }
            });
        });
    }

    setupFormSubmissions() {
        // Prevent default form submission for cart update forms
        document.querySelectorAll('.cart-update-form').forEach(form => {
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                // Form submission is handled by the quantity controls
            });
        });
    }

    // Public method to manually trigger updates
    updateCart(itemId) {
        this.submitQuantityUpdate(itemId);
    }

    // Public method to refresh cart display
    refreshCart() {
        window.location.reload();
    }
}

// Initialize cart manager when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    if (document.querySelector('.cart-update-form')) {
        window.cartManager = new CartManager();
    }
});

// Utility functions for external use
function updateCartItem(itemId) {
    if (window.cartManager) {
        window.cartManager.updateCart(itemId);
    }
}

function refreshCartDisplay() {
    if (window.cartManager) {
        window.cartManager.refreshCart();
    }
}

// Handle page visibility changes
document.addEventListener('visibilitychange', function() {
    if (!document.hidden && window.cartManager) {
        // Page became visible - could refresh cart if needed
        console.log('Cart page visible');
    }
});

// Handle online/offline status
window.addEventListener('online', function() {
    console.log('Connection restored');
});

window.addEventListener('offline', function() {
    console.log('Connection lost');
    if (window.cartManager) {
        // Could show offline message or disable updates
    }
});