/* global jQuery */
/* global wp */

/******************************************************************
*** Enhanced Icon Picker for Social Media Repeater ***
*******************************************************************/

// Enhanced Icon Picker functionality
(function($) {
    'use strict';

    // Enhanced icon libraries with comprehensive business and service icons
    const iconLibraries = {
        fontAwesome: {
            // Business & Service Icons (Perfect for Why Choose Us section)
            'fas fa-star': 'Premium Quality',
            'fas fa-shield-alt': 'Security & Trust',
            'fas fa-headset': 'Customer Support',
            'fas fa-shipping-fast': 'Fast Shipping',
            'fas fa-award': 'Award Winning',
            'fas fa-thumbs-up': 'Satisfaction',
            'fas fa-heart': 'Care & Love',
            'fas fa-gem': 'Premium',
            'fas fa-medal': 'Excellence',
            'fas fa-crown': 'Royal Treatment',
            'fas fa-handshake': 'Trust',
            'fas fa-clock': 'Fast Service',
            'fas fa-check-circle': 'Quality Assured',
            'fas fa-lock': 'Secure',
            'fas fa-rocket': 'Innovation',
            'fas fa-lightbulb': 'Smart Solutions',
            'fas fa-cogs': 'Professional',
            'fas fa-users': 'Team Support',
            'fas fa-phone': 'Contact',
            'fas fa-envelope': 'Email Support',
            'fas fa-map-marker-alt': 'Location',
            'fas fa-globe': 'Global Service',
            'fas fa-wifi': 'Connected',
            'fas fa-mobile-alt': 'Mobile Friendly',
            'fas fa-laptop': 'Technology',
            'fas fa-database': 'Data Management',
            'fas fa-cloud': 'Cloud Service',
            'fas fa-sync': 'Updates',
            'fas fa-download': 'Easy Download',
            'fas fa-upload': 'Easy Upload',
            'fas fa-search': 'Search',
            'fas fa-filter': 'Filter',
            'fas fa-sort': 'Organization',
            'fas fa-list': 'Catalog',
            'fas fa-th': 'Grid View',
            'fas fa-chart-line': 'Growth',
            'fas fa-chart-bar': 'Analytics',
            'fas fa-dollar-sign': 'Pricing',
            'fas fa-credit-card': 'Payment',
            'fas fa-shopping-cart': 'Shopping',
            'fas fa-gift': 'Gifts',
            'fas fa-tag': 'Offers',
            'fas fa-percent': 'Discounts',
            'fas fa-truck': 'Delivery',
            'fas fa-undo': 'Returns',
            'fas fa-exchange-alt': 'Exchange',
            'fas fa-tools': 'Maintenance',
            'fas fa-wrench': 'Repair',
            'fas fa-home': 'Home Service',
            'fas fa-building': 'Business',
            'fas fa-store': 'Shop',
            'fas fa-warehouse': 'Warehouse',
            // Social Media Icons
            'fab fa-facebook-f': 'Facebook',
            'fab fa-twitter': 'Twitter',
            'fab fa-instagram': 'Instagram',
            'fab fa-linkedin-in': 'LinkedIn',
            'fab fa-youtube': 'YouTube',
            'fab fa-pinterest': 'Pinterest',
            'fab fa-tiktok': 'TikTok',
            'fab fa-snapchat-ghost': 'Snapchat',
            'fab fa-whatsapp': 'WhatsApp',
            'fab fa-telegram-plane': 'Telegram',
            'fab fa-discord': 'Discord',
            'fab fa-reddit': 'Reddit',
            'fab fa-tumblr': 'Tumblr',
            'fab fa-flickr': 'Flickr',
            'fab fa-vimeo-v': 'Vimeo',
            'fab fa-twitch': 'Twitch',
            'fab fa-spotify': 'Spotify',
            'fab fa-soundcloud': 'SoundCloud',
            'fab fa-github': 'GitHub',
            'fab fa-dribbble': 'Dribbble',
            'fab fa-behance': 'Behance',
            'fab fa-medium': 'Medium',
            'fab fa-skype': 'Skype',
            'fab fa-slack': 'Slack'
        },
        phosphor: {
            // Business & Service Icons (Perfect for Why Choose Us section)
            'ph ph-star': 'Premium Quality',
            'ph ph-shield-check': 'Security & Trust',
            'ph ph-headset': 'Customer Support',
            'ph ph-truck': 'Fast Shipping',
            'ph ph-trophy': 'Award Winning',
            'ph ph-thumbs-up': 'Satisfaction',
            'ph ph-heart': 'Care & Love',
            'ph ph-diamond': 'Premium',
            'ph ph-medal': 'Excellence',
            'ph ph-crown': 'Royal Treatment',
            'ph ph-handshake': 'Trust',
            'ph ph-clock': 'Fast Service',
            'ph ph-check-circle': 'Quality Assured',
            'ph ph-lock': 'Secure',
            'ph ph-rocket': 'Innovation',
            'ph ph-lightbulb': 'Smart Solutions',
            'ph ph-gear': 'Professional',
            'ph ph-users': 'Team Support',
            'ph ph-phone': 'Contact',
            'ph ph-envelope': 'Email Support',
            'ph ph-map-pin': 'Location',
            'ph ph-globe': 'Global Service',
            'ph ph-wifi-high': 'Connected',
            'ph ph-device-mobile': 'Mobile Friendly',
            'ph ph-laptop': 'Technology',
            'ph ph-database': 'Data Management',
            'ph ph-cloud': 'Cloud Service',
            'ph ph-arrows-clockwise': 'Updates',
            'ph ph-download': 'Easy Download',
            'ph ph-upload': 'Easy Upload',
            'ph ph-magnifying-glass': 'Search',
            'ph ph-funnel': 'Filter',
            'ph ph-sort-ascending': 'Organization',
            'ph ph-list': 'Catalog',
            'ph ph-grid-four': 'Grid View',
            'ph ph-trend-up': 'Growth',
            'ph ph-chart-bar': 'Analytics',
            'ph ph-currency-dollar': 'Pricing',
            'ph ph-credit-card': 'Payment',
            'ph ph-shopping-cart': 'Shopping',
            'ph ph-gift': 'Gifts',
            'ph ph-tag': 'Offers',
            'ph ph-percent': 'Discounts',
            'ph ph-package': 'Delivery',
            'ph ph-arrow-u-up-left': 'Returns',
            'ph ph-swap': 'Exchange',
            'ph ph-wrench': 'Maintenance',
            'ph ph-screwdriver': 'Repair',
            'ph ph-house': 'Home Service',
            'ph ph-buildings': 'Business',
            'ph ph-storefront': 'Shop',
            'ph ph-warehouse': 'Warehouse',
            // Social Media Icons
            'ph ph-facebook-logo': 'Facebook',
            'ph ph-twitter-logo': 'Twitter',
            'ph ph-instagram-logo': 'Instagram',
            'ph ph-linkedin-logo': 'LinkedIn',
            'ph ph-youtube-logo': 'YouTube',
            'ph ph-pinterest-logo': 'Pinterest',
            'ph ph-tiktok-logo': 'TikTok',
            'ph ph-snapchat-logo': 'Snapchat',
            'ph ph-whatsapp-logo': 'WhatsApp',
            'ph ph-telegram-logo': 'Telegram',
            'ph ph-discord-logo': 'Discord',
            'ph ph-reddit-logo': 'Reddit',
            'ph ph-tumblr-logo': 'Tumblr',
            'ph ph-twitch-logo': 'Twitch',
            'ph ph-spotify-logo': 'Spotify',
            'ph ph-github-logo': 'GitHub',
            'ph ph-dribbble-logo': 'Dribbble',
            'ph ph-behance-logo': 'Behance',
            'ph ph-medium-logo': 'Medium',
            'ph ph-skype-logo': 'Skype',
            'ph ph-slack-logo': 'Slack'
        }
    };

    // Initialize enhanced icon picker when document is ready
    $(document).ready(function() {

        // Check if icon libraries are loaded
        setTimeout(function() {
            const testFA = $('<i class="fas fa-star" style="position: absolute; left: -9999px;"></i>').appendTo('body');
            const testPH = $('<i class="ph ph-star" style="position: absolute; left: -9999px;"></i>').appendTo('body');

            setTimeout(function() {

                testFA.remove();
                testPH.remove();
            }, 100);
        }, 500);

        initializeEnhancedIconPicker();
        createEnhancedIconPickerModal();

    });

    function initializeEnhancedIconPicker() {
        // Watch for clicks and focus on any icon input fields
        $(document).on('click focus', '.customizer-repeater-icon-control input', function(e) {
            e.preventDefault();
            e.stopPropagation();

            const iconInput = $(this);
            const modal = $('#pawfect-enhanced-icon-picker-modal');

            // Remove any green border styling
            iconInput.css({
                'border-color': '#ddd',
                'box-shadow': 'none',
                'outline': 'none'
            });

            modal.data('target-input', iconInput);
            modal.addClass('active');
            modal.find('.pawfect-icon-search-input').focus();

            loadIconsInModal('fontawesome');

            // Blur the input to prevent cursor
            iconInput.blur();
        });

        // Prevent default FontAwesome iconpicker from showing
        $(document).on('iconpickerShow iconpickerCreate iconpickerSelected', '.customizer-repeater-icon-control input', function(e) {
            e.preventDefault();
            e.stopPropagation();

            // Hide any existing iconpicker
            if ($(this).data('iconpicker')) {
                $(this).iconpicker('hide');
                $(this).iconpicker('destroy');
            }

            return false;
        });

        // Prevent keyboard input on icon fields
        $(document).on('keydown keypress keyup', '.customizer-repeater-icon-control input', function(e) {
            e.preventDefault();
            return false;
        });

        // Remove green border styling on any focus/blur events
        $(document).on('focus blur', '.customizer-repeater-icon-control input', function(e) {
            $(this).css({
                'border-color': '#ddd',
                'box-shadow': 'none',
                'outline': 'none'
            });
        });
    }

    function createEnhancedIconPickerModal() {
        if ($('#pawfect-enhanced-icon-picker-modal').length) {
            return;
        }

        const modal = $(`
            <div id="pawfect-enhanced-icon-picker-modal" class="pawfect-icon-picker-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 999999; display: none; align-items: center; justify-content: center; backdrop-filter: blur(2px);">
                <div class="pawfect-icon-picker-content" style="background: #fff; border-radius: 12px; width: 90%; max-width: 700px; max-height: 85vh; overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.2);">
                    <div class="pawfect-icon-picker-header" style="padding: 24px 28px 20px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center; background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);">
                        <h3 style="font-size: 18px; font-weight: 600; margin: 0; color: #2c3e50; letter-spacing: -0.02em;">Choose an Icon</h3>
                        <button type="button" class="pawfect-icon-picker-close" style="background: none; border: none; font-size: 20px; cursor: pointer; color: #95a5a6; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: all 0.2s ease;" onmouseover="this.style.background='#f8f9fa'; this.style.color='#e74c3c';" onmouseout="this.style.background='none'; this.style.color='#95a5a6';">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>
                    <div class="pawfect-icon-picker-search" style="padding: 24px 28px; border-bottom: 1px solid #f0f0f0;">
                        <div style="position: relative;">
                            <input type="text" class="pawfect-icon-search-input" placeholder="Search icons..." style="width: 100%; padding: 14px 16px 14px 44px; border: 2px solid #e9ecef; border-radius: 8px; font-size: 14px; background: #f8f9fa; transition: all 0.2s ease; outline: none;" onfocus="this.style.borderColor='#3498db'; this.style.background='#fff';" onblur="this.style.borderColor='#e9ecef'; this.style.background='#f8f9fa';">
                            <span style="position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: #95a5a6; font-size: 16px;">🔍</span>
                        </div>
                    </div>
                    <div class="pawfect-icon-picker-tabs" style="display: flex; margin: 0 28px; border-radius: 8px; background: #f8f9fa; padding: 4px;">
                        <button type="button" class="pawfect-icon-picker-tab active" data-type="fontawesome" style="flex: 1; padding: 12px 20px; border: none; background: #fff; cursor: pointer; border-radius: 6px; color: #3498db; font-weight: 500; box-shadow: 0 2px 4px rgba(0,0,0,0.1); transition: all 0.2s ease;">FontAwesome</button>
                        <button type="button" class="pawfect-icon-picker-tab" data-type="phosphor" style="flex: 1; padding: 12px 20px; border: none; background: transparent; cursor: pointer; border-radius: 6px; color: #7f8c8d; font-weight: 500; transition: all 0.2s ease;" onmouseover="this.style.background='rgba(255,255,255,0.5)';" onmouseout="this.style.background='transparent';">Phosphor Icons</button>
                    </div>
                    <div class="pawfect-icon-picker-body" style="padding: 20px 28px 28px;">
                        <div class="pawfect-icon-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 16px; max-height: 340px; overflow-y: auto; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e9ecef;"></div>
                    </div>
                </div>
            </div>
        `);

        $('body').append(modal);

        // Bind events
        modal.on('click', '.pawfect-icon-picker-close', function() {
            modal.removeClass('active').hide();
        });

        modal.on('click', function(e) {
            if (e.target === this) {
                modal.removeClass('active').hide();
            }
        });

        modal.on('click', '.pawfect-icon-picker-tab', function(e) {
            e.preventDefault();
            const tab = $(this);
            const type = tab.data('type');

            modal.find('.pawfect-icon-picker-tab').removeClass('active').css({
                'background': 'transparent',
                'color': '#7f8c8d',
                'box-shadow': 'none'
            });

            tab.addClass('active').css({
                'background': '#fff',
                'color': '#3498db',
                'box-shadow': '0 2px 4px rgba(0,0,0,0.1)'
            });

            loadIconsInModal(type);
        });

        modal.on('input', '.pawfect-icon-search-input', function() {
            const searchTerm = $(this).val();
            const activeTab = modal.find('.pawfect-icon-picker-tab.active').data('type');
            loadIconsInModal(activeTab, searchTerm);
        });

        modal.on('click', '.pawfect-icon-item', function(e) {
            e.preventDefault();
            const iconClass = $(this).data('icon');
            const targetInput = modal.data('target-input');

            if (targetInput) {
                targetInput.val(iconClass);
                targetInput.trigger('change');
            }

            modal.removeClass('active').hide();
        });

        // Show modal when active
        modal.on('addClass', function() {
            if (modal.hasClass('active')) {
                modal.show().css('display', 'flex');
            }
        });
    }

    function loadIconsInModal(type, searchTerm = '') {
        const grid = $('.pawfect-icon-grid');
        const icons = type === 'phosphor' ? iconLibraries.phosphor : iconLibraries.fontAwesome;

        grid.empty();

        Object.keys(icons).forEach(function(iconClass) {
            const iconName = icons[iconClass];

            if (searchTerm && !iconName.toLowerCase().includes(searchTerm.toLowerCase()) &&
                !iconClass.toLowerCase().includes(searchTerm.toLowerCase())) {
                return;
            }

            const iconItem = $(`
                <div class="pawfect-icon-item" data-icon="${iconClass}" style="display: flex; flex-direction: column; align-items: center; padding: 16px 12px; background: #fff; border: 1px solid #e9ecef; border-radius: 8px; cursor: pointer; text-align: center; transition: all 0.2s ease; min-height: 80px; justify-content: center;">
                    <i class="${iconClass}" style="font-size: 24px; margin-bottom: 8px; color: #7f8c8d; min-width: 24px; min-height: 24px; display: flex; align-items: center; justify-content: center;"></i>
                    <span style="font-size: 9px; color: #95a5a6; font-weight: 500; line-height: 1.2; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; opacity: 0.8;">${iconName}</span>
                </div>
            `);

            // Add fallback for icons that don't load
            const iconElement = iconItem.find('i');
            setTimeout(function() {
                if (iconElement.width() === 0 || iconElement.height() === 0) {
                    // Icon didn't load, show text fallback
                    iconElement.text('⭐').css({
                        'font-family': 'Arial, sans-serif',
                        'font-style': 'normal',
                        'font-size': '18px'
                    });
                }
            }, 100);

            iconItem.on('mouseenter', function() {
                $(this).css({
                    'border-color': '#3498db',
                    'background': '#f8f9fa',
                    'transform': 'translateY(-2px)',
                    'box-shadow': '0 4px 12px rgba(52, 152, 219, 0.15)'
                });
                $(this).find('i').css({
                    'color': '#3498db',
                    'transform': 'scale(1.1)',
                    'font-size': '26px'
                });
                $(this).find('span').css({
                    'color': '#2c3e50',
                    'opacity': '1'
                });
            }).on('mouseleave', function() {
                $(this).css({
                    'border-color': '#e9ecef',
                    'background': '#fff',
                    'transform': 'translateY(0)',
                    'box-shadow': 'none'
                });
                $(this).find('i').css({
                    'color': '#7f8c8d',
                    'transform': 'scale(1)',
                    'font-size': '24px'
                });
                $(this).find('span').css({
                    'color': '#95a5a6',
                    'opacity': '0.8'
                });
            });

            grid.append(iconItem);
        });
    }

    // Enhanced icon picker is now integrated directly into input fields
    // No separate buttons needed - clicking the input field opens the modal



})(jQuery);

