jQuery(document).ready(function($) {

    // Prevent multiple initializations
    if (window.ggmCommerceCartInitialized) {
        return;
    }
    window.ggmCommerceCartInitialized = true;

    // Helper function to get translated strings with fallbacks
    function getI18n(key, fallback) {
        if (typeof ggmCommerceAjax !== 'undefined' && ggmCommerceAjax.i18n && ggmCommerceAjax.i18n[key]) {
            return ggmCommerceAjax.i18n[key];
        }
        return fallback || key;
    }
    
    // Add to cart button handler
    $(document).on('click', '.ggmc-add-to-cart-btn', function(e) {
        e.preventDefault();

        var $button = $(this);
        var productId = $button.data('product-id');
        var hasVariations = $button.data('has-variations') === 1 || $button.data('has-variations') === '1';
        var variableBehavior = $button.data('variable-behavior') || 'link_to_product';
        var productUrl = $button.data('product-url');

        // Find the wrapper element (supports various widget contexts)
        var $wrapper = $button.closest('.ggmc-add-to-cart-wrapper, .product-grid-item, .product-actions, .ggmc-product-card, .ggmc-product-row, tr');

        // Check for variation selection if product has variations
        var variationId = null;
        var variationData = null;

        if (hasVariations) {
            // Look for variation hidden inputs - check multiple locations:
            // 1. Within the wrapper (for grid/table with inline selectors)
            // 2. Within a variation selector widget for this product (for product detail pages)
            // 3. Anywhere on the page for this product
            var $variationInput = $wrapper.find('.ggmc-selected-variation-id');

            // If not found or empty in wrapper, look for variation selector widget
            if (!$variationInput.length || !$variationInput.val()) {
                // Try exact product ID match first
                var $variationSelector = $('.ggmc-variation-selector[data-product-id="' + productId + '"]');

                // If not found, try without quotes (jQuery data can be int or string)
                if (!$variationSelector.length) {
                    $variationSelector = $('.ggmc-variation-selector').filter(function() {
                        return $(this).data('product-id') == productId;
                    });
                }

                if ($variationSelector.length) {
                    $variationInput = $variationSelector.find('.ggmc-selected-variation-id');
                }
            }

            // If still not found, search all hidden inputs on the page with matching product context
            if (!$variationInput.length || !$variationInput.val()) {
                // Look for any input that might be near an add-to-cart button for this product
                $variationInput = $('input.ggmc-selected-variation-id').filter(function() {
                    // Check if this input has a value and is related to our product
                    return $(this).val() !== '';
                }).first();
            }

            variationId = $variationInput.length && $variationInput.val() ? parseInt($variationInput.val()) : null;

            // Same approach for variation data
            var $variationDataInput = $wrapper.find('.ggmc-selected-variation-data');
            if (!$variationDataInput.length || !$variationDataInput.val()) {
                var $variationSelector = $('.ggmc-variation-selector').filter(function() {
                    return $(this).data('product-id') == productId;
                });
                if ($variationSelector.length) {
                    $variationDataInput = $variationSelector.find('.ggmc-selected-variation-data');
                }
            }
            variationData = $variationDataInput.length && $variationDataInput.val() ? $variationDataInput.val() : null;

            // Check variation mode - Independent mode doesn't use variation_id
            var variationMode = null;
            var $variationSelector = $('.ggmc-variation-selector').filter(function() {
                return $(this).data('product-id') == productId;
            });
            if ($variationSelector.length) {
                variationMode = $variationSelector.data('variation-mode');
            }

            // For Independent mode: check if we have variation data (selected attributes)
            // For Combined mode: check if we have a variation_id
            var hasValidSelection = false;
            if (variationMode === 'independent') {
                // Independent mode - need variation_data with selected attributes
                hasValidSelection = variationData && variationData !== '{}';
            } else {
                // Combined mode - need variation_id
                hasValidSelection = !!variationId;
            }

            // If no valid selection, handle based on behavior setting
            if (!hasValidSelection) {
                if (variableBehavior === 'link_to_product' && productUrl) {
                    // Redirect to product page
                    window.location.href = productUrl;
                    return;
                } else if (variableBehavior === 'link_to_product' && !productUrl) {
                    // Already on product page, but no variation selected - show message
                    showCartMessage(getI18n('select_options', 'Please select product options before adding to cart.'), 'warning');
                    return;
                } else if (variableBehavior === 'disabled') {
                    // Button should be disabled, but show message just in case
                    showCartMessage(getI18n('select_options_first', 'Please select product options first.'), 'warning');
                    return;
                } else if (variableBehavior === 'show_selector') {
                    // Trigger event to show variation selector (handled by variations.js)
                    $(document).trigger('ggmc_show_variation_selector', {
                        productId: productId,
                        wrapper: $wrapper
                    });
                    return;
                } else {
                    // Fallback: show message for any other case where variation is required but not selected
                    showCartMessage(getI18n('select_options', 'Please select product options before adding to cart.'), 'warning');
                    return;
                }
            }
        }

        // Find quantity input - check within parent wrapper first, then siblings
        var $quantityInput = $wrapper.find('.ggmc-quantity-input');
        if (!$quantityInput.length) {
            $quantityInput = $button.siblings('.ggmc-quantity-input');
        }
        var quantity = $quantityInput.val() || 1;

        // Store original button text (use add text if variation is now selected)
        var originalButtonText = hasVariations && (variationId || (variationMode === 'independent' && variationData))
            ? ($button.data('add-text') || 'Add to Cart')
            : $button.text();

        // Disable button and show loading state
        $button.prop('disabled', true).text('Adding...');

        // Build AJAX data
        var ajaxData = {
            action: 'ggmc_add_to_cart',
            product_id: productId,
            quantity: quantity,
            nonce: ggmCommerceAjax.nonce
        };

        // Add variation data if present
        if (variationId) {
            ajaxData.variation_id = variationId;
        }

        // For Independent mode, parse variation_data JSON and send as variation_attributes
        if (variationData) {
            try {
                var parsedData = JSON.parse(variationData);
                if (parsedData && typeof parsedData === 'object') {
                    ajaxData.variation_attributes = parsedData;
                }
            } catch (e) {
                // If not valid JSON, send as-is
                ajaxData.variation_data = variationData;
            }
        }

        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: ajaxData,
            success: function(response) {
                if (response.success) {
                    // Show success message
                    showCartMessage(response.data.message, 'success');

                    // Update cart count and total in header/widgets
                    updateCartDisplay(response.data.cart_count, response.data.cart_total);

                    // Trigger custom event for other components (like mini cart)
                    $(document).trigger('ggm_commerce_cart_updated', {
                        count: response.data.cart_count,
                        total: response.data.cart_total,
                        items: response.data.cart_items || [],
                        action: 'add_to_cart'
                    });

                    // Show brief success state, then reset button
                    $button.text('Added!');
                    setTimeout(function() {
                        $button.prop('disabled', false).text(originalButtonText);
                    }, 1000);
                } else {
                    showCartMessage(response.data.message || getI18n('error_occurred', 'An error occurred. Please try again.'), 'error');
                    $button.prop('disabled', false).text(originalButtonText);
                }
            },
            error: function(xhr, status, error) {
                showCartMessage(getI18n('error_occurred', 'An error occurred. Please try again.'), 'error');
                $button.prop('disabled', false).text(originalButtonText);
            }
        });
    });

    // Listen for variation selection changes to update add-to-cart button state and price
    $(document).on('ggmc_variation_changed', function(e, data) {
        // Find add-to-cart buttons for this product
        var $buttons = $('.ggmc-add-to-cart-btn[data-product-id="' + data.productId + '"]');

        $buttons.each(function() {
            var $button = $(this);
            var hasVariations = $button.data('has-variations') === 1 || $button.data('has-variations') === '1';

            if (!hasVariations) return;

            var variableBehavior = $button.data('variable-behavior') || 'link_to_product';
            var addText = $button.data('add-text') || 'Add to Cart';
            var variableText = $button.data('variable-text') || 'Select Options';

            // Check for valid selection - either variationId (Combined mode) or variationData (Independent mode)
            var hasValidSelection = false;
            if (data.variationId) {
                // Combined mode - has a variation_id
                hasValidSelection = true;
            } else if (data.variationData && data.variationData !== '{}') {
                // Independent mode - has selected attributes
                hasValidSelection = true;
            }

            if (hasValidSelection) {
                // Variation selected - enable button and show add text
                $button.prop('disabled', false).text(addText);
                $button.removeClass('variation-required').addClass('variation-selected');
            } else {
                // Variation cleared - reset to variable state
                $button.text(variableText);
                $button.removeClass('variation-selected').addClass('variation-required');

                if (variableBehavior === 'disabled') {
                    $button.prop('disabled', true);
                } else {
                    $button.prop('disabled', false);
                }
            }
        });

        // Update price display in add-to-cart widgets for this product
        var $priceElements = $('.ggmc-cart-price[data-product-id="' + data.productId + '"]');

        $priceElements.each(function() {
            var $priceEl = $(this);
            var symbol = $priceEl.data('currency-symbol') || '£';
            var position = $priceEl.data('currency-position') || 'before';

            // Check for valid selection
            var hasValidSelection = false;
            if (data.variationId) {
                hasValidSelection = true;
            } else if (data.variationData && data.variationData !== '{}') {
                hasValidSelection = true;
            }

            if (hasValidSelection && data.calculatedPrice !== undefined && data.calculatedPrice !== null) {
                // Variation selected - show the exact variation price
                var formatted = parseFloat(data.calculatedPrice).toFixed(2);
                var priceText = position === 'before' ? symbol + formatted : formatted + symbol;
                $priceEl.html('<span class="current-price">' + priceText + '</span>');
            } else {
                // Variation cleared - restore original "From $X" price
                var originalHtml = $priceEl.data('original-html');
                if (originalHtml) {
                    $priceEl.html(originalHtml);
                }
            }
        });
    });
    
    // Remove from cart
    $(document).on('click', '.ggmc-remove-from-cart', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var cartItemId = $button.data('cart-item-id');
        
        var confirmMsg = (ggm_commerce_ajax.i18n && ggm_commerce_ajax.i18n.confirm_remove)
            ? ggm_commerce_ajax.i18n.confirm_remove
            : 'Are you sure you want to remove this item from your cart?';
        if (confirm(confirmMsg)) {
            $.ajax({
                url: ggmCommerceAjax.ajax_url,
                type: 'POST',
                data: {
                    action: 'ggmc_remove_from_cart',
                    cart_item_id: cartItemId,
                    nonce: ggmCommerceAjax.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Check if cart is now empty
                        if (response.data.cart_empty) {
                            // Replace the entire cart table with empty cart message
                            var $cartContainer = $('.ggmc-cart-container');
                            if ($cartContainer.length) {
                                // Get the continue shopping URL from existing button or use default
                                var continueUrl = $('.ggmc-continue-shopping-btn').attr('href') || '/shop';
                                
                                $cartContainer.html(`
                                    <div class="ggmc-empty-cart">
                                        <p>Your cart is currently empty.</p>
                                        <a href="${continueUrl}" class="ggmc-continue-shopping-btn">
                                            Continue Shopping
                                        </a>
                                    </div>
                                `);
                            }
                        } else {
                            // Remove item from DOM and update totals
                            $button.closest('.cart-item').fadeOut(300, function() {
                                $(this).remove();
                                
                                // Update the cart total using the safe method
                                if (response.data.cart_total) {
                                    updateCartTotalDisplay(response.data.cart_total);
                                }
                            });
                        }
                        
                        updateCartDisplay(response.data.cart_count, response.data.cart_total);
                        showCartMessage(response.data.message, 'success');

                        // Trigger custom event for other components
                        $(document).trigger('ggm_commerce_cart_updated', {
                            count: response.data.cart_count,
                            total: response.data.cart_total,
                            items: response.data.cart_items || [],
                            action: 'remove_from_cart',
                            cart_empty: response.data.cart_empty
                        });
                    } else {
                        showCartMessage(response.data.message, 'error');
                    }
                },
                error: function() {
                    showCartMessage(getI18n('error_occurred', 'An error occurred. Please try again.'), 'error');
                }
            });
        }
    });
    
    // Update cart display elements
    function updateCartDisplay(count, total) {
        // Update cart count displays (multiple selectors for different widgets)
        $('.ggmc-cart-count:not(td):not(th)').text(count);
        $('.cart-count:not(td):not(th)').text(count);
        
        // Update cart total displays (multiple selectors for different widgets)
        $('.ggmc-cart-total:not(td):not(th)').text('$' + total);
        $('.cart-total:not(td):not(th)').text('$' + parseFloat(total).toFixed(2));
        
        // Update mini cart widget data attributes
        $('.ggmc-mini-cart-widget').attr('data-cart-count', count);
        
        // Update cart icon if it exists
        var $cartIcon = $('.ggmc-cart-icon');
        if ($cartIcon.length) {
            $cartIcon.attr('data-count', count);
        }
    }
    
    // Safely update cart total displays without affecting table structure
    function updateCartTotalDisplay(total) {
        var formattedTotal = '$' + parseFloat(total).toFixed(2);
        
        // Primary method: Use data attributes (most reliable)
        $('[data-cart-total]').html('<strong>' + formattedTotal + '</strong>');
        
        // Update GGM Commerce-specific classes
        $('.ggmc-cart-total:not(td):not(th)').html(formattedTotal);
        
        // Update mini cart widget classes
        $('.cart-total:not(td):not(th)').html(formattedTotal);
        $('.cart-total-display:not(td):not(th)').html('<strong>Total: ' + formattedTotal + '</strong>');
        
        // Fallback methods for other total displays
        $('.order-total:not(td):not(th)').html(formattedTotal);
        $('.cart-summary .total-amount').html(formattedTotal);
        $('.checkout-summary .total-amount').html(formattedTotal);
        $('.ggmc-cart-widget .cart-total').html(formattedTotal);
    }
    
    // Show cart messages with unified notification style
    function showCartMessage(message, type) {
        // Get notification settings from localized config
        var notifyConfig = (typeof ggmCommerceAjax !== 'undefined' && ggmCommerceAjax.notifications)
            ? ggmCommerceAjax.notifications
            : { enabled: '1', position: 'top-right', duration: 3000 };

        // Check if notifications are enabled
        if (notifyConfig.enabled === '0') {
            return;
        }

        type = type || 'info';

        // Remove existing messages
        $('.ggmc-cart-message').remove();

        // Determine icon based on type
        var iconClass = 'eicon-info-circle';
        if (type === 'success') iconClass = 'eicon-check-circle';
        if (type === 'warning') iconClass = 'eicon-warning';
        if (type === 'error') iconClass = 'eicon-close-circle';

        // Build position class
        var positionClass = 'position-' + (notifyConfig.position || 'top-right');

        // Create message element with icon, position class, and close button
        var $message = $('<div class="ggmc-cart-message ' + type + ' ' + positionClass + '">' +
            '<span class="message-icon"><i class="' + iconClass + '"></i></span>' +
            '<span class="message-text">' + message + '</span>' +
            '<button type="button" class="message-close">&times;</button>' +
            '</div>');

        // Add to body
        $('body').append($message);

        // Animate in
        setTimeout(function() {
            $message.addClass('visible');
        }, 10);

        // Auto-hide after configured duration
        var duration = parseInt(notifyConfig.duration, 10) || 3000;
        setTimeout(function() {
            $message.removeClass('visible');
            setTimeout(function() {
                $message.remove();
            }, 300);
        }, duration);

        // Close button handler
        $message.find('.message-close').on('click', function() {
            $message.removeClass('visible');
            setTimeout(function() {
                $message.remove();
            }, 300);
        });
    }
    
    // Quantity input controls for ADD TO CART widget
    $(document).off('click', '.ggmc-qty-plus').on('click', '.ggmc-qty-plus', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var $input = $(this).siblings('.ggmc-quantity-input');
        var currentVal = parseInt($input.val()) || 1;
        var newVal = currentVal + 1;
        
        if (newVal <= 999) {
            $input.val(newVal);
        }
    });
    
    $(document).off('click', '.ggmc-qty-minus').on('click', '.ggmc-qty-minus', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var $input = $(this).siblings('.ggmc-quantity-input');
        var currentVal = parseInt($input.val()) || 1;
        var newVal = currentVal - 1;
        
        if (newVal >= 1) {
            $input.val(newVal);
        }
    });
    
    // Debug: Check all cart quantity inputs on page load
    var uniqueCartItems = {};
    $('.ggmc-cart-quantity').each(function(index) {
        var $input = $(this);
        var cartItemId = $input.data('cart-item-id');

        uniqueCartItems[cartItemId] = (uniqueCartItems[cartItemId] || 0) + 1;
    });
    
    
    // Quantity controls for CART DISPLAY widget (different selectors)
    $(document).off('click.ggmc', '.qty-plus').on('click.ggmc', '.qty-plus', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var $button = $(this);
        var cartItemId = $button.data('cart-item-id');
        var $input = $button.siblings('.ggmc-cart-quantity').first();
        
        // Verify we have the right input
        if ($input.data('cart-item-id') !== cartItemId) {
            return false;
        }
        
        // Use HTML attribute as source of truth
        var currentVal = parseInt($input.attr('value'), 10) || 0;
        var newVal = currentVal + 1;
        
        if (newVal <= 999) {
            $input.val(newVal).attr('value', newVal);
        }
        
        return false;
    });
    
    $(document).off('click.ggmc', '.qty-minus').on('click.ggmc', '.qty-minus', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var $button = $(this);
        var cartItemId = $button.data('cart-item-id');
        var $input = $button.siblings('.ggmc-cart-quantity').first();
        
        // Verify we have the right input
        if ($input.data('cart-item-id') !== cartItemId) {
            return false;
        }
        
        // Use HTML attribute as source of truth
        var currentVal = parseInt($input.attr('value'), 10) || 0;
        var newVal = currentVal - 1;
        
        if (newVal >= 0) {
            $input.val(newVal).attr('value', newVal);
        }
        
        return false;
    });
    
    // Debounce function for performance
    function debounce(func, delay) {
        let timeoutId;
        return function (...args) {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => func.apply(this, args), delay);
        };
    }
    
    // Real-time quantity change handler for cart items (auto-update to server)
    $(document).on('input change', '.ggmc-cart-quantity', debounce(function() {
        var $input = $(this);
        var newQuantity = parseInt($input.val());
        var $row = $input.closest('tr, .cart-item');
        var $priceElement = $row.find('.product-price[data-price]');
        var price = parseFloat($priceElement.data('price'));
        var cartItemId = $input.data('cart-item-id');

        // Handle invalid quantities
        if (isNaN(newQuantity) || newQuantity < 0) {
            newQuantity = 0;
            $input.val(0);
        }

        // Update line total immediately (instant preview)
        if (!isNaN(price) && price > 0) {
            var lineTotal = price * newQuantity;
            var formattedTotal = '$' + lineTotal.toFixed(2);

            // Find the total cell - use product-total class from Cart Display renderer
            var $totalCell = $row.find('.product-total');
            if ($totalCell.length) {
                $totalCell.html(formattedTotal);
            } else {
                // Fallback for other possible selectors
                $row.find('.cart-item-total, .line-total').html(formattedTotal);
            }
        }

        // Recalculate and update cart total in real-time (instant preview)
        recalculateCartTotal();

        // Auto-update cart on server after user stops typing (debounced)
        autoUpdateCartItem(cartItemId, newQuantity);

    }, 800)); // 800ms debounce - waits for user to stop typing

    // Function to recalculate cart total from all line items
    function recalculateCartTotal() {
        var cartTotal = 0;

        // Loop through all cart items and sum up line totals
        $('.ggmc-cart-quantity').each(function() {
            var $input = $(this);
            var $row = $input.closest('tr, .cart-item');
            var $priceElement = $row.find('.product-price[data-price]');
            var price = parseFloat($priceElement.data('price'));
            var quantity = parseInt($input.val()) || 0;

            if (!isNaN(price) && !isNaN(quantity)) {
                cartTotal += price * quantity;
            }
        });

        // Update only the inner HTML of the total cell (preserving table structure)
        var formattedCartTotal = '$' + cartTotal.toFixed(2);
        var $totalCell = $('td[data-cart-total]');
        if ($totalCell.length) {
            $totalCell.html('<strong>' + formattedCartTotal + '</strong>');
        }

        return cartTotal;
    }

    // Auto-update individual cart item on server
    function autoUpdateCartItem(cartItemId, quantity) {
        // Build updates object with single item
        var updates = {};
        updates[cartItemId] = quantity;

        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_update_cart',
                updates: updates,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Update cart count in header/widgets
                    updateCartDisplay(response.data.cart_count, response.data.cart_total);

                    // Update the total line with proper formatting (only the TD content, not the whole row)
                    if (response.data.cart_total !== undefined) {
                        var formattedTotal = '$' + parseFloat(response.data.cart_total).toFixed(2);
                        var $totalCell = $('td[data-cart-total]');
                        if ($totalCell.length) {
                            $totalCell.html('<strong>' + formattedTotal + '</strong>');
                        }
                    }

                    // Trigger custom event for mini cart and other widgets
                    $(document).trigger('ggm_commerce_cart_updated', {
                        count: response.data.cart_count,
                        total: response.data.cart_total,
                        items: response.data.cart_items || [],
                        action: 'update_cart'
                    });

                    // If quantity is 0, remove the row
                    if (quantity === 0 && response.data.updated_items && response.data.updated_items[cartItemId]) {
                        var $row = $('.ggmc-cart-quantity[data-cart-item-id="' + cartItemId + '"]').closest('tr, .cart-item');
                        $row.fadeOut(300, function() {
                            $(this).remove();
                            // Check if cart is now empty
                            if ($('.ggmc-cart-quantity').length === 0) {
                                location.reload();
                            }
                        });
                    }
                } else {
                }
            },
            error: function(xhr, status, error) {
            }
        });
    }

    // Update Cart button handler
    $(document).on('click', '.ggmc-update-cart-btn', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var updates = {};
        var hasChanges = false;
        
        // Collect all quantity changes
        $('.ggmc-cart-quantity').each(function() {
            var $input = $(this);
            var cartItemId = $input.data('cart-item-id');
            var newQuantity = parseInt($input.val());
            
            // Handle NaN or empty values
            if (isNaN(newQuantity) || newQuantity < 0) {
                newQuantity = 0;
            }
            
            
            // Store the update
            updates[cartItemId] = newQuantity;
            hasChanges = true;
        });
        
        if (!hasChanges) {
            showCartMessage(getI18n('no_changes', 'No changes to update.'), 'error');
            return;
        }
        
        // Disable button and show loading state
        $button.prop('disabled', true).text('Updating...');
        
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_update_cart',
                updates: updates,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success) {
                    showCartMessage(response.data.message, 'success');
                    
                    // Update cart display dynamically instead of reloading
                    updateCartDisplay(response.data.cart_count, response.data.cart_total);
                    
                    // Process updated items from server response
                    if (response.data.updated_items) {
                        $.each(response.data.updated_items, function(cartItemId, itemData) {
                            var $row = $('.ggmc-cart-quantity[data-cart-item-id="' + cartItemId + '"]').closest('tr, .cart-item');
                            
                            if (itemData.quantity <= 0) {
                                // Remove the row with a smooth animation
                                $row.fadeOut(300, function() {
                                    $(this).remove();
                                    // Check if cart is empty
                                    if ($('.ggmc-cart-quantity').length === 0) {
                                        location.reload(); // Only reload if cart becomes empty
                                    }
                                });
                            } else {
                                // Update quantity input (in case it was corrected server-side)
                                $row.find('.ggmc-cart-quantity').val(itemData.quantity);

                                // Update line total with proper selector
                                var formattedTotal = '$' + parseFloat(itemData.line_total).toFixed(2);
                                var $totalCell = $row.find('.product-total');
                                if ($totalCell.length) {
                                    $totalCell.html(formattedTotal);
                                } else {
                                    // Fallback for other possible selectors
                                    $row.find('.cart-item-total, .line-total').html(formattedTotal);
                                }

                                // Clear visual indicators
                                $row.removeClass('quantity-changed will-be-removed');
                            }
                        });
                    }
                    
                    // Update main cart total display safely (only the TD content, not the whole row)
                    if (response.data.cart_total !== undefined) {
                        var formattedTotal = '$' + parseFloat(response.data.cart_total).toFixed(2);
                        var $totalCell = $('td[data-cart-total]');
                        if ($totalCell.length) {
                            $totalCell.html('<strong>' + formattedTotal + '</strong>');
                        }
                        updateCartTotalDisplay(response.data.cart_total);
                    }

                    // Clear all visual indicators
                    $('.quantity-changed, .will-be-removed').removeClass('quantity-changed will-be-removed');
                    $('.ggmc-update-cart-btn').removeClass('has-changes');

                    // Trigger custom event for other components
                    $(document).trigger('ggm_commerce_cart_updated', {
                        count: response.data.cart_count,
                        total: response.data.cart_total,
                        items: response.data.cart_items || [],
                        action: 'update_cart'
                    });
                } else {
                    showCartMessage(response.data.message, 'error');
                }
                
                $button.prop('disabled', false).text('Update Cart');
            },
            error: function() {
                showCartMessage(getI18n('error_occurred', 'An error occurred. Please try again.'), 'error');
                $button.prop('disabled', false).text('Update Cart');
            }
        });
    });
});