function CategoryGallery(rental_id, rental_name, images_arr){
    var rid = rental_id;
    var rentalName = rental_name;

    // Normalize images_arr: it may arrive as a JSON string, an object, or be undefined
    try {
        if (typeof images_arr === 'string' && images_arr.length) {
            images_arr = JSON.parse(images_arr);
        }
    } catch (e) {
        images_arr = {};
    }
    if (!images_arr) images_arr = {};

    // Where to append anchors and thumbs
    var $bigAfter = jQuery('#io_img_big2_' + rid);
    var $thumbAfter = jQuery('#io_img_thumb1_' + rid);

    if ($bigAfter.length && $thumbAfter.length) {
        var relVal = $bigAfter.attr('rel') || 'img_group noopener';

        // Helper to validate a URL-like value (non-empty and not literal placeholders)
        var isValid = function (u) {
            if (!u) return false;
            var s = String(u).trim();
            if (!s) return false;
            if (s.indexOf('%%') !== -1) return false; // ignore unreplaced placeholders
            if (s === '0' || s.toLowerCase() === 'null' || s.toLowerCase() === 'undefined') return false;
            return true;
        };

        var addedThumbs = 0;

        // Iterate image map and append missing big anchors and thumbs
        for (var key in images_arr) {
            if (!images_arr.hasOwnProperty(key)) continue;
            var imgObj = images_arr[key] || {};
            var href = imgObj["rentalimage_imagelocbig"] || imgObj["imagelocbig"] || imgObj["big"];
            var src  = imgObj["rentalimage_imageloc"]    || imgObj["imageloc"]    || imgObj["thumb"];

            // Compute index consistent with existing templates
            var n = parseInt(key, 10);
            if (isNaN(n)) {
                // Try to derive from position by incrementing a counter if keys are not numeric
                n = 1;
            }
            // Category templates already include big1, big2, and thumb1; gallery adds 2+ when missing
            var bigIndex = n + 1;   // matches io_cart_shortcode.html pattern
            var thumbIndex = n + 1; // thumb id series aligns with big series in newer code

            // Add big anchor if valid and not already present
            if (isValid(href)) {
                var bigId = '#io_img_big' + bigIndex + '_' + rid;
                if (jQuery(bigId).length === 0) {
                    var $a = jQuery('<a/>', {
                        rel: relVal,
                        href: href,
                        id: 'io_img_big' + bigIndex + '_' + rid
                    });
                    $bigAfter.after($a);
                    $bigAfter = $a; // maintain insertion point
                }
            }

            // Add thumbnail if valid and not already present
            if (isValid(src)) {
                var thumbId = '#io_img_thumb' + thumbIndex + '_' + rid;
                if (jQuery(thumbId).length === 0) {
                    var $img = jQuery('<img/>', {
                        'class': 'io_image_thumb skip-lazy',
                        title: rentalName,
                        src: src,
                        alt: rentalName,
                        id: 'io_img_thumb' + thumbIndex + '_' + rid
                    }).on('mouseover', function () {
                        if (typeof updateCategoryPic === 'function') {
                            updateCategoryPic(this);
                        }
                    });
                    $thumbAfter.after($img);
                    $thumbAfter = $img; // maintain insertion point
                    addedThumbs++;
                }
            }
        }

        // Reveal the thumbnail box if we added any extra thumbnails
        if (addedThumbs > 0) {
            jQuery('#io_img_thumb1_' + rid).closest('.io_image_thumbbox').show();
        }
    }
}