/******************************************************************
*** [UPDATED] Initialize draggable when the element is visible ***
*******************************************************************/
function pawfect_initialize_draggable(context) {
    'use strict';

    // Find the draggable wrapper within the provided context (the repeater box content)
    const $wrapper = context.find('.pawfect-draggable-wrapper');

    // Only run this logic if a wrapper is found AND it hasn't been initialized yet
    if ($wrapper.length > 0 && !$wrapper.hasClass('draggable-initialized')) {

        const $dot = $wrapper.find('.pawfect-draggable-dot');

        if ($dot.length > 0) {
            // Apply stored position from data attributes or default
            const savedTop = $dot.attr('data-top') || '50%';
            const savedLeft = $dot.attr('data-left') || '50%';
            $dot.css({ top: savedTop, left: savedLeft });

            // Initialize jQuery UI Draggable with enhanced containment
            $dot.draggable({
                containment: 'parent',
                scroll: false,
                cursor: 'grabbing',
                opacity: 0.8,
                distance: 5,
                stop: function (event, ui) {
                    // Calculate position as percentage, ensuring it stays within bounds
                    const parentWidth = $wrapper.width();
                    const parentHeight = $wrapper.height();
                    const dotWidth = $dot.outerWidth();
                    const dotHeight = $dot.outerHeight();

                    // Calculate percentage position with boundary constraints
                    let topPercent = Math.max(0, Math.min(100, (ui.position.top / (parentHeight - dotHeight)) * 100));
                    let leftPercent = Math.max(0, Math.min(100, (ui.position.left / (parentWidth - dotWidth)) * 100));

                    const top = topPercent.toFixed(1) + '%';
                    const left = leftPercent.toFixed(1) + '%';

                    // Update the data attributes for persistence
                    $dot.attr('data-top', top).attr('data-left', left);

                    // Find the closest repeater item container
                    const $repeaterItem = $wrapper.closest('.customizer-repeater-general-control-repeater-container');

                    // Update the hidden input fields
                    $repeaterItem.find('.customizer-repeater-text-two-control').val(top);
                    $repeaterItem.find('.customizer-repeater-text-three-control').val(left);

                    // Refresh all repeater values to save in the Customizer
                    pawfect_customizer_repeater_refresh_general_control_values();
                }
            });

            // Add a class to mark this as initialized so we don't run the code again
            $wrapper.addClass('draggable-initialized');
        }
    }
}


