jQuery(document).ready(function($) {
    // ===== Common Utility Functions =====
    
    // Function to set cookie
    function setLocation(name, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    
    // Function to get cookie
    function getLocation(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    $.ajax({
        url: wc_add_to_cart_params.ajax_url,
        type: 'POST',
        data: {
            action: 'wcmlim_trigger_location_price',
            security: wc_add_to_cart_params.security ?? null,
        },
        success: function(response) {
            jQuery('.location-stock-item').removeClass('highlighted');
            jQuery('.location-stock-item').removeClass('selected');
            jQuery(`.location-stock-item[data-location-id="${response['data']}"]`).trigger('click');
            jQuery(`.location-stock-item[data-location-id="${response['data']}"]`).addClass('highlighted');
        },
        error: function() {}
    });
    
    // ===== Common Variable Product Handling =====
    
    function handleVariationChange() {
        if ($('form.variations_form').length) {
            // Store the selected group for later use
            var selectedGroup = '';
            if ($('#location-stock-cards').data('group-enabled') || 
                $('#location-stock-list').data('group-enabled') || 
                $('.location-stock-text-container').data('group-enabled')) {
                selectedGroup = $('#wcmlim-location-group').val();
            }
            
            // Hide location elements initially for variable products
            if ($('#location-stock-table-variable').length) {
                $('.location-stock-row').hide();
                $('#variable-product-message').show();
                $('#location-stock-table-variable').show(); // Show the table container itself
            } else if ($('.location-stock-text-container').length) {
                $('.location-stock-item').hide();
                $('.variable-product-message').show();
            } else if ($('#location-stock-list').length) {
                $('#location-stock-list li:not(#variable-product-message):not(#select-group-message)').hide();
                
                // Check if using location groups
                if ($('#wcmlim-location-group').length) {
                    if (!selectedGroup) {
                        $('#variable-product-message').hide();
                        $('#select-group-message').show();
                    } else {
                        $('#select-group-message').hide();
                        $('#variable-product-message').show();
                    }
                } else {
                    $('#variable-product-message').show();
                }
            } else if ($('#location-stock-cards').length) {
                // For card view with location groups enabled
                $('#location-stock-cards .location-stock-card').hide();
                
                if ($('#location-stock-cards').data('group-enabled')) {
                    // If no group is selected, show group message
                    if (!selectedGroup) {
                        $('#variable-product-message').hide();
                        $('#select-group-message').show();
                    } else {
                        $('#select-group-message').hide();
                        $('#variable-product-message').show();
                    }
                } else {
                    // No groups, just show variable message
                    $('#variable-product-message').show();
                }
            }
            
            // Listen for variation change
            $('form.variations_form').on('woocommerce_variation_has_changed', function() {
                var selectedVariationId = $('input[name="variation_id"]').val();
                
                // Get the selected group again in case it changed
                if ($('#wcmlim-location-group').length) {
                    selectedGroup = $('#wcmlim-location-group').val();
                }
                
                if (selectedVariationId) {
                    var hasLocationGroup = $('#wcmlim-location-group').length > 0;
                    
                    // Table View
                    if ($('#location-stock-table-variable').length) {
                        if (hasLocationGroup && !selectedGroup) {
                            // If groups enabled but none selected, don't show locations
                            $('#variable-product-message').hide();
                            $('#select-group-message').show();
                            $('.location-stock-row').hide();
                        } else {
                            $('#variable-product-message').hide();
                            $('#select-group-message').hide();
                            
                            // If groups enabled, only show rows for the selected group
                            if (hasLocationGroup && selectedGroup) {
                                $('.location-stock-row').hide();
                                $('.location-stock-row').each(function() {
                                    var locationId = $(this).data('location-id');
                                    if (wcmlimGroupLocations[selectedGroup] && 
                                        wcmlimGroupLocations[selectedGroup].indexOf(locationId) !== -1) {
                                        $(this).fadeIn();
                                    }
                                });
                            } else {
                                $('.location-stock-row').fadeIn();
                            }
                            $('#location-stock-table-variable').show();
                        }
                    } 
                    // Simple Text View
                    else if ($('.location-stock-text-container').length) {
                        if (hasLocationGroup && !selectedGroup) {
                            $('.variable-product-message').hide();
                            $('#select-group-message').show();
                            $('.location-stock-item').hide();
                        } else {
                            $('.variable-product-message').hide();
                            $('#select-group-message').hide();
                            
                            if (hasLocationGroup && selectedGroup) {
                                $('.location-stock-item').hide();
                                $('.location-stock-item').each(function() {
                                    var locationId = $(this).data('location-id');
                                    if (wcmlimGroupLocations[selectedGroup] && 
                                        wcmlimGroupLocations[selectedGroup].indexOf(locationId) !== -1) {
                                        $(this).fadeIn();
                                    }
                                });
                            } else {
                                $('.location-stock-item').fadeIn();
                            }
                        }
                    }
                    // Expanded View
                    else if ($('#location-stock-list').length) {
                        if (hasLocationGroup && !selectedGroup) {
                            $('#variable-product-message').hide();
                            $('#select-group-message').show();
                            $('#location-stock-list li:not(#variable-product-message):not(#select-group-message)').hide();
                        } else {
                            $('#variable-product-message').hide();
                            $('#select-group-message').hide();
                            
                            if (hasLocationGroup && selectedGroup) {
                                $('#location-stock-list li:not(#variable-product-message):not(#select-group-message)').hide();
                                $('#location-stock-list li').each(function() {
                                    if (!$(this).is('#variable-product-message') && !$(this).is('#select-group-message')) {
                                        var locationId = $(this).data('location-id');
                                        if (wcmlimGroupLocations[selectedGroup] && 
                                            wcmlimGroupLocations[selectedGroup].indexOf(locationId) !== -1) {
                                            $(this).fadeIn();
                                        }
                                    }
                                });
                            } else {
                                $('#location-stock-list li:not(#variable-product-message):not(#select-group-message)').fadeIn();
                            }
                        }
                    }
                    // Card View
                    else if ($('#location-stock-cards').length) {
                        // Check if location groups are enabled
                        var groupsEnabled = $('#location-stock-cards').data('group-enabled');
                        
                        if (groupsEnabled) {
                            // Only show cards if a group is selected
                            if (selectedGroup) {
                                $('#variable-product-message').hide();
                                $('#select-group-message').hide();
                                // Show only cards that match the selected group
                                $('.location-stock-card').hide();
                                $('.location-stock-card').each(function() {
                                    var locationId = $(this).data('location-id');
                                    if (wcmlimGroupLocations[selectedGroup] && 
                                        wcmlimGroupLocations[selectedGroup].indexOf(locationId) !== -1) {
                                        $(this).fadeIn();
                                    }
                                });
                            } else {
                                // Keep showing the group selection message if no group is selected
                                $('#variable-product-message').hide();
                                $('#select-group-message').show();
                                $('.location-stock-card').hide();
                            }
                        } else {
                            // No groups, show all cards
                            $('#variable-product-message').hide();
                            $('.location-stock-card').fadeIn();
                        }
                    }
                    
                    // Update stock display for each location
                    updateLocationStockForVariation(selectedVariationId);
                    
                    // Re-apply highlighting to previously selected location
                    highlightSelectedLocation();
                    
                    // IMPORTANT: Preserve the visibility of the quantity and add to cart elements
                    // This ensures they don't disappear when selecting variations
                    $('.woocommerce-variation-add-to-cart').show();
                } else {
                    // Hide location elements when no variation is selected
                    if ($('#location-stock-table-variable').length) {
                        $('.location-stock-row').hide();
                        if (hasLocationGroup && !selectedGroup) {
                            $('#variable-product-message').hide();
                            $('#select-group-message').show();
                        } else {
                            $('#select-group-message').hide();
                            $('#variable-product-message').show();
                        }
                    } else if ($('.location-stock-text-container').length) {
                        $('.location-stock-item').hide();
                        if (hasLocationGroup && !selectedGroup) {
                            $('.variable-product-message').hide();
                            $('#select-group-message').show();
                        } else {
                            $('#select-group-message').hide();
                            $('.variable-product-message').show();
                        }
                    } else if ($('#location-stock-list').length) {
                        $('#location-stock-list li:not(#variable-product-message):not(#select-group-message)').hide();
                        if (hasLocationGroup && !selectedGroup) {
                            $('#variable-product-message').hide();
                            $('#select-group-message').show();
                        } else {
                            $('#select-group-message').hide();
                            $('#variable-product-message').show();
                        }
                    } else if ($('#location-stock-cards').length) {
                        // For card view with location groups
                        $('.location-stock-card').hide();
                        
                        if ($('#location-stock-cards').data('group-enabled')) {
                            // If a group is selected, show variable message
                            if (selectedGroup) {
                                $('#select-group-message').hide();
                                $('#variable-product-message').show();
                            } else {
                                // Otherwise show group message
                                $('#variable-product-message').hide();
                                $('#select-group-message').show();
                            }
                        } else {
                            // No groups, just show variable message
                            $('#variable-product-message').show();
                        }
                    }
                }
            });
            
            // Preserve form elements when selection changes
            $('form.variations_form').on('show_variation', function(event, variation) {
                // Make sure the add to cart button and quantity inputs remain visible
                $('.woocommerce-variation-add-to-cart').show();
                $('.quantity').show();
                $('.single_add_to_cart_button').show();
            });
        }
    }
    
    function updateLocationStockForVariation(variationId) {
        // Common AJAX update function for all views
        $('[data-location-id]').each(function() {
            console.log($(this));
            console.log('ajax calling');
            var locationId = $(this).data('location-id');
            var $stockDisplay = $(this).find('.wclim-views_subinfo, .stock-quantity');
            
            // Check if location cards should be visible (for location groups)
            var shouldBeVisible = true;
            var $locationCards = $('#location-stock-cards');
            
            if ($locationCards.data('group-enabled')) {
                var selectedGroup = $('.wclim_select_location select').val();
                var cardGroup = $(this).data('location-group');
                shouldBeVisible = (cardGroup === selectedGroup);
            }
            
            // Only make AJAX call for relevant cards (visible cards or ones that should be visible)
            if (shouldBeVisible) {
                // Show loading indicator
                $stockDisplay.text('Loading...').css('color', 'grey');
                $.ajax({
                    url: wc_add_to_cart_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'wcmlim_get_variation_location_stock',
                        variation_id: variationId,
                        location_id: locationId,
                        security: wc_add_to_cart_params.security
                    },
                    success: function(response) {
                        if (response.success) {
                            var stockText = response.data.stock_text;
                            var stockColor = response.data.stock_color;
                            var stockQty = response.data.stock_qty || 0;
                            
                            // Update stock display
                            $stockDisplay.text(stockText).css('color', stockColor);
                            $stockDisplay.parent().css('background-color', response.data.stock_bgcolor);
                            $stockDisplay.parent().css('border-radius', response.data.stock_radius);
                            $stockDisplay.parent().css('color', response.data.stock_color);
                            
                            // Also update data attributes for the card/row
                            $stockDisplay.closest('[data-location-id]').attr('data-lc-qty', stockQty);
                            
                            // Handle additional price data if available
                            if (response.data.regular_price) {
                                $stockDisplay.closest('[data-location-id]').attr('data-regular-price', response.data.regular_price);
                            }
                            if (response.data.sale_price) {
                                jQuery('.location-stock-item').removeClass('highlighted');
                                jQuery('.location-stock-item').each(function() {
                                    let locid = jQuery(this).attr('data-location-id');
                                    if(locid == response.data.selected_location_termid) {
                                        jQuery(this).addClass('highlighted');
                                    }
                                });
                                $stockDisplay.closest('[data-location-id]').attr('data-sale-price', response.data.sale_price);
                                $stockDisplay.closest('.location-stock-item').find('input[type=radio]').attr('data-lc-sale-price', `${response.data.sale_price}`);
                                $stockDisplay.closest('.location-stock-item').find('input[type=radio]').attr('data-lc-regular-price', `${response.data.regular_price}`);
                            }
                        } else {
                            $stockDisplay.text('Error').css('color', 'red');
                        }

                        // Handle hiding out of stock locations for variable products
                        if (response.data.should_hide_location === true) {
                            var locationId = response.data.data_location_id;
                            
                            // Hide in all view types
                            $('.location-stock-item[data-location-id="' + locationId + '"]').addClass('wcmlim-hide_out_of_stock_location').hide();
                            $('.location-stock-row[data-location-id="' + locationId + '"]').addClass('wcmlim-hide_out_of_stock_location').hide();
                            $('.location-stock-card[data-location-id="' + locationId + '"]').addClass('wcmlim-hide_out_of_stock_location').hide();
                            $('.wcmlim_radio_option[data-location-id="' + locationId + '"]').addClass('wcmlim-hide_out_of_stock_location').hide();
                            $('option[data-location-id="' + locationId + '"]').hide();
                            $('tr[data-location-id="' + locationId + '"]').addClass('wcmlim-hide_out_of_stock_location').hide();
                        } else {
                            var locationId = response.data.data_location_id;
                            
                            // Show in all view types
                            $('.location-stock-item[data-location-id="' + locationId + '"]').removeClass('wcmlim-hide_out_of_stock_location').show();
                            $('.location-stock-row[data-location-id="' + locationId + '"]').removeClass('wcmlim-hide_out_of_stock_location').show();
                            $('.location-stock-card[data-location-id="' + locationId + '"]').removeClass('wcmlim-hide_out_of_stock_location').show();
                            $('.wcmlim_radio_option[data-location-id="' + locationId + '"]').removeClass('wcmlim-hide_out_of_stock_location').show();
                            $('option[data-location-id="' + locationId + '"]').show();
                            $('tr[data-location-id="' + locationId + '"]').removeClass('wcmlim-hide_out_of_stock_location').show();
                        }

                    },
                    error: function() {
                        $stockDisplay.text('Error').css('color', 'red');
                    }
                });
            }
        });
    }
    
    // ===== Highlighting Selected Locations =====
    
    function highlightSelectedLocation() {
        var selectedLocationKey = getLocation("wcmlim_selected_location");
        var selectedLocationId = getLocation("wcmlim_selected_location_termid");
        
        if (selectedLocationKey && selectedLocationId) {
            // Table View
            if ($('#location-stock-table-simple').length || $('#location-stock-table-variable').length) {
                $('.location-stock-row').removeClass('highlighted');
                var $selectedRow = $('.location-stock-row[data-location-key="' + selectedLocationKey + '"]');
                if ($selectedRow.length) {
                    $selectedRow.addClass('highlighted');
                }
            } 
            // Simple Text View
            else if ($('.location-stock-text-container').length) {
                $('.location-stock-item').removeClass('highlighted');
                var $selectedItem = $('.location-stock-item[data-location-key="' + selectedLocationKey + '"]');
                if ($selectedItem.length) {
                    $selectedItem.addClass('highlighted');
                }
            }
            // Expanded View
            else if ($('#location-stock-list').length) {
                $('.location-list-item').removeClass('highlighted');
                var $selectedItem = $('.location-list-item[data-location-key="' + selectedLocationKey + '"]');
                if ($selectedItem.length) {
                    $selectedItem.addClass('highlighted');
                    $selectedItem.find('.toggle-details')
                        .removeClass('fa-plus').addClass('fa-minus');
                    $selectedItem.find('.extra-details').show();
                }
            }
            // Card View
            else if ($('#location-stock-cards').length) {
                $('.location-stock-card').removeClass('selected');
                var $selectedCard = $('.location-stock-card[data-location-id="' + selectedLocationId + '"]');
                if ($selectedCard.length) {
                    $selectedCard.addClass('selected');
                }
            }
        }
    }
    
    // ===== View Specific Setup Functions =====
    
    function setupTableView() {
        // Check if we have a table view
        const tableSimple = $('#location-stock-table-simple');
        const tableVariable = $('#location-stock-table-variable');
        
        if (!tableSimple.length && !tableVariable.length) return;
        
        // Variables to track state
        let selectedGroupId = null;
        let selectedVariationId = null;
        const isVariableProduct = tableVariable.length > 0;
        const groupsEnabled = $('#wcmlim-location-group').length > 0;
        
        // Cache DOM elements
        const locationTable = tableSimple.length ? tableSimple : tableVariable;
        const locationGroupDropdown = $('#wcmlim-location-group');
        const locationRows = $('.location-stock-row');
        const groupMessage = $('#select-group-message');
        const variableMessage = $('#variable-product-message');
        
        // Function to hide all location rows in the table
        function hideAllLocationRows() {
            locationRows.hide();
        }
        
        // Function to update the table view based on current selections
        function updateTableViewState() {
            
            // Hide all rows initially
            hideAllLocationRows();
            
            // For variable products
            if (isVariableProduct) {
                if (groupsEnabled) {
                    // If no group selected, show group message
                    if (!selectedGroupId) {
                        if (groupMessage) groupMessage.show();
                        if (variableMessage) variableMessage.hide();
                        locationTable.hide();
                    } 
                    // If group selected but no variation, show variation message
                    else if (!selectedVariationId) {
                        if (groupMessage) groupMessage.hide();
                        if (variableMessage) variableMessage.show();
                        locationTable.show();
                    } 
                    // Both group and variation selected - show filtered locations
                    else {
                        if (groupMessage) groupMessage.hide();
                        if (variableMessage) variableMessage.hide();
                        locationTable.show();
                        
                        // Show only rows for the selected group
                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroupId]) {
                            wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                                $('.location-stock-row[data-location-id="' + locationId + '"]').show();
                            });
                        }
                    }
                } 
                // Variable product without location groups
                else {
                    locationTable.show();
                    
                    // If variation selected, show all rows
                    if (selectedVariationId) {
                        if (variableMessage) variableMessage.hide();
                        locationRows.show();
                    } 
                    // If no variation selected, show message
                    else {
                        if (variableMessage) variableMessage.show();
                    }
                }
            } 
            // For simple products
            else {
                if (groupsEnabled) {
                    // If no group selected, show message and hide table
                    if (!selectedGroupId) {
                        if (groupMessage) groupMessage.show();
                        locationTable.hide();
                    } else {
                        // Group selected, hide message and show filtered rows
                        if (groupMessage) groupMessage.hide();
                        locationTable.show();
                        
                        // Only show rows from selected group
                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroupId]) {
                            wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                                $('.location-stock-row[data-location-id="' + locationId + '"]').show();
                            });
                        }
                    }
                } else {
                    // Simple product without location groups - show all rows
                    locationTable.show();
                    locationRows.show();
                }
            }
            
            // Highlight the selected location if any
            highlightSelectedLocation();
        }
        
        // Handle location group change
        if (locationGroupDropdown.length) {
            locationGroupDropdown.on('change', function() {
                selectedGroupId = $(this).val() || null;
                updateTableViewState();
            });
            
            // Initialize with current selection
            locationGroupDropdown.trigger('change');
        } else if (!isVariableProduct) {
            // If no groups and simple product, show the table and all rows
            locationTable.show();
            locationRows.show();
        }
        
        // Handle variable product variation changes
        if (isVariableProduct) {
            $('form.variations_form').on('show_variation', function(event, variation) {
                selectedVariationId = variation.variation_id;
                updateTableViewState();
                
                // Update stock information for displayed rows
                updateStockForVariation(selectedVariationId);
            });
            
            $('form.variations_form').on('reset_data', function() {
                selectedVariationId = null;
                updateTableViewState();
            });
        }
        
        
        // Handle row click events to set location
        $(document).on('click', '.location-stock-row', function() {
            var $row = $(this);
            var locationId = $row.data('location-id');
            var locationKey = $row.data('location-key');
            
            // Remove highlight from all rows
            locationRows.removeClass('highlighted');
            
            // Add highlight to clicked row
            $row.addClass('highlighted');
            
            // Set cookies for selected location
            setLocation("wcmlim_selected_location", locationKey.toString(), 30);
            setLocation("wcmlim_selected_location_termid", locationId.toString(), 30);
            
            // Update hidden fields for add to cart
            var $radioInput = $row.find('input[type="radio"]');
            var stockQty = $radioInput.data('lc-qty') || $row.find('.wclim-views_subinfo').text();
            var regularPrice = $radioInput.data('lc-regular-price') || $row.data('regular-price') || '';
            var salePrice = $radioInput.data('lc-sale-price') || $row.data('sale-price') || '';
            
            $('#lc_qty').val(stockQty);
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
            
            // Check the radio button
            if ($radioInput.length) {
                $radioInput.prop('checked', true);
            }
        });
        
        // Initialize with highlighting
        highlightSelectedLocation();
    }
    
    function setupSimpleTextView() {
        highlightSelectedLocation();
        
        // Set cookies and highlight on click
        $(document).on('click', '.location-stock-item', function(e) {
            var $item = $(this);
            
            // Get location data from the clicked item
            var locationId = $item.data('location-id');
            var locationKey = $item.data('location-key');
            
            // Remove highlight from all items and add it to the clicked one
            $('.location-stock-item').removeClass('highlighted');
            $item.addClass('highlighted');
            
            // Set cookies for selected location
            setLocation("wcmlim_selected_location", locationKey.toString(), 30);
            setLocation("wcmlim_selected_location_termid", locationId.toString(), 30);
            
            // Update hidden fields for add to cart
            $('#lc_qty').val($item.find('.wclim-views_subinfo').text());
            
            // Handle price data if available
            var regularPrice = $item.data('regular-price') || '';
            var salePrice = $item.data('sale-price') || '';
            
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
    }
    
    function setupExpandedView() {
        highlightSelectedLocation();
        
        // Variables to track state
        let selectedGroupId = null;
        let selectedVariationId = null;
        const isVariableProduct = $('form.variations_form').length > 0;
        const groupsEnabled = $('#wcmlim-location-group').length > 0;

        // Cache DOM elements
        const locationGroupDropdown = $('#wcmlim-location-group');
        const locationItems = $('.location-list-item:not(#select-group-message, #variable-product-message)');
        const groupMessage = $('#select-group-message');
        const variableMessage = $('#variable-product-message');

        // Initialize view state
        function updateExpandedViewState() {

            // Hide all location items first
            locationItems.hide();

            // For variable products
            if (isVariableProduct) {
                if (groupsEnabled) {
                    if (!selectedGroupId) {
                        groupMessage.show();
                        variableMessage.hide();
                    } else if (!selectedVariationId) {
                        groupMessage.hide();
                        variableMessage.show();
                    } else {
                        groupMessage.hide();
                        variableMessage.hide();

                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroupId]) {
                            wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                                $('.location-list-item[data-location-id="' + locationId + '"]').show();
                            });
                        }
                    }
                } else {
                    // For variable products without location groups
                    groupMessage.hide();
                    
                    if (!selectedVariationId) {
                        // Show the variation selection message
                        variableMessage.show();
                    } else {
                        // Hide the message and show all locations when variation is selected
                        variableMessage.hide();
                        locationItems.show();
                    }
                }
            } else {
                // Simple product logic
                if (groupsEnabled) {
                    if (!selectedGroupId) {
                        groupMessage.show();
                    } else {
                        groupMessage.hide();

                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroupId]) {
                            wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                                $('.location-list-item[data-location-id="' + locationId + '"]').show();
                            });
                        }
                    }
                } else {
                    locationItems.show();
                }
            }
        }

        // Handle location group change
        if (locationGroupDropdown.length) {
            locationGroupDropdown.on('change', function() {
                selectedGroupId = $(this).val() || null;
                updateExpandedViewState();
            });

            locationGroupDropdown.trigger('change');
        }

        // Handle variation selection for variable products
        if (isVariableProduct) {
            $('form.variations_form').on('show_variation', function(event, variation) {
                selectedVariationId = variation.variation_id;
                updateExpandedViewState();
            });

            $('form.variations_form').on('reset_data', function() {
                selectedVariationId = null;
                updateExpandedViewState();
            });
        }
        
        // Delegate click event on .location-name
        $(document).on('click', '.location-name', function(e) {
            var $item = $(this).closest('.location-list-item');
            var $icon = $item.find('.toggle-details');
            var $details = $item.find('.extra-details');
            var isOpen = $details.is(':visible'); // check if details are currently visible
    
            if (!isOpen) {
                // Close any other open items
                $('.location-list-item').not($item).each(function() {
                    $(this).removeClass('highlighted');
                    $(this).find('.extra-details').slideUp();
                    $(this).find('.toggle-details').removeClass('fa-minus').addClass('fa-plus');
                });
    
                // Open the clicked item
                $details.slideDown();
                $icon.removeClass('fa-plus').addClass('fa-minus');
                $item.addClass('highlighted');
    
                // Retrieve location data and set cookies
                var locationId = $item.data('location-id');
                var locationKey = $item.data('location-key');
                setLocation("wcmlim_selected_location", locationKey.toString(), 30);
                setLocation("wcmlim_selected_location_termid", locationId.toString(), 30);
    
                // Update hidden fields for add to cart and prices if available
                $('#lc_qty').val($item.find('.wclim-views_subinfo').text());
                var regularPrice = $item.data('regular-price') || '';
                var salePrice = $item.data('sale-price') || '';
                if (regularPrice) { $('#lc_regular_price').val(regularPrice); }
                if (salePrice) { $('#lc_sale_price').val(salePrice); }
            } else {
                // Collapse the details and remove highlight
                $details.slideUp();
                $icon.removeClass('fa-minus').addClass('fa-plus');
                $item.removeClass('highlighted');
            }
        });
    }
    
    function setupCardView() {
        // Create a mapping of term_id to original location key to preserve sorting
        var locationKeyMap = {};
        $('.location-stock-card').each(function() {
            var locationId = $(this).data('location-id');
            var locationKey = $(this).data('location-key');
            locationKeyMap[locationId] = locationKey;
        });
        
        highlightSelectedLocation();
        
        // Check if location groups are enabled
        var groupsEnabled = $('#location-stock-cards').data('group-enabled');
        
        // Get DOM elements for card view
        const locationGroupDropdown = $('#wcmlim-location-group');
        const locationCards = $('.location-stock-card');
        const groupMessage = $('#select-group-message');
        const variableMessage = $('#variable-product-message');
        const isVariableProduct = $('form.variations_form').length > 0;
        let selectedVariationId = null;
        
        // Handle location group dropdown change if groups are enabled
        if (groupsEnabled) {
            $(document).on('change', '.wclim_select_location select, #wcmlim-location-group', function() {
                var selectedGroup = $(this).val();
                
                // Hide all cards first
                locationCards.hide();
                
                if (selectedGroup) {
                    // Check if we're on a variable product page
                    if (isVariableProduct) {
                        selectedVariationId = $('input[name="variation_id"]').val();
                        
                        if (selectedVariationId && selectedVariationId !== '') {
                            // If variation is selected, show relevant cards and hide messages
                            if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroup]) {
                                wcmlimGroupLocations[selectedGroup].forEach(function(locationId) {
                                    $('.location-stock-card[data-location-id="' + locationId + '"]').fadeIn();
                                });
                            }
                            groupMessage.hide();
                            variableMessage.hide();
                            
                            // Re-fetch stock information for the variation
                            updateLocationStockForVariation(selectedVariationId);
                        } else {
                            // If no variation selected, hide cards and show variation message
                            groupMessage.hide();
                            variableMessage.show();
                        }
                    } else {
                        // For simple products, just show cards from the selected group
                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroup]) {
                            wcmlimGroupLocations[selectedGroup].forEach(function(locationId) {
                                $('.location-stock-card[data-location-id="' + locationId + '"]').fadeIn();
                            });
                        }
                        groupMessage.hide();
                    }
                } else {
                    // If no group selected, show the message
                    groupMessage.show();
                    variableMessage.hide();
                }
                
                // Reset selected location
                $('.location-stock-card').removeClass('selected');
            });
            
            // Trigger change event to initialize the view based on any pre-selected group
            locationGroupDropdown.trigger('change');
        } else {
            // If location groups are not enabled
            if (isVariableProduct) {
                // For variable products without groups, we'll handle visibility in variation change
                variableMessage.show();
                locationCards.hide();
            } else {
                // For simple products without groups, show all cards
                locationCards.show();
            }
        }
        
        // Handle click on location cards
        $(document).on('click', '.location-stock-card', function(e) {
            var $card = $(this);
            
            // Skip if the card is not visible (filtered out by group or variation)
            if (!$card.is(':visible')) {
                return;
            }
            
            var locationId = $card.data('location-id');
            var locationKey = $card.data('location-key');
            
            // Remove selected class from all cards
            $('.location-stock-card').removeClass('selected');
            
            // Add selected class to this card
            $card.addClass('selected');
            
            // Store mapping of this location ID to its key
            locationKeyMap[locationId] = locationKey;
            
            // Set cookies for selected location
            setLocation("wcmlim_selected_location", locationKey.toString(), 30);
            setLocation("wcmlim_selected_location_termid", locationId.toString(), 30);
            
            // Update hidden fields for add to cart
            $('#lc_qty').val($card.find('.stock-quantity').text());
            
            // Handle price data if available
            var regularPrice = $card.data('regular-price') || '';
            var salePrice = $card.data('sale-price') || '';
            
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
        
        // Listen for variation changes
        if (isVariableProduct) {
            $('form.variations_form').on('show_variation', function(event, variation) {
                selectedVariationId = variation.variation_id;
                
                // Update view based on selection
                if (groupsEnabled) {
                    if (locationGroupDropdown.val()) {
                        locationGroupDropdown.trigger('change');
                    }
                } else {
                    // For variable products without groups, show all cards when variation is selected
                    variableMessage.hide();
                    locationCards.fadeIn();
                    
                    // Update stock info for all cards
                    updateLocationStockForVariation(selectedVariationId);
                }
            });
            
            $('form.variations_form').on('reset_data', function() {
                selectedVariationId = null;
                
                if (groupsEnabled) {
                    if (locationGroupDropdown.val()) {
                        // Show variable message and hide cards
                        variableMessage.show();
                        locationCards.hide();
                    }
                } else {
                    // Hide cards and show variable message
                    variableMessage.show();
                    locationCards.hide();
                }
            });
        }
    }
    
    function setupSelectView() {
        // Check if we're in a Select View
        if (!$('#select_location').length) return;
        if(!$('#wcmlim-change-sl-select').length) return;
        // Variables to store references to key elements
        var mainLocationSelect = document.getElementById('select_location');
        var locationGroupDropdown = document.querySelector('.wcmlim-location-group-dropdown');
        var storeDropdown = document.querySelector('.wclim_select_location select');
        var isVariableProduct = $('form.variations_form').length > 0;

        // Reset the main product location dropdown
        if (mainLocationSelect) {
            // Reset to the default '-1' option
            mainLocationSelect.value = '-1';
            
            // Trigger a change event to ensure any listeners update accordingly
            var changeEvent = new Event('change', { bubbles: true });
            mainLocationSelect.dispatchEvent(changeEvent);
        }
        
        // Also reset the store location dropdown (from shortcode)
        var storeSelectElement = document.getElementById('wcmlim-change-sl-select');
        if (storeSelectElement) {
            // Reset to the empty value option (Select Location)
            storeSelectElement.value = '';
            
            // Trigger a change event
            var storeChangeEvent = new Event('change', { bubbles: true });
            storeSelectElement.dispatchEvent(changeEvent);
        }
        
        // Hide location details until a selection is made
        var locationDetails = document.getElementById('locationDetails');
        if (locationDetails) {
            locationDetails.style.display = 'none';
        }
        
        // Add a short delay and check again (for dropdowns that might be loaded after DOM content loaded)
        setTimeout(function() {
            // Check if the dropdowns have been auto-selected and reset them
            if (mainLocationSelect && mainLocationSelect.value !== '-1') {
                mainLocationSelect.value = '-1';
                mainLocationSelect.dispatchEvent(new Event('change', { bubbles: true }));
            }
            
            if (storeSelectElement && storeSelectElement.value !== '') {
                storeSelectElement.value = '';
                storeSelectElement.dispatchEvent(new Event('change', { bubbles: true }));
            }
        }, 100);
        
        // For maximum compatibility, also reset on window load
        $(window).on('load', function() {
            // Reset both dropdowns
            if (mainLocationSelect) {
                mainLocationSelect.value = '-1';
                mainLocationSelect.dispatchEvent(new Event('change', { bubbles: true }));
            }
            
            if (storeSelectElement) {
                storeSelectElement.value = '';
                storeSelectElement.dispatchEvent(new Event('change', { bubbles: true }));
            }
        });
        
        // Create locationDetails div if it doesn't exist yet
        if (!document.getElementById('locationDetails')) {
            var detailsDiv = document.createElement('div');
            detailsDiv.id = 'locationDetails';
            detailsDiv.style.display = 'none';
            if (mainLocationSelect && mainLocationSelect.parentNode) {
                mainLocationSelect.parentNode.insertBefore(detailsDiv, mainLocationSelect.nextSibling);
            }
        }
        
        // Function to update the location details in the UI
        function updateLocationDetails(locationKey) {
            var detailsDiv = document.getElementById('locationDetails');
            
            // If no valid location is selected, hide the div and exit
            if (!locationKey || locationKey === '-1') {
                detailsDiv.innerHTML = '';
                detailsDiv.style.display = 'none';
                return;
            }
            
            // Make sure we have data for this location - use the global variable from the PHP file
            if (typeof allLocationsData === 'undefined') {
                console.error('Location data not available. Make sure allLocationsData is defined.');
                return;
            }
            
            var data = allLocationsData[locationKey];
            
            if (!data || Object.keys(data).length === 0) {
                detailsDiv.innerHTML = '';
                detailsDiv.style.display = 'none';
                return;
            }
            
            // Since we have data, show the div and populate it
            detailsDiv.style.display = 'block';
            
            var html = '';
            
            // Build HTML content for location details
            html += '<div class="location-details-container">';
    
            // Group address fields together
            var addressFields = [];
            if (data['address']) addressFields.push(data['address']);
            if (data['street_number']) addressFields.push(data['street_number']);
            if (data['route']) addressFields.push(data['route']);
            if (data['locality']) addressFields.push(data['locality']);
            if (data['postal_code']) addressFields.push(data['postal_code']);
            if (data['country']) addressFields.push(data['country']);
            
            if (addressFields.length > 0) {
                html += '<div class="address-fields"><span class="dashicons dashicons-admin-home" style="vertical-align: sub;"></span>' + addressFields.join(', ') + '</div>';
            }
    
            // Group email and phone together
            var contactFields = [];
            if (data['email']) contactFields.push(data['email']);
            if (data['phone']) contactFields.push(data['phone']);
            
            if (contactFields.length > 0) {
                html += '<div class="contact-fields"><span class="dashicons dashicons-email" style="vertical-align: sub;"></span>' + contactFields.join(' , ') + '</div>';
            }
    
            // Group start and end time together
            var timingFields = [];
            if (data['start_time'] && data['end_time']) {
                timingFields.push(data['start_time'] + ' - ' + data['end_time']);
            } else if (data['start_time']) {
                timingFields.push(data['start_time']);
            } else if (data['end_time']) {
                timingFields.push(data['end_time']);
            }
            
            if (timingFields.length > 0) {
                html += '<div class="timing-fields"><span class="dashicons dashicons-clock" style="vertical-align: sub;"></span>' + timingFields.join(' , ') + '</div>';
            }
    
            html += '</div>';
            
            // Update the details div with our new content
            detailsDiv.innerHTML = html;
        }
        
        // Make the update function available globally
        window.wcmlimUpdateLocationDetails = updateLocationDetails;
        
        // Function to trigger update for main dropdown after a delay
        function triggerMainDropdownUpdate() {
            setTimeout(function() {
                if (mainLocationSelect && mainLocationSelect.value && mainLocationSelect.value !== '-1') {
                    updateLocationDetails(mainLocationSelect.value);
                }
            }, 300);
        }
        
        // Handle main dropdown change for both simple and variable products
        if (mainLocationSelect) {
            $(mainLocationSelect).on('change', function() {
                updateLocationDetails(this.value);
            });
            
            // Initialize with current value
            if (mainLocationSelect.value && mainLocationSelect.value !== '-1') {
                updateLocationDetails(mainLocationSelect.value);
            }
        }
        
        // Handle location group dropdown change
        if (locationGroupDropdown) {
            $(locationGroupDropdown).on('change', function() {
                triggerMainDropdownUpdate();
            });
        }
        
        // Handle store location dropdown change
        if (storeDropdown) {
            $(storeDropdown).on('change', function() {
                triggerMainDropdownUpdate();
            });
        }
        
        // Special handling for variable products
        if (isVariableProduct) {
            // For variations, we need to update location details when a variation is selected
            $('form.variations_form').on('show_variation', function(event, variation) {
                triggerMainDropdownUpdate();
            });
            
            // When variations are reset, we should still show location details
            $('form.variations_form').on('reset_data', function() {
                triggerMainDropdownUpdate();
            });
            
            // Also handle the case where the variation form is initialized
            $('form.variations_form').on('woocommerce_variation_has_changed', function() {
                triggerMainDropdownUpdate();
            });
        }
        
        // Listen for AJAX events
        $(document).ajaxComplete(function(event, xhr, settings) {
            // Wait a bit to ensure the DOM is updated
            setTimeout(function() {
                var currentLoc = mainLocationSelect ? mainLocationSelect.value : null;
                if (currentLoc && currentLoc !== '-1') {
                    updateLocationDetails(currentLoc);
                }
            }, 500);
        });
    }

    function setupListView() {
        // Check if we're in a List View
        if (!$('.location_list').length) return;

        
        // Variables to track state
        let selectedGroupId = null;
        let selectedVariationId = null;
        const isVariableProduct = $('form.variations_form').length > 0;
        const groupsEnabled = $('#wcmlim-location-group').length > 0;
        const locationItems = $('.wcmlim_radio_option');
        
        // Cache DOM elements
        const locationGroupDropdown = $('#wcmlim-location-group');
        const groupMessage = $('#select-group-message');
        const variableMessage = $('#variable-product-message');
        
        // Function to handle location group changes
        function updateListViewState() {
            
            // Hide all location items first
            locationItems.hide();
            
            // For variable products
            if (isVariableProduct) {
                if (groupsEnabled) {
                    // If no group selected, show group message
                    if (!selectedGroupId) {
                        if (groupMessage) groupMessage.show();
                        if (variableMessage) variableMessage.hide();
                    } 
                    // If group selected but no variation, show variation message
                    else if (!selectedVariationId) {
                        if (groupMessage) groupMessage.hide();
                        if (variableMessage) variableMessage.show();
                    } 
                    // Both group and variation selected - show filtered locations
                    else {
                        if (groupMessage) groupMessage.hide();
                        if (variableMessage) variableMessage.hide();
                        
                        // Show locations from selected group
                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroupId]) {
                            wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                                locationItems.filter('[data-location-id="' + locationId + '"]').fadeIn();
                            });
                        }
                    }
                } else {
                    // For variable products without groups
                    if (variableMessage) variableMessage.hide();
                    
                    // Only show locations if variation is selected
                    if (selectedVariationId) {
                        locationItems.fadeIn();
                    } else if (variableMessage) {
                        variableMessage.show();
                    }
                }
            } 
            // For simple products
            else {
                if (groupsEnabled) {
                    // Show group message if no group selected
                    if (!selectedGroupId) {
                        if (groupMessage) groupMessage.show();
                    } else {
                        if (groupMessage) groupMessage.hide();
                        
                        // Show locations from selected group
                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroupId]) {
                            wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                                locationItems.filter('[data-location-id="' + locationId + '"]').fadeIn();
                            });
                        }
                    }
                } else {
                    // If no groups, show all locations
                    locationItems.show();
                }
            }
            
            // Highlight previously selected location
            highlightSelectedLocation();
        }
        
        // Handle location group change
        if (locationGroupDropdown && locationGroupDropdown.length) {
            locationGroupDropdown.on('change', function() {
                selectedGroupId = $(this).val() || null;
                updateListViewState();
            });
            
            // Initialize with the current value
            locationGroupDropdown.trigger('change');
        }
        
        // Handle variation selection for variable products
        if (isVariableProduct) {
            $('form.variations_form').on('show_variation', function(event, variation) {
                selectedVariationId = variation.variation_id;
                updateListViewState();
                
                // Update stock information for displayed locations
                updateLocationStockForVariation(selectedVariationId);
            });
            
            $('form.variations_form').on('reset_data', function() {
                selectedVariationId = null;
                updateListViewState();
            });
        }
        
        // Handle radio option click events
        $(document).on('click', '.wcmlim_radio_option', function(e) {
            var $item = $(this);
            
            // If the click was on a radio input, don't trigger twice
            if ($(e.target).is('input[type="radio"]')) {
                return;
            }
            
            // Get the radio input inside this option
            var $radio = $item.find('input[type="radio"]');
            if ($radio.length) {
                $radio.prop('checked', true);
                
                // Use native DOM click to ensure all related events fire
                $radio[0].click();
            }
            
            // Add highlighting and store location data
            var locationId = $item.data('location-id');
            var locationKey = $item.data('location-key');
            
            // Store location data in cookies
            setLocation("wcmlim_selected_location", locationKey.toString(), 30);
            setLocation("wcmlim_selected_location_termid", locationId.toString(), 30);
            
            // Update hidden fields for add to cart
            var stockQty = $radio.data('lc-qty') || '';
            var regularPrice = $radio.data('lc-regular-price') || '';
            var salePrice = $radio.data('lc-sale-price') || '';
            
            $('#lc_qty').val(stockQty);
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
    }
    
    function setupThreeColView() {
        // Check if we're in a Three Column View
        if (!$('.wcmlim-threecol_view').length) return;
        
        // Variables to track state
        let selectedGroupId = null;
        let selectedVariationId = null;
        const isVariableProduct = $('form.variations_form').length > 0;
        const groupsEnabled = $('#wcmlim-location-group').length > 0;
        
        // Cache DOM elements
        const locationGroupDropdown = $('#wcmlim-location-group');
        const locationItems = $('.location-stock-item');
        const variableLocationItems = $('.variable-location-item');
        const groupMessage = $('#select-group-message');
        const variableMessage = $('#variable-product-message');
        
        // Function to update the three column view based on current selections
        function updateThreeColViewState() {
            
            // Hide all location items first
            locationItems.hide();
            
            // For variable products
            if (isVariableProduct) {
                if (groupsEnabled) {
                    // If no group selected, show group message
                    if (!selectedGroupId) {
                        if (groupMessage) groupMessage.show();
                        if (variableMessage) variableMessage.hide();
                    } 
                    // If group selected but no variation, show variation message
                    else if (!selectedVariationId) {
                        if (groupMessage) groupMessage.hide();
                        if (variableMessage) variableMessage.show();
                    } 
                    // Both group and variation selected - show filtered locations
                    else {
                        if (groupMessage) groupMessage.hide();
                        if (variableMessage) variableMessage.hide();
                        
                        // Show only locations from the selected group
                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroupId]) {
                            wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                                variableLocationItems.filter('[data-location-id="' + locationId + '"]').fadeIn();
                            });
                        }
                    }
                } else {
                    // Variable product without location groups
                    if (variableMessage) variableMessage.hide();
                    
                    // Only show locations if variation is selected
                    if (selectedVariationId) {
                        variableLocationItems.fadeIn();
                    } else if (variableMessage) {
                        variableMessage.show();
                    }
                }
            } 
            // For simple products
            else {
                if (groupsEnabled) {
                    // Show group message if no group selected
                    if (!selectedGroupId) {
                        if (groupMessage) groupMessage.show();
                    } else {
                        if (groupMessage) groupMessage.hide();
                        
                        // Show only locations from the selected group
                        if (wcmlimGroupLocations && wcmlimGroupLocations[selectedGroupId]) {
                            wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                                locationItems.filter(':not(.variable-location-item)[data-location-id="' + locationId + '"]').fadeIn();
                            });
                        }
                    }
                } else {
                    // If no location groups, show all simple product locations
                    locationItems.not('.variable-location-item').show();
                }
            }
            
            // Highlight previously selected location
            highlightSelectedLocation();
        }
        
        // Handle location group change
        if (locationGroupDropdown && locationGroupDropdown.length) {
            locationGroupDropdown.on('change', function() {
                selectedGroupId = $(this).val() || null;
                updateThreeColViewState();
            });
            
            // Initialize with the current value
            locationGroupDropdown.trigger('change');
        }
        
        // Handle variable product variation changes
        if (isVariableProduct) {
            $('form.variations_form').on('show_variation', function(event, variation) {
                selectedVariationId = variation.variation_id;
                updateThreeColViewState();
            });
            
            $('form.variations_form').on('reset_data', function() {
                selectedVariationId = null;
                updateThreeColViewState();
            });
        }
        
        // Handle location item click events
        $(document).on('click', '.location-stock-item', function() {
            var $item = $(this);
            
            // Skip if the item is not visible (filtered out by group or variation)
            if (!$item.is(':visible')) {
                return;
            }
            
            var locationId = $item.data('location-id');
            var locationKey = $item.data('location-key');
            
            // Remove highlight from all items and add it to the clicked one
            $('.location-stock-item').removeClass('highlighted');
            $item.addClass('highlighted');
            
            // Set cookies for selected location
            setLocation("wcmlim_selected_location", locationKey.toString(), 30);
            setLocation("wcmlim_selected_location_termid", locationId.toString(), 30);
            
            // Update hidden fields for add to cart
            var stockQty = $item.attr('data-lc-qty') || $item.find('.wclim-views_subinfo').text();
            var regularPrice = $item.data('regular-price') || '';
            var salePrice = $item.data('sale-price') || '';
            
            $('#lc_qty').val(stockQty);
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
        
        // Initialize the view
        updateThreeColViewState();
    }
    
    // ===== Initialize based on view type =====
    
    // Handle variable products for all views
    handleVariationChange();
    
    // Initialize the appropriate view
    if ($('#location-stock-table-simple').length || $('#location-stock-table-variable').length) {
        setupTableView();
    } else if ($('.location-stock-text-container').length) {
        setupSimpleTextView();
    } else if ($('#location-stock-list').length) {
        setupExpandedView();
    } else if ($('#location-stock-cards').length) {
        setupCardView();
    } else if ($('#select_location').length) {
        setupSelectView();
    } else if ($('.location_list').length) {
        setupListView();
    } else if ($('.wcmlim-threecol_view').length) {
        setupThreeColView();
    }

    // Handle dropdown changes
    const firstDropdown = $('#select_location'); // First dropdown
    const secondDropdown = $('#select_city_area'); // Second dropdown

    // Initialize second dropdown with a placeholder
    secondDropdown.html('<option value="">' + '- Select City / Area -' + '</option>').prop('disabled', true);

    // Listen for changes in the first dropdown
    firstDropdown.on('change', function () {
        const selectedValue = $(this).val();

        // Reset the second dropdown
        secondDropdown.html('<option value="">' + '- Select City / Area -' + '</option>').prop('disabled', true);

        if (selectedValue) {
            // Example: Fetch data dynamically or use predefined data
            const cityAreaData = {
                1: [
                    { value: 'area1', text: 'Area 1' },
                    { value: 'area2', text: 'Area 2' },
                ],
                2: [
                    { value: 'area3', text: 'Area 3' },
                    { value: 'area4', text: 'Area 4' },
                ],
            };

            // Populate the second dropdown based on the selected value
            if (cityAreaData[selectedValue]) {
                cityAreaData[selectedValue].forEach((item) => {
                    secondDropdown.append(
                        $('<option>', {
                            value: item.value,
                            text: item.text,
                        })
                    );
                });

                // Enable the second dropdown
                secondDropdown.prop('disabled', false);
            }
        }
    });

    function updateViewState() {
    
        // Hide all location items first
        locationItems.hide();
    
        // For variable products
        if (isVariableProduct) {
            // Location groups enabled
            if (groupsEnabled) {
                // If no group selected, always show group message first
                if (!selectedGroupId) {
                    groupMessage.show();
                    variableMessage.hide();
                } 
                // If group is selected but no variation, show variation message
                else if (!selectedVariationId) {
                    groupMessage.hide();
                    variableMessage.show();
                } 
                // Both group and variation selected - show filtered locations
                else {
                    groupMessage.hide();
                    variableMessage.hide();
    
                    // Show only locations from selected group
                    if (wcmlimGroupLocations[selectedGroupId]) {
                        wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                            $('.location-list-item[data-location-id="' + locationId + '"]').show();
                        });
                    }
                }
            } 
            // Location groups disabled
            else {
                // Ensure stocks list is not shown unless a group is selected
                groupMessage.hide();
                variableMessage.show();
            }
        } 
        // For simple products
        else {
            if (groupsEnabled) {
                if (!selectedGroupId) {
                    groupMessage.show();
                } else {
                    groupMessage.hide();
    
                    // Show only locations from selected group
                    if (wcmlimGroupLocations[selectedGroupId]) {
                        wcmlimGroupLocations[selectedGroupId].forEach(function(locationId) {
                            $('.location-list-item[data-location-id="' + locationId + '"]').show();
                        });
                    }
                }
            } else {
                locationItems.show();
            }
        }
    }
});