// Function to generate list view content on demand (global scope)
generateListViewContent = function() {
    console.log('[IO List View] Generating list view content dynamically');

    jQuery('.io_item2_list').each(function() {
        var $item = jQuery(this);

        // Skip if already generated
        if ($item.find('.io_list_view_content').length > 0) {
            return;
        }

        // Extract rental_id from the item
        var rentalId = $item.find('.item_rentalid').text().trim();
        if (!rentalId) {
            console.warn('[IO List View] No rental_id found for item, skipping');
            return;
        }

        // Read data from dynamically named global variables
        // var description = String(window['data_description_' + rentalId] || "").replace(/[\r\n]+/g, "").trim();
        
        // Check if category data exists for this rental
        if (typeof window.io_category_data === 'undefined' || !window.io_category_data[rentalId]) {
            console.warn('[IO List View] No category data found for rental', rentalId);
            return;
        }
        
        var indoorOutdoor = String(window.io_category_data[rentalId]['indoor_outdoor'] || "").replace(/[\r\n]+/g, "").trim();
        var staff = String(window.io_category_data[rentalId]['staff'] || "").replace(/[\r\n]+/g, "").trim();
        var electric = String(window.io_category_data[rentalId]['electric'] || "").replace(/[\r\n]+/g, "").trim();
        var dimensions = String(window.io_category_data[rentalId]['dimensions'] || "").replace(/[\r\n]+/g, "").trim();

        // Helper function to strip HTML tags from text
        var stripHtml = function(html) {
            var tmp = document.createElement("DIV");
            tmp.innerHTML = html;
            return (tmp.textContent || tmp.innerText || "").trim();
        };

        // Helper function to escape HTML to prevent XSS
        var escapeHtml = function(text) {
            var map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, function(m) { return map[m]; });
        };

        // Strip HTML tags from description
        // description = stripHtml(description);

        // Build the HTML structure with escaped content
        var html = '<div class="io_list_view_content">';
        // html += '<div class="io_item_description_line">' + escapeHtml(description) + '</div>';
        html += '<div class="io_item_details_labeled">';

        // Setup field - only add if valid
        if (indoorOutdoor && indoorOutdoor !== '0' && indoorOutdoor.length > 0) {
            html += '<div class="io_detail_item io_detail_setup">';
            html += '<span class="io_detail_label">Setup:</span>';
            html += '<span class="io_detail_value">' + escapeHtml(indoorOutdoor) + '</span>';
            html += '</div>';
        }

        // Operators field - only add if valid
        var operatorsText = staff ? staff + ' Adult Supervision Required' : "";
        if (operatorsText &&
            operatorsText !== '0 Adult Supervision Required' &&
            operatorsText !== 'Adult Supervision Required' &&
            operatorsText !== '0') {
            html += '<div class="io_detail_item io_detail_operators">';
            html += '<span class="io_detail_label">Operators:</span>';
            html += '<span class="io_detail_value">' + escapeHtml(operatorsText) + '</span>';
            html += '</div>';
        }

        // Power field - only add if valid
        var powerText = electric ? electric + ' Outlets' : "";
        if (powerText &&
            powerText !== '0 Outlets' &&
            powerText !== '0.00 Outlets' &&
            powerText !== 'Outlets' &&
            powerText !== '0') {
            html += '<div class="io_detail_item io_detail_power">';
            html += '<span class="io_detail_label">Power:</span>';
            html += '<span class="io_detail_value">' + escapeHtml(powerText) + '</span>';
            html += '</div>';
        }

        // Size field - only add if valid
        if (dimensions && dimensions !== '0' && dimensions.length > 0) {
            html += '<div class="io_detail_item io_detail_size">';
            html += '<span class="io_detail_label">Size:</span>';
            html += '<span class="io_detail_value">' + escapeHtml(dimensions) + '</span>';
            html += '</div>';
        }

        html += '</div>'; // close io_item_details_labeled
        html += '</div>'; // close io_list_view_content

        // Insert before the buttons container
        $item.find('.io_buttons_container').before(html);
    });
}

/* when clicking the thumb swatches under main image (2nd image for an item) */
function updateCategoryPic(img) {
    /* calling image */
    let thumb_id = img.id;
    let big_id = thumb_id.replace('thumb', 'big').replace(/:/g, '\\:');

    /* main image we are updating */
    let main_img = jQuery(img).parent().parent().find(".io_image_big")[0];

    let img_big = document.querySelector("#" + big_id);
    main_img.src = img_big.href;
    /* document.querySelector("#single_image").href =img_big.href; */
}