function pawfect_media_upload(button_class) {
    'use strict';
    jQuery('body').on('click', button_class, function () {
        var button_id = '#' + jQuery(this).attr('id');
        var display_field = jQuery(this).parent().children('input:text');
        var preview_container = jQuery(this).parent().find('.customizer-repeater-image-preview');
        var _custom_media = true;

        wp.media.editor.send.attachment = function (props, attachment) {

            if (_custom_media) {
                if (typeof display_field !== 'undefined') {
                    var image_url = '';
                    // Always use the largest available size for better quality
                    if (attachment.sizes && attachment.sizes.full) {
                        image_url = attachment.sizes.full.url;
                    } else if (attachment.sizes && attachment.sizes.large) {
                        image_url = attachment.sizes.large.url;
                    } else if (attachment.url) {
                        image_url = attachment.url;
                    } else {
                        // Fallback to original size selection logic
                        switch (props.size) {
                            case 'full':
                                image_url = attachment.sizes.full.url;
                                break;
                            case 'medium':
                                image_url = attachment.sizes.medium.url;
                                break;
                            case 'thumbnail':
                                image_url = attachment.sizes.thumbnail.url;
                                break;
                            default:
                                image_url = attachment.url;
                        }
                    }

                    display_field.val(image_url);
                    display_field.trigger('change');

                    // Update image preview
                    pawfect_update_image_preview(preview_container, image_url);
                }
                _custom_media = false;
            } else {
                return wp.media.editor.send.attachment(button_id, [props, attachment]);
            }
        };
        wp.media.editor.open(button_class);
        window.send_to_editor = function (html) {

        };
        return false;
    });
}

