/**
 * WCMLIM Stock Refresh Script
 * 
 * Ensures stock information is always up-to-date by refreshing
 * stock display on page load and after location changes.
 */
jQuery(document).ready(function($) {
    // Function to load stock information for product
    function loadStockInfo(productId) {
        var container = $('.wcmlim-stock-container[data-product-id="' + productId + '"]');
        
        if (container.length) {
            container.find('.wcmlim-stock').hide();
            container.find('.wcmlim-loading').show();
            
            $.ajax({
                url: multi_inventory.ajaxurl,
                type: 'POST',
                data: {
                    action: 'wcmlim_load_stock',
                    product_id: productId,
                    security: multi_inventory.nonce
                },
                success: function(response) {
                    if (response.success && response.data) {
                        container.html('<span class="wcmlim-stock">' + response.data + '</span>');
                    } else {
                        // container.html('<span class="wcmlim-stock">Stock information unavailable</span>');
                    }
                },
                error: function() {
                    container.html('<span class="wcmlim-stock">Error loading stock information</span>');
                }
            });
        }
    }
    
    // Load stock information for all products on page
    $('.wcmlim-stock-container').each(function() {
        var productId = $(this).data('product-id');
        if (!$(this).find('.wcmlim-stock').length) {
            loadStockInfo(productId);
        }
    });
    
    // Refresh stock when location selection changes
    $(document).on('change', '#select_location, #wcmlim-change-lc-select', function() {
        // Add a small delay to ensure cookies are updated first
        setTimeout(function() {
            $('.wcmlim-stock-container').each(function() {
                var productId = $(this).data('product-id');
                loadStockInfo(productId);
            });
        }, 200);
    });
    
    // Also refresh after page navigation events
    $(document).on('click', '.woocommerce-pagination a', function() {
        $(window).on('load', function() {
            $('.wcmlim-stock-container').each(function() {
                var productId = $(this).data('product-id');
                loadStockInfo(productId);
            });
        });
    });
});