jQuery(document).ready(function($) {
    // Hide price when zero
    jQuery(".rentNameIO_pricespan").each(function () {
        if( !Number( this.textContent.replace(/[^0-9.-]+/g,"") ) ){
            jQuery(this.parentElement).hide();
        }
    });
    jQuery(".io_item2_list").each(function(){
        let rentalId = jQuery(this).find('.item_rentalid').text().trim();
        if (io_categoryVariantImages == 'on'){
            // Check if category data exists before accessing
            if (typeof window.io_category_data !== 'undefined' && window.io_category_data[rentalId]) {
                CategoryGallery(rentalId, window.io_category_data[rentalId]['rental_name'], window.io_category_data[rentalId]['images_arr']);
            } else {
                console.warn('[IO Category Gallery] No category data found for rental', rentalId);
            }
        }
    });


    console.log('[IO View Toggle] Document ready, initializing view toggle functionality');

    // Check if category_id has a numeric value to identify actual category pages
    // This must happen before any view state is applied
    var categoryId = $('.category_id').text().trim();
    var hasNumericCategoryId = categoryId && !isNaN(categoryId) && categoryId.length > 0;

    if (!hasNumericCategoryId) {
        console.log('[IO View Toggle] No valid numeric category ID found, this is not a category page - skipping initialization');
        return;
    }

    console.log('[IO View Toggle] Category page detected with categoryId:', categoryId);
    $('body').addClass('io-has-category-id');

    // Show the toggle buttons on category pages
    $('.io_view_toggle_container').show();
    console.log('[IO View Toggle] Toggle buttons displayed for category page');

    // Track if view toggle has been initialized
    var isInitialized = false;

    // Initialize view toggle functionality
    function initViewToggle(force) {
        // Skip if already initialized unless forced
        if (isInitialized && !force) {
            console.log('[IO View Toggle] Already initialized, skipping');
            return;
        }

        console.log('[IO View Toggle] Initializing view toggle functionality');

        // Check if toggle buttons exist
        if ($('.io_view_toggle_btn').length === 0) {
            console.warn('[IO View Toggle] Toggle buttons not found in DOM');
            return;
        }
        console.log('[IO View Toggle] Found', $('.io_view_toggle_btn').length, 'toggle buttons');

        // Check if category container exists
        if ($('.io_catdiv2').length === 0) {
            console.warn('[IO View Toggle] Category container (.io_catdiv2) not found');
            return;
        }
        console.log('[IO View Toggle] Found', $('.io_catdiv2').length, 'category containers');

        // Get saved view preference from localStorage
        var savedView = localStorage.getItem('io_category_view') || 'tile';
        console.log('[IO View Toggle] Retrieved saved view preference:', savedView);

        // Set initial view
        $('.io_catdiv2').removeClass('tile-view list-view').addClass(savedView + '-view');
        console.log('[IO View Toggle] Applied initial view class:', savedView + '-view');

        // Update button states
        $('.io_view_toggle_btn').removeClass('active');
        $('.io_view_toggle_btn[data-view="' + savedView + '"]').addClass('active');
        console.log('[IO View Toggle] Updated button states, active button:', savedView);

        // Generate list view content if initial view is list
        if (savedView === 'list') {
            if (typeof generateListViewContent === 'function') {
                generateListViewContent();
            } else {
                console.warn('[IO View Toggle] generateListViewContent function not available yet');
            }
        }

        // Log current items count
        var itemCount = $('.io_item2_list').length;
        console.log('[IO View Toggle] Found', itemCount, 'items in category');

        // Handle toggle button clicks using native JavaScript for better compatibility
        // Remove any existing event listeners first
        $('.io_view_toggle_btn').off('click.viewToggle');

        // Use native JavaScript addEventListener for more reliable event handling
        var buttons = document.querySelectorAll('.io_view_toggle_btn');
        console.log('[IO View Toggle] Attaching event listeners to', buttons.length, 'buttons using native JS');

        buttons.forEach(function(button) {
            // Remove any existing listener
            var newButton = button.cloneNode(true);
            button.parentNode.replaceChild(newButton, button);

            // Add fresh event listener
            newButton.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();

                var view = this.getAttribute('data-view');
                console.log('[IO View Toggle] Button clicked (native listener), switching to view:', view);

                // Generate list view content if switching to list view
                if (view === 'list') {
                    if (typeof generateListViewContent === 'function') {
                        generateListViewContent();
                    } else {
                        console.warn('[IO View Toggle] generateListViewContent function not available');
                    }
                }

                // Update button states
                document.querySelectorAll('.io_view_toggle_btn').forEach(function(btn) {
                    btn.classList.remove('active');
                });
                this.classList.add('active');
                console.log('[IO View Toggle] Updated button active states');

                // Update grid view
                var catdiv = document.querySelector('.io_catdiv2');
                if (catdiv) {
                    catdiv.classList.remove('tile-view', 'list-view');
                    catdiv.classList.add(view + '-view');
                    console.log('[IO View Toggle] Applied view class:', view + '-view');
                }

                // Save preference
                localStorage.setItem('io_category_view', view);
                console.log('[IO View Toggle] Saved view preference to localStorage:', view);

                // Debug: Log current layout state
                setTimeout(function() {
                    if (catdiv) {
                        var containerClasses = catdiv.className;
                        var visibleItems = document.querySelectorAll('.io_item2_list:not([style*="display: none"])').length;
                        console.log('[IO View Toggle] Layout updated - Container classes:', containerClasses);
                        console.log('[IO View Toggle] Visible items after view change:', visibleItems);

                        // Check if list view content is properly shown/hidden
                        if (view === 'list') {
                            var visibleListContent = document.querySelectorAll('.io_list_view_content:not([style*="display: none"])').length;
                            console.log('[IO View Toggle] Visible list content elements:', visibleListContent);
                        }
                    }
                }, 100);
            }, true); // Use capture phase

            console.log('[IO View Toggle] Event listener attached to button:', newButton.getAttribute('data-view'));
        });

        console.log('[IO View Toggle] Event handlers attached successfully');

        // Mark as initialized
        isInitialized = true;
    }

    // Initialize when page loads
    console.log('[IO View Toggle] Starting initial setup');
    initViewToggle();

    // Also initialize after dynamic content loads (if applicable)
    $(document).on('io_content_loaded', function() {
        console.log('[IO View Toggle] Dynamic content loaded event detected, reinitializing');
        initViewToggle();
    });

    // Debug: Monitor for DOM changes that might affect our functionality
    if (typeof MutationObserver !== 'undefined') {
        var mutationTimeout;
        var lastItemCount = $('.io_item2_list').length;

        var observer = new MutationObserver(function(mutations) {
            // Debounce: clear existing timeout and set a new one
            clearTimeout(mutationTimeout);

            mutationTimeout = setTimeout(function() {
                var currentItemCount = $('.io_item2_list').length;

                // Only trigger if we have new items that weren't there before
                if (currentItemCount > lastItemCount) {
                    console.log('[IO View Toggle] New items detected in DOM (' + lastItemCount + ' -> ' + currentItemCount + ')');
                    lastItemCount = currentItemCount;

                    // If already initialized, just generate list view content for new items if in list view
                    if (isInitialized) {
                        var currentView = localStorage.getItem('io_category_view') || 'tile';
                        if (currentView === 'list') {
                            console.log('[IO View Toggle] Generating list view content for new items');
                            if (typeof generateListViewContent === 'function') {
                                generateListViewContent();
                            } else {
                                console.warn('[IO View Toggle] generateListViewContent function not available');
                            }
                        }
                    } else {
                        // Not initialized yet, so initialize
                        console.log('[IO View Toggle] Initializing due to new items');
                        initViewToggle();
                    }
                }
            }, 250); // 250ms debounce
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        console.log('[IO View Toggle] DOM mutation observer started');
    }

    // Debug: Log window resize events that might affect responsive layout
    $(window).on('resize.viewToggle', function() {
        var windowWidth = $(window).width();
        var currentView = $('.io_catdiv2').hasClass('list-view') ? 'list' : 'tile';
        console.log('[IO View Toggle] Window resized to:', windowWidth, 'px, current view:', currentView);
    });

    console.log('[IO View Toggle] Initialization complete');
});