/**
 * WooCommerce Multi-Location Inventory Management - View Scripts
 *
 * This file contains all the JavaScript functionality for different location view types:
 * - Table View
 * - Simple Text View
 * - Three Column View
 * - Two Column View
 * - List View
 * - Card View
 */

jQuery(document).ready(function($) {
    // Determine which view is active based on DOM elements
    const viewType = getActiveViewType();
    
    /**
     * Detect which view is currently active
     * @returns {string} The active view type
     */
    function getActiveViewType() {
        if ($('.wcmlim-twocol_view').length) return 'two-column';
        if ($('.wcmlim-threecol_view').length) return 'three-column';
        if ($('.table_location-wrapper').length) return 'table';
        if ($('.simple_text_location-wrapper').length) return 'simple-text';
        if ($('.card_location-wrapper').length) return 'card';
        if ($('.wcmlim_radio_option').length) return 'list';
        if ($('.wcmlim-drawer_view').length) return 'drawer';
        if ($('.wcmlim-popup_view').length) return 'popup';
        return 'unknown';
    }
    
    // Initialize the view based on detected type
    initializeView(viewType);
    
    /**
     * Set up the specific view based on type
     * @param {string} viewType The type of view to initialize
     */
    function initializeView(viewType) {
        
        // Common initialization for all views
        setupCommonFunctionality();
        
        // View-specific initialization
        switch(viewType) {
            case 'two-column':
                setupTwoColumnView();
                break;
            case 'three-column':
                setupThreeColumnView();
                break;
            case 'table':
                setupTableView();
                break;
            case 'simple-text':
                setupSimpleTextView();
                break;
            case 'card':
                setupCardView();
                break;
            case 'list':
                setupListView();
                break;
            case 'drawer':
                setupDrawerView();
                break;
            case 'popup':
                setupPopupView();
                break;
        }
        
        // Always initialize variable product handling if needed
        if ($('form.variations_form').length > 0) {
            setupVariableProductHandling();
        }
    }
    
    /**
     * Common functionality used across all views
     */
    function setupCommonFunctionality() {
        // Cookie handling functions
        window.setWcmlimCookie = function(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=/";
        }
        
        window.getWcmlimCookie = function(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;
        }
        
        // Common location selection function
        window.handleLocationSelection = function(locationId, locationKey, stockText) {
            // Update cookies
            setWcmlimCookie("wcmlim_selected_location", locationKey, 30);
            setWcmlimCookie("wcmlim_selected_location_termid", locationId, 30);
            
            // Update hidden fields
            $('#lc_qty').val(stockText);
        }
        
        // Initialize based on stored location
        highlightSelectedLocation();
    }
    
    /**
     * Highlights the selected location across all view types
     */
    function highlightSelectedLocation() {
        const selectedLocationKey = getWcmlimCookie("wcmlim_selected_location");
        const selectedLocationId = getWcmlimCookie("wcmlim_selected_location_termid");
        
        if (selectedLocationId) {
            // Remove highlights from all items
            $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').removeClass('highlighted selected');
            
            // Add highlight to selected location based on view type
            switch(viewType) {
                case 'two-column':
                case 'three-column':
                case 'simple-text':
                    $(`.location-stock-item[data-location-id="${selectedLocationId}"]`).addClass('highlighted');
                    break;
                case 'table':
                    $(`.location-stock-row[data-location-id="${selectedLocationId}"]`).addClass('highlighted');
                    break;
                case 'card':
                    $(`.location-stock-card[data-location-id="${selectedLocationId}"]`).addClass('selected');
                    break;
                case 'list':
                    $(`.wcmlim_radio_option[data-location-id="${selectedLocationId}"]`).addClass('highlighted');
                    $(`#select_location_${selectedLocationKey}`).prop('checked', true);
                    break;
            }
        }
    }
    
    /**
     * Set up the location group selector functionality
     */
    function setupLocationGroupSelector() {
        if (typeof wcmlimGroupLocations !== 'undefined') {
            // Handle initial state
            const isVariableProduct = $('form.variations_form').length > 0;
            
            if (isVariableProduct) {
                // For variable products, show variable message and hide locations
                $('.variable-product-message').show();
                $('#variable-product-message').show();
                $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').hide();
                $('.location-stock-group').hide();
            } else {
                // For simple products, show group message and hide locations
                $('#select-group-message').show();
                $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').hide();
                $('.location-stock-group').hide();
            }
            
            // Handle location group selection change
            $('#wcmlim-location-group').on('change', function() {
                const selectedGroup = $(this).val();
                
                // If no group selected, show message and hide locations
                if (selectedGroup === '') {
                    $('#select-group-message').show();
                    $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').hide();
                    $('.location-stock-group').hide();
                    
                    if (isVariableProduct) {
                        $('.variable-product-message, #variable-product-message').hide();
                    }
                    return;
                }
                
                // Hide group message
                $('#select-group-message').hide();
                
                // For variable products, check if variation is selected
                if (isVariableProduct) {
                    const variationId = $('input[name="variation_id"]').val();
                    
                    if (!variationId || variationId === '0') {
                        // No variation selected, show variable message
                        $('.variable-product-message, #variable-product-message').show();
                        $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').hide();
                        $('.location-stock-group').hide();
                        return;
                    } else {
                        // Variation selected, hide variable message
                        $('.variable-product-message, #variable-product-message').hide();
                    }
                }
                
                // Get locations for selected group
                const groupLocations = wcmlimGroupLocations[selectedGroup] || [];
                
                // Hide all locations first
                $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').hide();
                $('.location-stock-group').hide();
                
                // Show only locations in the selected group
                if (groupLocations.length > 0) {
                    // Handle showing locations based on view type
                    switch(viewType) {
                        case 'three-column':
                            var visibleGroups = {};
                            
                            groupLocations.forEach(function(locationId) {
                                var $item = $(`.location-stock-item[data-location-id="${locationId}"]`);
                                if ($item.length) {
                                    if ($item.hasClass('wcmlim-hide_out_of_stock_location')) {
                                        $item.hide();
                                    } else {
                                        $item.show();
                                    }
                                    var $group = $item.closest('.location-stock-group');
                                    var groupIndex = $group.index('.location-stock-group');
                                    visibleGroups[groupIndex] = true;
                                }
                            });
                            
                            for (var groupIndex in visibleGroups) {
                                $('.location-stock-group').eq(groupIndex).show();
                            }
                            break;
                            
                        case 'table':
                            groupLocations.forEach(function(locationId) {
                                $(`.location-stock-row[data-location-id="${locationId}"]`).show();
                                $(`tr[data-location-id="${locationId}"]`).show(); // Show all related rows
                            });
                            break;
                            
                        default:
                            // // Default handling for other views
                            groupLocations.forEach(function(locationId) {
                                const $locationItem = $(`.location-stock-item[data-location-id="${locationId}"]`);
                                
                                // Check if the element has a specific class (e.g., 'some-class')
                                if ($locationItem.hasClass('wcmlim-hide_out_of_stock_location')) {
                                    $locationItem.hide();
                                } else {
                                    $locationItem.show();
                                }

                                // Show other elements as usual
                                let $listitem = $(`.wcmlim_radio_option[data-location-id="${locationId}"]`);
                                // Check if the element has a specific class (e.g., 'some-class')
                                if ($listitem.hasClass('wcmlim-hide_out_of_stock_location')) {
                                    $listitem.hide();
                                } else {
                                    $listitem.show();
                                }
                                let $carditem = $(`.location-stock-card[data-location-id="${locationId}"]`);
                                // Check if the element has a specific class (e.g., 'some-class')
                                if ($carditem.hasClass('wcmlim-hide_out_of_stock_location')) {
                                    $carditem.hide();
                                } else {
                                    $carditem.show();
                                }
                            });
                    }
                }
            });
        }
    }
    
    /**
     * Set up handling for variable products
     */
    function setupVariableProductHandling() {
        const variationForm = $('form.variations_form');
        if (variationForm.length > 0) {
            // Trigger WooCommerce's reset_data event to clear variations
            variationForm.trigger('reset_data');
            
            // Optionally, clear the selected variation dropdowns
            variationForm.find('select').val('').change();
        }
        if ($('form.variations_form').length > 0) {
            // Show variable message and hide locations initially
            $('.variable-product-message, #variable-product-message').show();
            $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').hide();
            
            // Listen for variation selection
            $('form.variations_form').on('show_variation', function() {
                // Hide variable message
                $('.variable-product-message, #variable-product-message').hide();
                
                // Check if location groups are enabled
                if (typeof wcmlimGroupLocations !== 'undefined') {
                    const selectedGroup = $('#wcmlim-location-group').val();
                    
                    // If no group selected, keep showing group message
                    if (!selectedGroup) {
                        $('#select-group-message').show();
                        return;
                    }
                    
                    // Hide group message
                    $('#select-group-message').hide();
                    
                    // Trigger the change event to show the correct locations
                    $('#wcmlim-location-group').trigger('change');
                } else {
                    // No groups, show all locations
                    $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').show();
                }
                
                // Get variation ID
                const variationId = $('input[name="variation_id"]').val();
                
                // Update stock information for each location
                updateLocationStockForVariation(variationId);
            });
            
            // Handle variation reset
            $('form.variations_form').on('reset_data', function() {
                // Hide locations
                $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').hide();
                
                // Show appropriate messages
                if (typeof wcmlimGroupLocations !== 'undefined') {
                    const selectedGroup = $('#wcmlim-location-group').val();
                    
                    if (selectedGroup) {
                        $('.variable-product-message, #variable-product-message').show();
                        $('#select-group-message').hide();
                    } else {
                        $('.variable-product-message, #variable-product-message').hide();
                        $('#select-group-message').show();
                    }
                } else {
                    $('.variable-product-message, #variable-product-message').show();
                }
            });
        }
    }
    
    /**
     * Update location stock information for a variation via AJAX
     * @param {string} variationId The ID of the selected variation
     */
    function updateLocationStockForVariation(variationId) {
        // Hide all locations initially to prevent flicker
        $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card').hide();
        $('option[data-location-id]').hide();
        $('tr[data-location-id]').hide();
        
        // Get all location elements
        const $allLocations = $('.location-stock-item, .location-stock-row, .wcmlim_radio_option, .location-stock-card');
        
        // Keep track of pending requests
        let pendingRequests = $allLocations.length;
        let locationsToShow = [];
        let locationsToHide = [];
        
        // If no locations to process, exit early
        if (pendingRequests === 0) {
            console.log('No locations found to update for variation ' + variationId);
            return;
        }
        
        // Update each location
        $allLocations.each(function() {
            const $locationEl = $(this);
            const locationId = $locationEl.data('location-id');
            const locationKey = $locationEl.data('location-key');
            
            // Find the stock display element based on view type
            var $stockDisplay;
            switch(viewType) {
                case 'two-column':
                case 'three-column':
                case 'simple-text':
                    $stockDisplay = $locationEl.find('.wclim-views_subinfo');
                    break;
                case 'table':
                    $stockDisplay = $locationEl.find('.wclim-views_subinfo');
                    break;
                case 'card':
                    $stockDisplay = $locationEl.find('.wclim-views_subinfo');
                    break;
                case 'list':
                    $stockDisplay = $locationEl.find('.wclim-views_subinfo');
                    break;
                default:
                    // For expanded view or any other type
                    $stockDisplay = $locationEl.find('.wclim-views_subinfo');
                    if ($stockDisplay.length === 0) {
                        // Try alternative selectors for expanded view
                        $stockDisplay = $locationEl.find('[class*="stock"]');
                    }
                    break;
                
            }

            // Make AJAX request with proper error handling
            $.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
                },
                context: $locationEl, // Preserve context
                success: function(response) {
                    pendingRequests--;
                    
                    if (response && response.success) {
                        // Update stock display - handle different view types
                        if (viewType === 'two-column' || viewType === 'three-column' || viewType === 'simple-text' || viewType === 'table') {
                            this.find('.wclim-views_subinfo').text(response.data.stock_text).css('color', response.data.stock_color);
                        } else if (viewType === 'card') {
                            this.find('.wclim-views_subinfo').text(response.data.stock_text).css('color', response.data.stock_color);
                        } else if (viewType === 'list') {
                            this.find('.wclim-views_subinfo').text(response.data.stock_text).css('color', response.data.stock_color);
                        } else {
                            // Handle other views including expanded view
                            var $stockEl = this.find('.wclim-views_subinfo');
                            if ($stockEl.length === 0) {
                                $stockEl = this.find('[class*="stock"]');
                            }
                            if ($stockEl.length) {
                                $stockEl.text(response.data.stock_text).css('color', response.data.stock_color);
                            }
                        }
                        this.find('.stock-display').css('background-color', response.data.stock_bgcolor);
                        this.find('.stock-display').css('border-radius', response.data.stock_radius);
                        this.find('.stock-display').css('color', response.data.stock_color);
                        
                        // Collect locations to show/hide instead of applying immediately
                        var currentLocationId = response.data.data_location_id;
                        
                        if (response.data.should_hide_location === true) {
                            locationsToHide.push(currentLocationId);
                        } else {
                            locationsToShow.push(currentLocationId);
                        }
                        
                        // Update data attributes
                        this.attr('data-lc-qty', response.data.stock_qty);
                        
                        if (response.data.regular_price) {
                            this.attr('data-lc-regular-price', response.data.regular_price);
                        }
                        if (response.data.sale_price) {
                            this.attr('data-lc-sale-price', response.data.sale_price);
                        }
                        
                        // Handle location fields if available
                        if (response.data.location_fields) {
                            handleLocationFields(this, response.data.location_fields, currentLocationId, locationKey);
                        }
                        if (response.data.location_note) {
                            const $locationNote = this.find('.location-details');
                            $locationNote.append('<p class="simple_view_location_details"><span class="dashicons dashicons-welcome-write-blog" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_contact_info">' + response.data.location_note + '</span></p>');
                        }
                    } else {
                        console.error("Stock update failed for location " + locationId);
                        // Show error if AJAX returns error
                        var $stockEl = this.find('.wclim-views_subinfo, .stock-quantity, [class*="stock"]');
                        if ($stockEl.length) {
                            $stockEl.text('Error').css('color', 'red');
                        }
                        pendingRequests--;
                    }
                    
                    // When all requests are complete, apply visibility changes
                    if (pendingRequests === 0) {
                        applyLocationVisibility(locationsToShow, locationsToHide);
                    }
                },
                error: function(xhr, status, error) {
                    pendingRequests--;
                    console.error("AJAX error for location " + locationId + ": " + error);
                    // Show error if AJAX fails
                    var $stockEl = this.find('.wclim-views_subinfo, .stock-quantity, [class*="stock"]');
                    if ($stockEl.length) {
                        $stockEl.text('Error').css('color', 'red');
                    }
                    
                    // When all requests are complete, apply visibility changes
                    if (pendingRequests === 0) {
                        applyLocationVisibility(locationsToShow, locationsToHide);
                    }
                }
            });
            
            // Show loading indicator
            if ($stockDisplay.length) {
                $stockDisplay.text('Loading...').css('color', 'grey');
            }
            
            // Remove existing location details based on view type
            switch(viewType) {
                case 'simple-text':
                    $locationEl.find('.simple_view_location_details').remove();
                    break;
                case 'three-column':
                    $locationEl.find('.threecol_view_location_details').remove();
                    break;
                case 'table':
                    $(`tr[data-location-id="${locationId}"]:not(.location-stock-row)`).remove();
                    break;
                case 'card':
                    $locationEl.find('.location-details').remove();
                    break;
                case 'list':
                    $locationEl.find('.simple_view_location_details').remove();
                    break;
                default:
                    // Handle other views including expanded view
                    $locationEl.find('[class*="_details"], [class*="location-details"], .extra-details p').not('.location-name').remove();
                    break;
            }
        });
    }
    
    /**
     * Apply visibility changes to locations in batch to prevent flicker
     * @param {Array} locationsToShow Array of location IDs to show
     * @param {Array} locationsToHide Array of location IDs to hide
     */
    function applyLocationVisibility(locationsToShow, locationsToHide) {
        // Hide locations that should be hidden
        locationsToHide.forEach(function(locationId) {
            $('.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();
        });
        
        // Show locations that should be visible
        locationsToShow.forEach(function(locationId) {
            $('.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();
        });
        
        // Check if all locations are hidden and show a message
        if (locationsToShow.length === 0 && locationsToHide.length > 0) {
            // All locations are hidden, show a "no locations available" message
            if ($('.no-locations-message').length === 0) {
                var messageHtml = '<div class="no-locations-message" style="text-align: center; padding: 20px; color: #666; font-style: italic;">No locations available for this variation.</div>';
                $('.location-stock-cards, .location-stock-list, .location-stock-text-container, #location-stock-table').after(messageHtml);
            }
        } else {
            // Remove the message if locations are available
            $('.no-locations-message').remove();
        }
        
        // Trigger custom event to notify that location visibility has been applied
        // This allows other scripts (like max location count) to run after AJAX completes
        $(document).trigger('wcmlim_location_visibility_applied');
    }
    
    /**
     * Helper function to handle location fields display in different views
     */
    function handleLocationFields($element, locationFields, locationId, locationKey) {
        switch(viewType) {
            case 'simple-text':
                
                break;
            case 'three-column':
                
                break;
                
            case 'two-column':
                // Clear existing details
                const $locationDetails = $element.find('.location-details');
                if ($locationDetails.length) {
                    $locationDetails.empty();
                    
                    // Add each field category
                    for (const [category, value] of Object.entries(locationFields)) {
                        if (value) {
                            const fieldNameCapitalized = category.charAt(0).toUpperCase() + category.slice(1);
                            if (fieldNameCapitalized == "Address") {
                                $locationDetails.append('<p class="simple_view_location_details"><span class="dashicons dashicons-admin-home" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_address_info">' + value + '</span></p>');
                            } else if (fieldNameCapitalized == "Contact") {
                                $locationDetails.append('<p class="simple_view_location_details"><span class="dashicons dashicons-email" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_contact_info">' + value + '</span></p>');
                            } else if (fieldNameCapitalized == "Timing") {
                                $locationDetails.append('<p class="simple_view_location_details"><span class="dashicons dashicons-clock" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_time_info">' + value + '</span></p>');
                            } else if (fieldNameCapitalized == "Distance") {
                                $locationDetails.append('<p class="simple_view_location_details"><span class="dashicons dashicons-location" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_distance_info">' + value + '</span></p>');
                            }
                        }
                    }
                } else {
                    // Create container if it doesn't exist
                    const $newDetails = $('<div class="location-details"></div>');
                    for (const [category, value] of Object.entries(locationFields)) {
                        if (value) {
                            const fieldNameCapitalized = category.charAt(0).toUpperCase() + category.slice(1);
                            if (fieldNameCapitalized == "Address") {
                                $newDetails.append('<p class="simple_view_location_details"><span class="dashicons dashicons-admin-home" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_address_info">' + value + '</span></p>');
                            } else if (fieldNameCapitalized == "Contact") {
                                $newDetails.append('<p class="simple_view_location_details"><span class="dashicons dashicons-email" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_contact_info">' + value + '</span></p>');
                            } else if (fieldNameCapitalized == "Timing") {
                                $newDetails.append('<p class="simple_view_location_details"><span class="dashicons dashicons-clock" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_time_info">' + value + '</span></p>');
                            } else if (fieldNameCapitalized == "Distance") {
                                $newDetails.append('<p class="simple_view_location_details"><span class="dashicons dashicons-location" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_distance_info">' + value + '</span></p>');
                            }
                        }
                    }
                    $element.append($newDetails);
                }
                break;
                
            case 'table':
                let insertAfter = $element;
               
                break;
                
            case 'card':
                // Create details container
                const $detailsContainer = $('<div class="location-details"></div>');
                
                // Add each category
                for (const [category, value] of Object.entries(locationFields)) {
                    if (value) {
                        const fieldNameCapitalized = category.charAt(0).toUpperCase() + category.slice(1);
                        if (fieldNameCapitalized == "Address") {
                            $detailsContainer.append('<p class="simple_view_location_details"><span class="dashicons dashicons-admin-home" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_address_info">' + value + '</span></p>');
                        } else if (fieldNameCapitalized == "Contact") {
                            $detailsContainer.append('<p class="simple_view_location_details"><span class="dashicons dashicons-email" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_contact_info">' + value + '</span></p>');
                        } else if (fieldNameCapitalized == "Timing") {
                            $detailsContainer.append('<p class="simple_view_location_details"><span class="dashicons dashicons-clock" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_time_info">' + value + '</span></p>');
                        } else if (fieldNameCapitalized == "Distance") {
                            $detailsContainer.append('<p class="simple_view_location_details"><span class="dashicons dashicons-location" style="vertical-align: sub;"></span><span class="wclim-views_font_size wclim-views_distance_info">' + value + '</span></p>');
                        }
                    }
                }
                
                // Add details to card
                $element.append($detailsContainer);
                break;
                
            case 'list':
                // Find the hr element or add one if it doesn't exist
                // let $hr = $element.find('hr');
                // if ($hr.length === 0) {
                //     $element.append('<hr style="width: 100%; margin: 5px 0; border-top: 1px solid #ccc;">');
                // }
                
                for (const [category, value] of Object.entries(locationFields)) {
                    if (value) {
                        const fieldNameCapitalized = category.charAt(0).toUpperCase() + category.slice(1);
                        
                        if (fieldNameCapitalized == "Address") {
                            $element.append(
                                '<div class="simple_view_location_details" style="display: flex; width: 100%;">' +
                                '<span class="dashicons dashicons-admin-home" style="vertical-align: sub;"></span>' +
                                '<span>' + value + '</span>' +
                                '</div>'
                            );
                        } else if (fieldNameCapitalized == "Contact") {
                            $element.append(
                                '<div class="simple_view_location_details" style="display: flex; width: 100%;">' +
                                '<span class="dashicons dashicons-email" style="vertical-align: sub;"></span>' +
                                '<span>' + value + '</span>' +
                                '</div>'
                            );
                        } else if (fieldNameCapitalized == "Timing") {
                            $element.append(
                                '<div class="simple_view_location_details" style="display: flex; width: 100%;">' +
                                '<span class="dashicons dashicons-clock" style="vertical-align: sub;"></span>' +
                                '<span>' + value + '</span>' +
                                '</div>'
                            );
                        } else if (fieldNameCapitalized == "Distance") {
                            $element.append(
                                '<div class="simple_view_location_details" style="display: flex; width: 100%;">' +
                                '<span class="dashicons dashicons-location" style="vertical-align: sub;"></span>' +
                                '<span>' + value + '</span>' +
                                '</div>'
                            );
                        }
                    }
                }
                break;
                
            default:
                // Handle other views including expanded view
                const $detailsArea = $element.find('.extra-details');
               
                break;
        }
    }

    /**
     * Drawer View specific setup
     */
    function setupDrawerView() {
        setupLocationGroupSelector();
    }

    /**
     * Popup View specific setup
     */
    function setupPopupView() {
        setupLocationGroupSelector();
    }


    /**
     * Two Column View specific setup
     */
    function setupTwoColumnView() {
        setupLocationGroupSelector();
        
        // Handle location item click
        $(document).on('click', '.location-stock-item', function() {
            const $item = $(this);
            const locationId = $item.data('location-id');
            const locationKey = $item.data('location-key');
            
            // Update selected state
            $('.location-stock-item').removeClass('highlighted');
            $item.addClass('highlighted');
            
            // Update cookies and hidden fields
            setWcmlimCookie("wcmlim_selected_location", locationKey, 30);
            setWcmlimCookie("wcmlim_selected_location_termid", locationId, 30);
            
            $('#lc_qty').val($item.find('.wclim-views_subinfo').text());
            
            // Handle price information
            const regularPrice = $item.data('lc-regular-price');
            const salePrice = $item.data('lc-sale-price');
            
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
    }
    
    /**
     * Three Column View specific setup
     */
    function setupThreeColumnView() {
        setupLocationGroupSelector();
        
        // Handle location item click
        $(document).on('click', '.location-stock-item', function() {
            const $item = $(this);
            const locationId = $item.data('location-id');
            const locationKey = $item.data('location-key');
            
            // Update selected state
            $('.location-stock-item').removeClass('highlighted');
            $item.addClass('highlighted');
            
            // Update cookies and hidden fields
            setWcmlimCookie("wcmlim_selected_location", locationKey, 30);
            setWcmlimCookie("wcmlim_selected_location_termid", locationId, 30);
            
            $('#lc_qty').val($item.find('.wclim-views_subinfo').text());
            
            // Handle price information
            const regularPrice = $item.data('lc-regular-price');
            const salePrice = $item.data('lc-sale-price');
            
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
    }
    
    /**
     * Table View specific setup
     */
    function setupTableView() {
        setupLocationGroupSelector();
        
        // Handle row click
        $(document).on('click', '.location-stock-row', function() {
            const $row = $(this);
            const locationId = $row.data('location-id');
            const locationKey = $row.data('location-key');
            
            // Update selected state
            $('.location-stock-row').removeClass('highlighted');
            $row.addClass('highlighted');
            
            // Update cookies and hidden fields
            setWcmlimCookie("wcmlim_selected_location", locationKey, 30);
            setWcmlimCookie("wcmlim_selected_location_termid", locationId, 30);
            
            $('#lc_qty').val($row.find('.wclim-views_subinfo').text());
            
            // Handle price information
            const regularPrice = $row.data('lc-regular-price');
            const salePrice = $row.data('lc-sale-price');
            
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
    }
    
    /**
     * Simple Text View specific setup
     */
    function setupSimpleTextView() {
        setupLocationGroupSelector();
        
        // Handle location item click
        $(document).on('click', '.location-stock-item', function() {
            const $item = $(this);
            const locationId = $item.data('location-id');
            const locationKey = $item.data('location-key');
            
            // Update selected state
            $('.location-stock-item').removeClass('highlighted');
            $item.addClass('highlighted');
            
            // Update cookies and hidden fields
            setWcmlimCookie("wcmlim_selected_location", locationKey, 30);
            setWcmlimCookie("wcmlim_selected_location_termid", locationId, 30);
            
            $('#lc_qty').val($item.find('.wclim-views_subinfo').text());
            
            // Handle price information
            const regularPrice = $item.data('lc-regular-price');
            const salePrice = $item.data('lc-sale-price');
            
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
    }
    
    /**
     * Card View specific setup
     */
    function setupCardView() {
        setupLocationGroupSelector();
        
        // Handle card click
        $(document).on('click', '.location-stock-card', function() {
            const $card = $(this);
            const locationId = $card.data('location-id');
            const locationKey = $card.data('location-key');
            
            // Update selected state
            $('.location-stock-card').removeClass('selected');
            $card.addClass('selected');
            
            // Update cookies and hidden fields
            setWcmlimCookie("wcmlim_selected_location", locationKey, 30);
            setWcmlimCookie("wcmlim_selected_location_termid", locationId, 30);
            
            $('#lc_qty').val($card.find('.stock-quantity').text());
            
            // Handle price information
            const regularPrice = $card.data('lc-regular-price');
            const salePrice = $card.data('lc-sale-price');
            
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
    }
    
    /**
     * List View specific setup
     */
    function setupListView() {
        setupLocationGroupSelector();
        
        // Handle radio option click
        $(document).on('click', '.wcmlim_radio_option', function() {
            const $option = $(this);
            const locationId = $option.data('location-id');
            const locationKey = $option.data('location-key');
            
            // Check the radio button
            $option.find('input[type="radio"]').prop('checked', true);
            
            // Update cookies and hidden fields
            setWcmlimCookie("wcmlim_selected_location", locationKey, 30);
            setWcmlimCookie("wcmlim_selected_location_termid", locationId, 30);
            
            $('#lc_qty').val($option.find('label span:last-child').text());
            
            // Handle price information from the radio input
            const $radio = $option.find('input[type="radio"]');
            const regularPrice = $radio.data('lc-regular-price');
            const salePrice = $radio.data('lc-sale-price');
            
            if (regularPrice) $('#lc_regular_price').val(regularPrice);
            if (salePrice) $('#lc_sale_price').val(salePrice);
        });
    }
});
