(function ($) {
    'use strict';

    // Admin part of the plugin
    // Initialize the admin functionality when document is ready
    $(document).ready(function () {

        $('.wcps-copy-shortcode').on('click', function () {
            var shortcodeText = $(this).data('clipboard-text');

            // Use Clipboard API for modern browsers
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(shortcodeText)
                    .then(function () {
                        // Success feedback
                        var originalText = $(this).text();
                        $(this).text('Copied!');

                        var $button = $(this);
                        setTimeout(function () {
                            $button.text(originalText);
                        }, 1500);
                    }.bind(this))
                    .catch(function () {
                        // Fallback to old method if clipboard API fails
                        fallbackCopyTextToClipboard(shortcodeText, $(this));
                    }.bind(this));
            } else {
                // Fallback for browsers that don't support clipboard API
                fallbackCopyTextToClipboard(shortcodeText, $(this));
            }
        });

        // Add clear search functionality
        $('#showcase-search-input').on('search', function () {
            if ($(this).val() === '') {
                // If search input is cleared, redirect to the page without search parameter
                window.location.href = removeURLParameter(window.location.href, 's');
            }
        });

        // Make sure checkboxes in header/footer sync with each other
        $('#cb-select-all-1, #cb-select-all-2').on('change', function () {
            var isChecked = $(this).prop('checked');
            $('#cb-select-all-1, #cb-select-all-2').prop('checked', isChecked);
            $('input[name="showcase_ids[]"]').prop('checked', isChecked);
        });

        // Handle checkbox changes to show/hide floating delete button
        $('input[name="showcase_ids[]"]').on('change', function () {
            var checkedCount = $('input[name="showcase_ids[]"]:checked').length;
            if (checkedCount > 0) {
                $('#wcps-floating-delete').fadeIn();
            } else {
                $('#wcps-floating-delete').fadeOut();
            }
        });

        // Handle "Select All" checkbox changes
        $('#cb-select-all-1, #cb-select-all-2').on('change', function () {
            var isChecked = $(this).prop('checked');
            if (isChecked) {
                $('#wcps-floating-delete').fadeIn();
            } else {
                $('#wcps-floating-delete').fadeOut();
            }
        });

        // Handle floating delete button click
        $('.wcps-bulk-delete').on('click', function () {
            var selectedIds = [];

            // Get all checked checkboxes
            $('input[name="showcase_ids[]"]:checked').each(function () {
                selectedIds.push($(this).val());
            });

            if (selectedIds.length === 0) {
                alert('Please select at least one showcase to delete.');
                return;
            }

            if (confirm('Are you sure you want to delete the selected showcases?')) {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'proddisp_bulk_delete_showcases',
                        ids: selectedIds,
                        nonce: $('#proddisp_nonce').val()
                    },
                    success: function (response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert(response.data || 'An error occurred during the delete operation.');
                        }
                    },
                    error: function () {
                        alert('An error occurred during the delete operation.');
                    }
                });
            }
        });

        // Bulk action form handling
        $('#wcps-bulk-action-form').on('submit', function (e) {
            e.preventDefault();

            var action = $('#bulk-action-selector-top').val();
            if (action == '-1') {
                action = $('#bulk-action-selector-bottom').val();
            }

            if (action == 'delete') {
                var selectedIds = [];

                // Get all checked checkboxes with the name 'showcase_ids[]'
                $('input[name="showcase_ids[]"]:checked').each(function () {
                    selectedIds.push($(this).val());
                });

                if (selectedIds.length === 0) {
                    alert('Please select at least one showcase to delete.');
                    return;
                }

                if (confirm('Are you sure you want to delete the selected showcases?')) {
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'proddisp_bulk_delete_showcases',
                            ids: selectedIds,
                            nonce: $('#proddisp_nonce').val()
                        },
                        success: function (response) {
                            if (response.success) {
                                location.reload();
                            } else {
                                alert(response.data || 'An error occurred during the delete operation.');
                            }
                        },
                        error: function () {
                            alert('An error occurred during the delete operation.');
                        }
                    });
                }
            }
        });



        // Delete showcase functionality
        $('.wcps-delete-showcase').on('click', function (e) {
            e.preventDefault();

            var showcaseId = $(this).data('id');

            if (confirm('Are you sure you want to delete this showcase? This action cannot be undone.')) {
                deleteShowcase(showcaseId);
            }
        });

        // Initialize color pickers in display 
        if ($.fn.wpColorPicker) {
            $('.wcps-color-picker').wpColorPicker({
                change: function (event, ui) {
                    // Get the input element
                    var $input = $(this);
                    // Update the input value with the new color
                    $input.val(ui.color.toString());
                    // Trigger the updatePreviewStyles function for instant update
                    updatePreviewStyles();
                    // Mark this as a style-only change to prevent full preview regeneration
                    $input.data('style-only-change', true);
                }
            });
        }

        // Initialize select2 for product and category selectors

        if ($.fn.select2) {
            $('#proddisp_products, #proddisp_category, #proddisp_tag, #proddisp_brand, #proddisp_attribute, #proddisp_attribute_terms').select2({
                width: '100%',
                placeholder: 'Select items'
            });
        }

        // Tabs functionality
        $('.wcps-tabs-nav a').on('click', function (e) {
            e.preventDefault();

            // Remove active class from all tabs
            $('.wcps-tabs-nav a').removeClass('active');
            $('.wcps-tab-panel').removeClass('active');

            // Add active class to current tab
            $(this).addClass('active');

            // Show the corresponding panel
            $($(this).attr('href')).addClass('active');

            // Save active tab to localStorage
            var activeTab = $(this).attr('href');
            localStorage.setItem('proddisp_active_tab', activeTab);
        });

        // Initialize tabs on page load to prevent jumping
        $(document).ready(function () {
            // Hide all tabs and panels initially
            $('.wcps-tabs-nav a').removeClass('active');
            $('.wcps-tab-panel').removeClass('active');

            var savedTab = localStorage.getItem('proddisp_active_tab');

            if (savedTab) {
                // Check if the saved tab exists
                var $savedTabLink = $('.wcps-tabs-nav a[href="' + savedTab + '"]');
                if ($savedTabLink.length > 0) {
                    // Add active class to saved tab
                    $savedTabLink.addClass('active');
                    $(savedTab).addClass('active');
                } else {
                    // If saved tab doesn't exist, default to first tab
                    $('.wcps-tabs-nav a:first').addClass('active');
                    $('.wcps-tab-panel:first').addClass('active');
                }
            } else {
                // If no saved tab, default to first tab
                $('.wcps-tabs-nav a:first').addClass('active');
                $('.wcps-tab-panel:first').addClass('active');
            }

            // Initialize copy functionality
            initCopyFunctionality();
        });

        // Initialize copy functionality
        function initCopyFunctionality() {
            // console.log('Initializing copy functionality...');

            // Shortcode copy functionality
            $(document).on('click', '.wcps-copy-shortcode-btn', function (e) {
                e.preventDefault();
                // console.log('Copy button clicked');

                var shortcode = $(this).data('shortcode');
                var $button = $(this);

                // console.log('Shortcode to copy:', shortcode);

                // Copy to clipboard
                if (navigator.clipboard && window.isSecureContext) {
                    // Use modern clipboard API
                    navigator.clipboard.writeText(shortcode).then(function () {
                        // console.log('Copied successfully via clipboard API');
                        showCopySuccess($button);
                    }).catch(function (err) {
                        // console.log('Clipboard API failed:', err);
                        fallbackCopyTextToClipboard(shortcode, $button);
                    });
                } else {
                    // Fallback for older browsers
                    // console.log('Using fallback copy method');
                    fallbackCopyTextToClipboard(shortcode, $button);
                }
            });
        }

        // Toggle fields based on product and cat source selection
        $('input[name="proddisp_product_source"]').on('change', function () {
            var source = $(this).val();

            if (source === 'specific') {
                $('#wcps-specific-products').show();
                $('#wcps-category-selection, #wcps-tag-selection, #wcps-brand-selection, #wcps-attribute-selection').hide();
            } else if (source === 'category') {
                $('#wcps-category-selection').show();
                $('#wcps-specific-products, #wcps-tag-selection, #wcps-brand-selection, #wcps-attribute-selection').hide();
            } else if (source === 'tag') {
                $('#wcps-tag-selection').show();
                $('#wcps-specific-products, #wcps-category-selection, #wcps-brand-selection, #wcps-attribute-selection').hide();
            } else if (source === 'brand') {
                $('#wcps-brand-selection').show();
                $('#wcps-specific-products, #wcps-category-selection, #wcps-tag-selection, #wcps-attribute-selection').hide();
            } else if (source === 'attribute') {
                $('#wcps-attribute-selection').show();
                $('#wcps-specific-products, #wcps-category-selection, #wcps-tag-selection, #wcps-brand-selection').hide();
            }


            // Update preview - this is a structural change (product selection)
            generatePreview();
        });

        // Toggle excerpt length field based on show description checkbox
        $('input[name="proddisp_show_description"]').on('change', function () {
            if ($(this).is(':checked')) {
                $('#wcps-excerpt-length').show();
            } else {
                $('#wcps-excerpt-length').hide();
            }

            // Update preview - this is a structural change
            generatePreview();
        });


        
        // Function to remove URL parameter on search in admin showcase list page 
        function removeURLParameter(url, parameter) {
            var urlParts = url.split('?');
            if (urlParts.length >= 2) {
                var prefix = encodeURIComponent(parameter) + '=';
                var parts = urlParts[1].split(/[&;]/g);

                for (var i = parts.length; i-- > 0;) {
                    if (parts[i].lastIndexOf(prefix, 0) !== -1) {
                        parts.splice(i, 1);
                    }
                }

                return urlParts[0] + (parts.length > 0 ? '?' + parts.join('&') : '');
            }
            return url;
        }


        // Define style options for each layout type
        
        // Function to update style options based on selected layout
        function updateStyleOptions(layout) {
            var $styleSelect = $('#proddisp_layout_mode');
            var currentStyle = $styleSelect.val();

            // Clear existing showcase sub laymode mode 
            $styleSelect.empty();

            // Add new options based on selected layout
            if (layoutStyles[layout]) {
                $.each(layoutStyles[layout], function (index, style) {
                    var selected = (currentStyle === style.value) ? ' selected' : '';
                    $styleSelect.append('<option value="' + style.value + '"' + selected + '>' + style.label + '</option>');
                });
            } else {
                // Fallback default options if no specific styles defined
                $styleSelect.append('<option value="basic-grid">Basic Grid</option>');
                $styleSelect.append('<option value="card-grid">Card Grid</option>');
                $styleSelect.append('<option value="masonry-grid">Masonry Grid</option>');
            }

            // Update preview after style options change
            generatePreview();
        }


        // Update the current layout when back to editor page to update layout style 
        $(document).ready(function () {
            var initialLayout = $('#proddisp_layout').val();
            updateStyleOptions(initialLayout);
        });

        // Refresh preview button
        $('.wcps-refresh-preview').on('click', function () {
            generatePreview();
        });

        // Define style-only fields that should only trigger CSS updates
        
        // Layout mode change event class name 
        $('#proddisp_layout_mode').on('change', function () {
            // Update the container class immediately (in case AJAX is slow)
            setTimeout(updatePreviewContainerClass, 100);

            // Also update after AJAX completes
            $(document).ajaxComplete(function (event, xhr, settings) {
                // Check if this is the preview AJAX request
                if (settings.data && typeof settings.data === 'string' && settings.data.indexOf('action=proddisp_get_shortcode_preview') !== -1) {
                    // Update the container class after preview is loaded
                    setTimeout(updatePreviewContainerClass, 200);
                }
            });
        });

        // Product search filter for specific products
        $(document).on('input', '#wcps-product-search', function () {
            var search = $(this).val().toLowerCase();
            $('#proddisp_products option').each(function () {
                var text = $(this).text().toLowerCase();
                $(this).toggle(text.indexOf(search) !== -1);
            });
            // If using Select2, trigger change for live update
            if ($.fn.select2 && $('#proddisp_products').data('select2')) {
                $('#proddisp_products').trigger('change.select2');
            }
        });


        // Reusable function to show the ToastMaster pricing modal
        function showPricingModal() {
            Toast.price({
                title: '🚀 Your Ultimate WooCommerce Companion!',
                subtitle: 'Evaluate the features and select a bundle based on your needs.',
                toggles: {
                    options: ['Yearly', 'Lifetime'],
                    active: 'Yearly',
                    savings: { 'Yearly': 'Save 73%', 'Lifetime': 'Save 80%' }
                },
                plans: [
                    {
                        name: 'Single',
                        prices: {
                            'Yearly': { original: 155.88, current: 41.99, period: '/year' },
                            'Lifetime': { original: 155.88, current: 108.49, period: '/lifetime' }
                        },
                        features: [
                            'All Pro Layout Showcase',
                            'Editor page Easy Layout Type and Mode Selections',
                            'Display Mode Product Actions',
                            'Upcomming Showcase',
                            'Priority Support',
                        ],
                        button: {
                            text: 'Get It Now',
                            callback: function (data) {
                                // data contains: { plan, toggle, prices }
                                pricingCallback(data.plan, data.toggle);
                            }
                        }
                    },
                    {
                        name: 'Pro-5',
                        prices: {

                            'Yearly': { original: 359.88, current: 120.99, period: '/year' },
                            'Lifetime': { original: 426.75, current: 240.99, period: '/lifetime' }
                        },
                        features: [
                            'All Pro Layout Showcase',
                            'Editor page Easy Layout Type and Mode Selections',
                            'Display Mode Product Actions',
                            'Upcomming Showcase',
                            'Priority Support',
                        ],
                        button: {
                            text: 'Grab It Now',
                            callback: function (data) {
                                // data contains: { plan, toggle, prices }
                                pricingCallback(data.plan, data.toggle);
                            }
                        },
                        tag: Toast.tag('new', 'HOT DEAL', '#e74c3c')
                    },
                    {
                        name: 'Agency-100',
                        prices: {
                            'Yearly': { original: 599.88, current: 320.99, period: '/year' },
                            'Lifetime': { original: 751.00, current: 448.99, period: '/lifetime' }
                        },
                        features: [
                            'All Pro Layout Showcase',
                            'Editor page Easy Layout Type and Mode Selections',
                            'Display Mode Product Actions',
                            'Upcomming Showcase',
                            'Priority Support',
                        ],
                        button: {
                            text: 'Get It Now',
                            callback: function (data) {
                                // data contains: { plan, toggle, prices }
                                pricingCallback(data.plan, data.toggle);
                            }
                        },

                    }
                ],
                recommended: 'Pro',
                guarantee: {
                    days: 14,
                    title: '14-Day Money-Back Guarantee',
                    text: 'Try it risk-free. If you\'re not satisfied, get a full refund within 14 days.'
                },
                backdropClose: true,
                bodyClose: true,
                escClose: true
            });
        }
        // Make the entire .wcps-pro-locked area clickable for the ToastMaster pricing modal
        $(document).on('click', '.wcps-pro-locked', function (e) {
            showPricingModal();
        });
        // Add click handler for .wcps-upgrade-pro-btn to show the same pricing modal
        $(document).on('click', '.wcps-upgrade-pro-btn', function (e) {
            e.preventDefault();
            showPricingModal();
        });
        // Prevent modal on input click inside .wcps-pro-locked
        $(document).on('click', '.wcps-pro-locked input, .wcps-pro-locked select, .wcps-pro-locked textarea, .wcps-pro-locked label', function (e) {
            e.stopPropagation();
        });

    });

    // Pricing Function 
    function pricingCallback(plan, selectedToggle) {

        let licenses = 1; // Default for Single
        if (plan.name === 'Single') {
            licenses = 1;
        } else if (plan.name === 'Pro-5') {
            licenses = 5;
        }
        else if (plan.name === 'Agency-100') {
            licenses = 100;
        }

        // Determine billing cycle based on selected toggle
        let billingCycle = 'yearly'; // Default
        if (selectedToggle === 'Lifetime') {
            billingCycle = 'lifetime';
        }

        // console.log('Selected Plan:', plan.name);
        // console.log('Selected Toggle:', selectedToggle);
        // console.log('Licenses:', licenses);
        // console.log('Billing Cycle:', billingCycle);

        const handler = FS.Checkout.configure({
            plugin_id: '19582',
            plan_id: '32465',
            public_key: 'pk_5e7406cb0a5b592c68a76ad7b706c',
        });

        handler.open({
            name: 'Product Display',
            licenses: licenses,
            billing_cycle: billingCycle,
            purchaseCompleted: function (response) {
                // The logic here will be executed immediately after the purchase confirmation.
                // alert(response.user.email);
            },
            success: function (response) {
                // The logic here will be executed after the customer closes the checkout, after a successful purchase.
                // alert(response.user.email);
            }
        });
    }

    // Add to the existing generatePreview function
    var originalGeneratePreview = window.generatePreview || function () { };
    window.generatePreview = function () {
        // Call the original function
        originalGeneratePreview.apply(this, arguments);

        // Update the container class after the preview is generated
        setTimeout(updatePreviewContainerClass, 500);
    };

    // Also update on initial load
    setTimeout(updatePreviewContainerClass, 1000);


    // ENd 

    function updatePreviewContainerClass() {
        // Get the selected layout mode
        var selectedLayoutMode = $('#proddisp_layout_mode').val();

        // Target the preview container and update its class
        var $previewContainer = $('#wcps-showcase-preview .wcps-container');

        if ($previewContainer.length) {
            // Remove any existing layout classes (that start with wcps-layout-)
            var classesToRemove = [];
            $.each($previewContainer.attr('class').split(' '), function (index, className) {
                if (className.indexOf('wcps-layout-') === 0) {
                    classesToRemove.push(className);
                }
            });

            $previewContainer.removeClass(classesToRemove.join(' '));

            // Add the new layout class based on the selected layout mode
            $previewContainer.addClass('wcps-layout-' + selectedLayoutMode);

            // console.log('Updated container class to: wcps-layout-' + selectedLayoutMode);
        } else {
            // console.log('Preview container not found');
        }
    }

    // END 

    function fallbackCopyTextToClipboard(text, $button) {
        var tempInput = $('<input>');
        $('body').append(tempInput);
        tempInput.val(text).select();

        try {
            var successful = document.execCommand('copy');

            if (successful) {
                // console.log('Copied successfully via fallback method');
                showCopySuccess($button);
            } else {
                console.error('Fallback copy failed');
                alert('Failed to copy to clipboard. Please try selecting and copying the text manually.');
            }
        } catch (err) {
            console.error('Unable to copy to clipboard', err);
            alert('Failed to copy to clipboard. Please try selecting and copying the text manually.');
        }

        tempInput.remove();
    }


    // Call this function when document is ready and when initializing icon pickers
    function initFullIconFunctionality() {
        // Toggle display of icon picker based on checkbox state
        $('.wcps-tab-panel input[type="checkbox"]').each(function () {
            var $checkbox = $(this);
            var $iconSelect = $checkbox.closest('.wcps-button-option').find('.wcps-icon-select');

            // Set initial state
            if ($checkbox.is(':checked')) {
                $iconSelect.show();
            } else {
                $iconSelect.hide();
            }

            // Handle toggle
            $checkbox.off('change').on('change', function () {
                if ($(this).is(':checked')) {
                    $iconSelect.slideDown(200);
                } else {
                    $iconSelect.slideUp(200);
                }
            });
        });

        // Toggle icon picker based on display mode
        $('.wcps-tab-panel select[name$="_display_mode"]').each(function () {
            var $select = $(this);
            var $iconPicker = $select.closest('.wcps-icon-select').find('.wcps-icon-picker');

            // Set initial state
            if ($select.val() === 'text_only') {
                $iconPicker.hide();
            } else {
                $iconPicker.show();
            }

            // Handle change
            $select.off('change').on('change', function () {
                if ($(this).val() === 'text_only') {
                    $iconPicker.slideUp(200);
                } else {
                    $iconPicker.slideDown(200);
                }
            });
        });

        // Initialize FontAwesome icon picker
        completeFontAwesomeIconPicker();
    }

    // Add this line to your document.ready function
    $(document).ready(function () {
        // Rest of your existing code...

        // Initialize icon functionality
        initFullIconFunctionality();

        // For cases where content is loaded dynamically
        $(document).on('proddisp_content_loaded', function () {
            initFullIconFunctionality();
        });
    });
    // Icon picker -----------------------------------------------------------------------------END

    // Function to show copy success
    function showCopySuccess($button) {
        // console.log('showCopySuccess called');

        var $icon = $button.find('.dashicons');
        // console.log('Icon element found:', $icon.length);
        // console.log('Icon before change:', $icon.attr('class'));

        // Store original icon classes
        var originalClasses = $icon.attr('class');
        // console.log('Original classes stored:', originalClasses);

        // Add copied class to button
        $button.addClass('copied');

        // Change icon to checkmark
        $icon.attr('class', 'dashicons dashicons-yes');
        // console.log('Icon after change to checkmark:', $icon.attr('class'));

        // Show success notice
        var $notice = $('<div class="wcps-copy-notice"><span class="dashicons dashicons-yes"></span>Shortcode copied to clipboard!</div>');
        $('body').append($notice);

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

        // Remove copied class and notice after delay
        setTimeout(function () {
            // console.log('Restoring icon...');
            $button.removeClass('copied');
            // Restore original icon classes
            $icon.attr('class', originalClasses);
            // console.log('Icon after restoration:', $icon.attr('class'));
            $notice.removeClass('show');
            setTimeout(function () {
                $notice.remove();
            }, 300);
        }, 2000);
    }

    // --- Pricing Callback for ToastMaster Modal ---



    // Get start page js 
    // FAQ Toggle Functionality
    function initFAQ() {
        $('.faq-toggle').on('click', function (e) {
            e.preventDefault();

            const $toggle = $(this);
            const $content = $toggle.next('.faq-content');
            const $icon = $toggle.find('.faq-icon');
            const $faqItem = $toggle.closest('.faq-item');

            // Check if this FAQ is currently active
            const isActive = $toggle.hasClass('active');

            // Close all other FAQ items (accordion behavior)
            $('.faq-toggle').not($toggle).removeClass('active');
            $('.faq-content').not($content).slideUp(300);
            $('.faq-icon').not($icon).text('+').css('transform', 'rotate(0deg)');
            $('.faq-item').not($faqItem).removeClass('active');

            // Toggle current FAQ
            if (isActive) {
                // Close current FAQ
                $toggle.removeClass('active');
                $content.slideUp(300);
                $icon.text('+');
                $faqItem.removeClass('active');
            } else {
                // Open current FAQ
                $toggle.addClass('active');
                $content.slideDown(300);
                $icon.text('−');
                $faqItem.addClass('active');
            }
        });
    }

    // Initialize all functionality
    function init() {
        applyPreviewScaling();
        initFAQ();
        initSmoothScroll();
        initAnimations();
        initCopyShortcodes();
        initCardEffects();
        initParallax();
        initProgressBars();
        initTypewriter();
        initEnhancedCards();
        initScrollAnimations();
        initAutoResize();
        initKeyboardNavigation();
        initButtonLoading();
        initFAQSearch();
        

        // Animate stats when page loads
        setTimeout(animateStats, 500);

        // Add loaded class to enable CSS transitions
        $('body').addClass('page-loaded');
    }

    // Initialize when document is ready
    init();

    // Re-initialize on window resize for responsive adjustments
    $(window).on('resize', function () {
        // Only re-init parallax on resize
        initParallax();
    });

    // Add custom easing functions
    $.easing.easeOutCubic = function (x, t, b, c, d) {
        return c * ((t = t / d - 1) * t * t + 1) + b;
    };

    $.easing.easeInOutCubic = function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
        return c / 2 * ((t -= 2) * t * t + 2) + b;
    };

    // Utility functions
    const utils = {
        // Debounce function
        debounce: function (func, wait, immediate) {
            let timeout;
            return function () {
                const context = this, args = arguments;
                const later = function () {
                    timeout = null;
                    if (!immediate) func.apply(context, args);
                };
                const callNow = immediate && !timeout;
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
                if (callNow) func.apply(context, args);
            };
        },

        // Throttle function
        throttle: function (func, limit) {
            let inThrottle;
            return function () {
                const args = arguments;
                const context = this;
                if (!inThrottle) {
                    func.apply(context, args);
                    inThrottle = true;
                    setTimeout(() => inThrottle = false, limit);
                }
            };
        },

        // Generate random ID
        generateId: function () {
            return Math.random().toString(36).substr(2, 9);
        },

        // Format number with commas
        formatNumber: function (num) {
            return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
    };

    // Make utils available globally
    window.WCPSUtils = utils;


})(jQuery);



// Initialize when document is ready
/* $(document).ready(function () {
    initPreviewScaling();
});

// Wrap the preview scaling in jQuery to fix the $ is not a function error
(function ($) {
    'use strict';

    // Enhanced preview scaling function that works with dynamic content
    

})(jQuery); */