// Function to update image preview
function pawfect_update_image_preview(container, image_url) {
    'use strict';
    if (container.length > 0) {
        if (image_url && image_url !== '') {
            // Show image preview
            container.html(
                '<img src="' + image_url + '" alt="Preview" style="max-width: 100%; height: 60px; object-fit: cover; border-radius: 4px; border: 1px solid #ddd; display: block;" />' +
                '<button type="button" class="button button-link customizer-repeater-remove-image" style="color: #dc3232; text-decoration: none; font-size: 12px; margin-top: 5px;">Remove Image</button>'
            );
        } else {
            // Show placeholder
            container.html(
                '<div class="customizer-repeater-image-placeholder" style="width: 100%; height: 60px; background: #f7f7f7; border: 2px dashed #ddd; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #666; font-size: 12px;">No image selected</div>'
            );
        }
    }
}

/********************************************
 *** Generate unique id ***
 *********************************************/
function pawfect_customizer_repeater_uniqid(prefix, more_entropy) {
    'use strict';
    if (typeof prefix === 'undefined') {
        prefix = '';
    }

    var retId;
    var php_js;
    var formatSeed = function (seed, reqWidth) {
        seed = parseInt(seed, 10)
            .toString(16); // to hex str
        if (reqWidth < seed.length) { // so long we split
            return seed.slice(seed.length - reqWidth);
        }
        if (reqWidth > seed.length) { // so short we pad
            return new Array(1 + (reqWidth - seed.length))
                .join('0') + seed;
        }
        return seed;
    };

    // BEGIN REDUNDANT
    if (!php_js) {
        php_js = {};
    }
    // END REDUNDANT
    if (!php_js.uniqidSeed) { // init seed with big random int
        php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
    }
    php_js.uniqidSeed++;

    retId = prefix; // start with prefix, add current milliseconds hex string
    retId += formatSeed(parseInt(new Date()
        .getTime() / 1000, 10), 8);
    retId += formatSeed(php_js.uniqidSeed, 5); // add seed hex string
    if (more_entropy) {
        // for more entropy we add a float lower to 10
        retId += (Math.random() * 10)
            .toFixed(8)
            .toString();
    }

    return retId;
}


/********************************************
 *** General Repeater ***
 *********************************************/
function pawfect_customizer_repeater_refresh_social_icons(th) {
    'use strict';
    var icons_repeater_values = [];
    th.find('.customizer-repeater-social-repeater-container').each(function () {
        var icon = jQuery(this).find('.icp').val();
        var link = jQuery(this).find('.customizer-repeater-social-repeater-link').val();
        var id = jQuery(this).find('.customizer-repeater-social-repeater-id').val();

        if (!id) {
            id = 'customizer-repeater-social-repeater-' + pawfect_customizer_repeater_uniqid();
            jQuery(this).find('.customizer-repeater-social-repeater-id').val(id);
        }

        if (icon !== '' && link !== '') {
            icons_repeater_values.push({
                'icon': icon,
                'link': link,
                'id': id
            });
        }
    });

    th.find('.social-repeater-socials-repeater-colector').val(JSON.stringify(icons_repeater_values));
    pawfect_customizer_repeater_refresh_general_control_values();
}


function pawfect_customizer_repeater_refresh_general_control_values() {

    'use strict';
    jQuery('.customizer-repeater-general-control-repeater').each(function () {
        var values = [];
        var th = jQuery(this);
        th.find('.customizer-repeater-general-control-repeater-container').each(function () {

            var icon_value = jQuery(this).find('.icp').val();
            var text = jQuery(this).find('.customizer-repeater-text-control').val();
            var button_text = jQuery(this).find('.customizer-repeater-button-text-control').val();
            var link = jQuery(this).find('.customizer-repeater-link-control').val();
            var color = jQuery(this).find('.customizer-repeater-color-control').val();
            var designation = jQuery(this).find('.customizer-repeater-designation-control').val();
             var product_select = jQuery(this).find('.customizer-repeater-product-select').val();
            var open_new_tab = jQuery(this).find('.customizer-repeater-checkbox').val();
            var image_url = jQuery(this).find('.custom-media-url').val();
            var svg_code = jQuery(this).find('.customizer-repeater-svg-code').val();
            var choice = jQuery(this).find('.customizer-repeater-image-choice').val();
            var title = jQuery(this).find('.customizer-repeater-title-control').val();
            var subtitle = jQuery(this).find('.customizer-repeater-subtitle-control').val();
            var slide_format = jQuery(this).find('.customizer-repeater-slide-format').val();
            var content_format = jQuery(this).find('.customizer-repeater-slide-content-format').val();
            var rating_control = jQuery(this).find('.customizer-repeater-rating-control').val();
            var video_url = jQuery(this).find('.customizer-repeater-video-url-control').val();
            var id = jQuery(this).find('.social-repeater-box-id').val();
            if (!id) {
                id = 'social-repeater-' + pawfect_customizer_repeater_uniqid();
                jQuery(this).find('.social-repeater-box-id').val(id);
            }
            var social_repeater = jQuery(this).find('.social-repeater-socials-repeater-colector').val();
            var shortcode = jQuery(this).find('.customizer-repeater-shortcode-control').val();

            var text_two = jQuery(this).find('.customizer-repeater-text-two-control').val();    // Top
            var text_three = jQuery(this).find('.customizer-repeater-text-three-control').val(); // Left
            var position_preset = jQuery(this).find('.customizer-repeater-position-select-control').val(); // Preset
             var product_select  = jQuery(this).find('.customizer-repeater-product-select').val(); // Preset

            if (text !== '' || image_url !== '' || svg_code !== '' || title !== '' || subtitle !== '' || icon_value !== '' || link !== '' || designation !== '' || open_new_tab !== '' || choice !== '' || social_repeater !== '' || shortcode !== '' || position_preset !== '' || product_select !== '' || text_two !== '' || text_three !== '' || color !== '' || button_text !== '' || slide_format !== '' || content_format !== '' || rating_control !== '' || video_url !== '') {
                values.push({
                    'icon_value': (choice === 'customizer_repeater_none' ? '' : icon_value),
                    'color': color,
                    'text': pawfect_escapeHtml(text),
                    'link': link,
                    'image_url': (choice === 'customizer_repeater_none' ? '' : image_url),
                    'svg_code': svg_code,
                    'choice': choice,
                    'title': pawfect_escapeHtml(title),
                    'subtitle': pawfect_escapeHtml(subtitle),
                    'social_repeater': pawfect_escapeHtml(social_repeater),
                    'id': id,
                    'shortcode': pawfect_escapeHtml(shortcode),
                    'text_two': pawfect_escapeHtml(text_two),
                    'text_three': pawfect_escapeHtml(text_three),
                    'position_preset': pawfect_escapeHtml(position_preset),
                     'product_select': pawfect_escapeHtml(product_select),
                    
                    'button_text': button_text,
                    'designation': designation,
                    'open_new_tab': open_new_tab,
                    'slide_format': slide_format,
                    'content_format': content_format,
                    'rating_control': rating_control,
                    'video_url': video_url
                });
            }

        });
        th.find('.customizer-repeater-colector').val(JSON.stringify(values));
        th.find('.customizer-repeater-colector').trigger('change');
    });
}


jQuery(document).ready(function () {
    'use strict';

    var theme_conrols = jQuery('#customize-theme-controls');

    // ** [UPDATED] Initialize draggable controls for any repeaters that are already visible on page load **
    jQuery('.customizer-repeater-box-content-hidden').filter(':visible').each(function () {
        pawfect_initialize_draggable(jQuery(this));
    });

    // ADDED: This block runs on page load, finds every media dropdown, and triggers the 'change' event.
    // This ensures the correct field (Icon, Image, or SVG) is showing when you first load the Customizer.
    setTimeout(function () {

        theme_conrols.find('.customizer-repeater-image-choice').each(function () {
            jQuery(this).trigger('change');
        });

        // Initialize image previews for existing data
        theme_conrols.find('.custom-media-url').each(function () {
            var image_url = jQuery(this).val();
            var preview_container = jQuery(this).parent().find('.customizer-repeater-image-preview');
            if (image_url && preview_container.length > 0) {
                pawfect_update_image_preview(preview_container, image_url);
            }
        });
    }, 200);
    // ** [UPDATED] Initialize draggable when a repeater box is opened **
    theme_conrols.on('click', '.customizer-repeater-customize-control-title', function () {
        jQuery(this).next().slideToggle('medium', function () {
            if (jQuery(this).is(':visible')) {
                jQuery(this).prev().addClass('repeater-expanded');
                jQuery(this).css('display', 'block');
                // Initialize the draggable control now that this section is visible
                pawfect_initialize_draggable(jQuery(this));
            } else {
                jQuery(this).prev().removeClass('repeater-expanded');
            }
        });
    });

    theme_conrols.on('change', '.icp', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
        return false;
    });

    theme_conrols.on('change', '.customizer-repeater-slide-format', function () {
        if (jQuery(this).val() === 'customizer_repeater_slide_format_video') {
            jQuery(this).parent().parent().find('.customizer-repeater-video-url-control').show();
            jQuery(this).parent().parent().find('.Video').show();
        } else {
            jQuery(this).parent().parent().find('.customizer-repeater-video-url-control').hide();
            jQuery(this).parent().parent().find('.Video').hide();
        }
        pawfect_customizer_repeater_refresh_general_control_values();
        return false;

    });

    theme_conrols.on('change', '.customizer-repeater-rating-control', function () {
        if (jQuery(this).val() === 'customizer_repeater_rating_control_five') {
            jQuery(this).parent().parent().find('.customizer-repeater-rating-control').show();
            jQuery(this).parent().parent().find('.Video').show();
        }
        pawfect_customizer_repeater_refresh_general_control_values();
        return false;

    });

    // Content 
    theme_conrols.on('change', '.customizer-repeater-slide-content-format', function () {
        if (jQuery(this).val() === 'left') {
            jQuery(this).parent().parent().find('.customizer-repeater-slide-content-format').show();
            //jQuery(this).parent().parent().find('.Video').show();
        }
        pawfect_customizer_repeater_refresh_general_control_values();
        return false;

    });

    // UPDATED: This block now handles all 4 cases (Icon, Image, SVG, None) and makes sure to hide the other fields.
    theme_conrols.on('change', '.customizer-repeater-image-choice', function () {
        var container = jQuery(this).parent().parent();
        var choice = jQuery(this).val();

        if (choice === 'customizer_repeater_image') {
            container.find('.social-repeater-general-control-icon').hide();
            container.find('.customizer-repeater-svg-control').hide();
            container.find('.customizer-repeater-image-control').show();
        } else if (choice === 'customizer_repeater_icon') {
            container.find('.customizer-repeater-image-control').hide();
            container.find('.customizer-repeater-svg-control').hide();
            container.find('.social-repeater-general-control-icon').show();
        } else if (choice === 'customizer_repeater_svg') {
            container.find('.social-repeater-general-control-icon').hide();
            container.find('.customizer-repeater-image-control').hide();
            container.find('.customizer-repeater-svg-control').show();
        } else if (choice === 'customizer_repeater_none') {
            container.find('.social-repeater-general-control-icon').hide();
            container.find('.customizer-repeater-image-control').hide();
            container.find('.customizer-repeater-svg-control').hide();
        }

        pawfect_customizer_repeater_refresh_general_control_values();
        return false;
    });

    pawfect_media_upload('.customizer-repeater-custom-media-button');

    // Enhanced: Handle image URL changes and update preview
    jQuery(document).on('change keyup', '.custom-media-url', function () {
        var image_url = jQuery(this).val();
        var preview_container = jQuery(this).parent().find('.customizer-repeater-image-preview');
        pawfect_update_image_preview(preview_container, image_url);
        pawfect_customizer_repeater_refresh_general_control_values();
        return false;
    });

    // Handle SVG textarea changes
    jQuery(document).on('change keyup', '.customizer-repeater-svg-code', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
        return false;
    });

    // Handle remove image button
    jQuery(document).on('click', '.customizer-repeater-remove-image', function () {
        var image_control = jQuery(this).closest('.customizer-repeater-image-control');
        var input_field = image_control.find('.custom-media-url');
        var preview_container = image_control.find('.customizer-repeater-image-preview');

        // Clear the input field
        input_field.val('').trigger('change');

        // Update preview to show placeholder
        pawfect_update_image_preview(preview_container, '');

        return false;
    });


    var color_options = {
        change: function (event, ui) {
            pawfect_customizer_repeater_refresh_general_control_values();
        }
    };

    /**
     * This adds a new box to repeater
     */
    theme_conrols.on('click', '.customizer-repeater-new-field', function () {
        var th = jQuery(this).parent();
        var id = 'customizer-repeater-' + pawfect_customizer_repeater_uniqid();
        if (typeof th !== 'undefined') {
            // ** Get the pristine HTML of the original dot before we clone the container **
            //const originalDotHTML = th.find('.customizer-repeater-general-control-repeater-container:first .pawfect-draggable-dot')[0].outerHTML;
            let originalDotHTML = '';
            const firstDot = th.find('.customizer-repeater-general-control-repeater-container:first .pawfect-draggable-dot')[0];
            if (firstDot) {
                originalDotHTML = firstDot.outerHTML;
            }


            /* Clone the first box*/
            var field = th.find('.customizer-repeater-general-control-repeater-container:first').clone(true, true);

            if (typeof field !== 'undefined') {

                // ** Replace the problematic cloned dot with the pristine copy **
                if (originalDotHTML) {
                    field.find('.pawfect-draggable-dot').replaceWith(originalDotHTML);
                }

                /*Set the default value for choice between image and icon to icon*/
                field.find('.customizer-repeater-image-choice').val('customizer_repeater_icon');

                /*Show icon selector*/
                field.find('.social-repeater-general-control-icon').show();

                // Set unique ID to hidden input used for tracking
                field.find('.social-repeater-box-id').val(id);

                // Remove the 'initialized' flag from the clone so it can be re-initialized
                field.find('.pawfect-draggable-wrapper').removeClass('draggable-initialized');

                /*Hide image selector*/
                if (field.find('.social-repeater-general-control-icon').length > 0) {
                    field.find('.customizer-repeater-image-control').hide();
                    field.find('.customizer-repeater-svg-control').hide(); // ADDED
                }

                /*Show delete box button because it's not the first box*/
                field.find('.social-repeater-general-control-remove-field').show();

                /* Empty control for icon */
                field.find('.input-group-addon').find('.fa').attr('class', 'fa');


                /*Remove all repeater fields except first one*/

                field.find('.customizer-repeater-social-repeater').find('.customizer-repeater-social-repeater-container').not(':first').remove();
                field.find('.customizer-repeater-social-repeater-link').val('');
                field.find('.social-repeater-socials-repeater-colector').val('');

                /*Remove value from icon field*/
                field.find('.icp').val('');

                /*Remove value from text field*/
                field.find('.customizer-repeater-text-control').val('');

                /*Remove value from button text field*/
                field.find('.customizer-repeater-button-text-control').val('');

                field.find('.customizer-repeater-video-url-control').val('');

                /*Remove value from button rating control*/
                field.find('.customizer-repeater-rating-control').val('');

                /*Remove value from designation  text field*/
                field.find('.customizer-repeater-designation-control').val('');

                /*Set the default value in slide format*/
                field.find('.customizer-repeater-slide-format').val('customizer_repeater_slide_format_standard');

                /*Set the default value in slide format*/
                field.find('.customizer-repeater-slide-content-format').val('left');

                /*Set the default value in slide format*/
                field.find('.customizer-repeater-rating-control').val('customizer_repeater_rating_control_five');

                /*Remove value from link field*/
                field.find('.customizer-repeater-link-control').val('');

                /*Set box id*/
                field.find('.social-repeater-box-id').val(id);

                /*Remove value from media field*/
                field.find('.custom-media-url').val('');
                field.find('.customizer-repeater-svg-code').val(''); // ADDED

                /*Remove value from title field*/
                field.find('.customizer-repeater-title-control').val('');

                /*Remove value from color field*/
                field.find('.wp-picker-container').replaceWith('<input type="text" class="customizer-repeater-color-control ' + id + '">');
                field.find('.customize-control-notifications-container').remove();
                field.find('.customizer-repeater-color-control').wpColorPicker(color_options);

                /*Remove value from subtitle field*/
                field.find('.customizer-repeater-subtitle-control').val('');

                /*Remove value from shortcode field*/
                field.find('.customizer-repeater-shortcode-control').val('');

                /*Reset position fields*/
                field.find('.customizer-repeater-text-two-control').val('');
                field.find('.customizer-repeater-text-three-control').val('');
                field.find('.customizer-repeater-position-select-control').val('');
                 field.find('.customizer-repeater-product-select').val('');

                // Reset draggable dot's position and data for the new clone
                field.find('.pawfect-draggable-dot')
                    .css({ top: '50%', left: '50%' })
                    .attr('data-top', '50%')
                    .attr('data-left', '50%');

                /*Set the default value in checkbox*/
                field.find('.customizer-repeater-checkbox').val('');

                /*Append new box*/
                th.find('.customizer-repeater-general-control-repeater-container:first').parent().append(field);

                // Check if the new box is already visible and initialize it if so.
                var newBoxContent = field.find('.customizer-repeater-box-content-hidden');
                if (newBoxContent.is(':visible')) {
                    pawfect_initialize_draggable(newBoxContent);
                }

                /*Refresh values*/
                pawfect_customizer_repeater_refresh_general_control_values();
            }
        }
        return false;
    });

    theme_conrols.on('click', '.social-repeater-general-control-remove-field', function () {
        if (typeof jQuery(this).parent() !== 'undefined') {
            jQuery(this).parent().hide(500, function () {
                jQuery(this).parent().remove();
                pawfect_customizer_repeater_refresh_general_control_values();
            });
        }
        return false;
    });


    theme_conrols.on('keyup', '.customizer-repeater-title-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    jQuery('.customizer-repeater-color-control').wpColorPicker(color_options);

    theme_conrols.on('keyup', '.customizer-repeater-subtitle-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('keyup', '.customizer-repeater-shortcode-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('keyup', '.customizer-repeater-text-two-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('keyup', '.customizer-repeater-text-three-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('change', '.customizer-repeater-position-select-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });


      theme_conrols.on('change', '.customizer-repeater-product-select', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });



    theme_conrols.on('keyup', '.customizer-repeater-video-url-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('keyup', '.customizer-repeater-slide-content-format', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('keyup', '.customizer-repeater-text-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('keyup', '.customizer-repeater-button-text-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    })

    theme_conrols.on('keyup', '.customizer-repeater-link-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('keyup', '.customizer-repeater-designation-control', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    theme_conrols.on('change', '.customizer-repeater-checkbox', function () {
        pawfect_customizer_repeater_refresh_general_control_values();
    });

    /*Drag and drop to change icons order*/
    jQuery('.customizer-repeater-general-control-droppable').sortable({
        axis: 'y',
        update: function () {
            pawfect_customizer_repeater_refresh_general_control_values();
        }
    });

    // This handler syncs the manual input fields with the draggable dot position
    jQuery(document).on('keyup change', '.customizer-repeater-text-two-control, .customizer-repeater-text-three-control', function () {
        const container = jQuery(this).closest('.customizer-repeater-general-control-repeater-container');
        const dot = container.find('.pawfect-draggable-dot');
        const top = container.find('.customizer-repeater-text-two-control').val();
        const left = container.find('.customizer-repeater-text-three-control').val();
        dot.css({ top, left });
    });


    /*----------------- Socials Repeater ---------------------*/
    theme_conrols.on('click', '.social-repeater-add-social-item', function (event) {
        event.preventDefault();
        var th = jQuery(this).parent();
        var id = 'customizer-repeater-social-repeater-' + pawfect_customizer_repeater_uniqid();
        if (typeof th !== 'undefined') {
            var field = th.find('.customizer-repeater-social-repeater-container:first').clone(true, true);
            if (typeof field !== 'undefined') {
                field.find('.icp').val('');
                field.find('.input-group-addon').find('.fa').attr('class', 'fa');
                field.find('.social-repeater-remove-social-item').show();
                field.find('.customizer-repeater-social-repeater-link').val('');
                field.find('.customizer-repeater-social-repeater-id').val(id);
                th.find('.customizer-repeater-social-repeater-container:first').parent().append(field);
            }
        }
        return false;
    });

    theme_conrols.on('click', '.social-repeater-remove-social-item', function (event) {
        event.preventDefault();
        var th = jQuery(this).parent();
        var repeater = jQuery(this).parent().parent();
        th.remove();
        pawfect_customizer_repeater_refresh_social_icons(repeater);
        return false;
    });

    theme_conrols.on('keyup', '.customizer-repeater-social-repeater-link', function (event) {
        event.preventDefault();
        var repeater = jQuery(this).parent().parent();
        pawfect_customizer_repeater_refresh_social_icons(repeater);
        return false;
    });

    theme_conrols.on('change', '.customizer-repeater-social-repeater-container .icp', function (event) {
        event.preventDefault();
        var repeater = jQuery(this).parent().parent().parent();
        pawfect_customizer_repeater_refresh_social_icons(repeater);
        return false;
    });

});

var entityMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    '\'': '&#39;',
    '/': '&#x2F;'
};

function pawfect_escapeHtml(string) {
    'use strict';
    //noinspection JSUnresolvedFunction
    string = String(string).replace(new RegExp('\r?\n', 'g'), '<br />');
    string = String(string).replace(/\\/g, '&#92;');
    return String(string).replace(/[&<>"'\/]/g, function (s) {
        return entityMap[s];
    });
}


