/**
 * Enhanced Icon Picker for Social Media Repeater
 * Adds Phosphor Icons support and visual icon picker to existing pawfect_Repeater
 *
 * @package Pawfect
 * @since 1.0.0
 */


(function ($) {
    'use strict';


    // Icon libraries data
    const iconLibraries = {
        fontAwesome: {
            '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',
            'fab fa-xing': 'Xing',
            'fab fa-yelp': 'Yelp',
            'fab fa-foursquare': 'Foursquare',
            'fab fa-tripadvisor': 'TripAdvisor'
        },
        phosphor: {
            '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',
            'ph ph-envelope': 'Email',
            'ph ph-phone': 'Phone',
            'ph ph-globe': 'Website',
            'ph ph-rss': 'RSS',
            'ph ph-share-network': 'Share'
        }
    };

    // Initialize enhanced icon picker
    $(document).ready(function () {
        initializeEnhancedIconPicker();
        createIconPickerModal();
        watchForRepeaterChanges();

        // Debug the repeater structure
        setTimeout(function () {
            debugRepeaterStructure();

            // Also debug service content specifically
            const serviceControl = $('#customize-control-pawfect_service_content');
            if (serviceControl.length > 0) {
                const icpInputs = serviceControl.find('.icp');
                icpInputs.each(function (index) {
                });
            }
        }, 1000);

    });

    // Also try when window loads
    $(window).on('load', function () {
    });

    // Watch for customizer changes and new repeater items
    $(document).on('DOMNodeInserted', function (e) {
        if ($(e.target).hasClass('customizer-repeater-general-control-repeater-container') ||
            $(e.target).find('.customizer-repeater-general-control-repeater-container').length) {
        }
    });

    /**
     * Initialize enhanced icon picker for social media repeater
     */
    function initializeEnhancedIconPicker() {

        // Enable the advanced icon picker with dual library support
        $(document).on('click', '#customize-control-pawfect_social_media_icons .icp-auto', function (e) {
            e.preventDefault();
            e.stopPropagation();

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


            // Store reference to the input for later use
            modal.data('target-input', iconInput);

            // Show modal
            modal.addClass('active');

            // Force modal to show with inline styles
            modal.css({
                'display': 'flex',
                'visibility': 'visible',
                'opacity': '1'
            });


            // Focus on search input
            modal.find('.pawfect-icon-search-input').focus();

            // Load icons for the active tab
            const activeTab = modal.find('.pawfect-icon-picker-tab.active').data('type') || 'fontawesome';
            loadIcons(activeTab);
        });

        // Enable clicks on the icon addon button (the icon preview next to input)
        $(document).on('click', '#customize-control-pawfect_social_media_icons .input-group-addon', function (e) {
            e.preventDefault();
            e.stopPropagation();

            // Find the associated input field
            const iconInput = $(this).siblings('.icp-auto');
            const modal = $('#pawfect-enhanced-icon-picker-modal');


            if (iconInput.length > 0) {
                // Store reference to the input for later use and mark as social context
                modal.data('target-input', iconInput);
                modal.data('context', 'social');

                // Show modal
                modal.addClass('active');

                // Force modal to show with inline styles
                modal.css({
                    'display': 'flex',
                    'visibility': 'visible',
                    'opacity': '1'
                });

                // Focus on search input
                modal.find('.pawfect-icon-search-input').focus();

                // Load icons for the active tab
                const activeTab = modal.find('.pawfect-icon-picker-tab.active').data('type') || 'fontawesome';
                loadIcons(activeTab);
            }
        });

        // Enable the advanced icon picker for Service/Why Choose Us section specifically
        $(document).on('click', '#customize-control-pawfect_service_content .icp, #customize-control-pawfect_service_content .icp-auto, #customize-control-pawfect_service_content .input-group-addon', function (e) {
            e.preventDefault();
            e.stopPropagation();

            const $input = $(this).hasClass('icp') ? $(this) : $(this).siblings('input.icp');
            const modal = $('#pawfect-enhanced-icon-picker-modal');


            // Store reference to the input for later use and mark as service context
            modal.data('target-input', $input);
            modal.data('context', 'service');

            // Show modal
            modal.addClass('active');

            // Force modal to show with inline styles
            modal.css({
                'display': 'flex',
                'visibility': 'visible',
                'opacity': '1'
            });

            // Focus on search input
            modal.find('.pawfect-icon-search-input').focus();

            // Load service-specific icons for the active tab
            const activeTab = modal.find('.pawfect-icon-picker-tab.active').data('type') || 'fontawesome';
            loadIcons(activeTab, 'service');

        });

        // Enable the advanced icon picker for ALL other repeater controls (fallback)
        $(document).on('click', '.icp-container input.icp:not(#customize-control-pawfect_social_media_icons .icp):not(#customize-control-pawfect_service_content .icp), .icp-container .input-group-addon:not(#customize-control-pawfect_social_media_icons .input-group-addon):not(#customize-control-pawfect_service_content .input-group-addon)', function (e) {
            e.preventDefault();
            e.stopPropagation();

            const $input = $(this).hasClass('icp') ? $(this) : $(this).siblings('input.icp');
            const modal = $('#pawfect-enhanced-icon-picker-modal');
            const controlId = $input.closest('.customize-control').attr('id');


            // Store reference to the input for later use and mark as general context
            modal.data('target-input', $input);
            modal.data('context', 'general');

            // Show modal
            modal.addClass('active');

            // Force modal to show with inline styles
            modal.css({
                'display': 'flex',
                'visibility': 'visible',
                'opacity': '1'
            });

            // Focus on search input
            modal.find('.pawfect-icon-search-input').focus();

            // Load icons for the active tab
            const activeTab = modal.find('.pawfect-icon-picker-tab.active').data('type') || 'fontawesome';
            loadIcons(activeTab);

        });

        // Prevent the old FontAwesome iconpicker from showing for all repeater controls
        $(document).on('iconpickerShow iconpickerCreate', '.icp-container input.icp', function (e) {
            e.preventDefault();
            e.stopPropagation();

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

            return false;
        });

        // Also prevent the old iconpicker from initializing on service content
        $(document).on('focus click', '#customize-control-pawfect_service_content .icp', function (e) {

            // Prevent any iconpicker initialization
            if ($(this).data('iconpicker')) {
                $(this).iconpicker('destroy');
            }

            // Remove any iconpicker classes
            $(this).removeClass('iconpicker-element');
        });
    }

    /**
     * Create enhanced icon picker modal
     */
    function createIconPickerModal() {
        if ($('#pawfect-enhanced-icon-picker-modal').length) {
            return;
        }


        const modal = $(`
            <div id="pawfect-enhanced-icon-picker-modal" class="pawfect-icon-picker-modal">
                <div class="pawfect-icon-picker-content">
                    <div class="pawfect-icon-picker-header">
                        <h3 class="pawfect-icon-picker-title">Select Social Media Icon</h3>
                        <button type="button" class="pawfect-icon-picker-close">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>
                    <div class="pawfect-icon-picker-search">
                        <input type="text" class="pawfect-icon-search-input" placeholder="Search icons...">
                    </div>
                    <div class="pawfect-icon-picker-tabs">
                        <button type="button" class="pawfect-icon-picker-tab active" data-type="fontawesome">
                            Font Awesome
                        </button>
                        <button type="button" class="pawfect-icon-picker-tab" data-type="phosphor">
                            Phosphor Icons
                        </button>
                    </div>
                    <div class="pawfect-icon-picker-body">
                        <div class="pawfect-icon-grid"></div>
                    </div>
                </div>
            </div>
        `);

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

        // Bind modal events
        modal.on('click', '.pawfect-icon-picker-close', closeIconPicker);
        modal.on('click', function (e) {
            if (e.target === this) {
                closeIconPicker();
            }
        });
        modal.on('click', '.pawfect-icon-picker-tab', handleTabSwitch);
        modal.on('input', '.pawfect-icon-search-input', handleIconSearch);
        modal.on('click', '.pawfect-icon-item', handleIconSelect);

        // ESC key to close
        $(document).on('keydown', function (e) {
            if (e.keyCode === 27 && modal.hasClass('active')) {
                closeIconPicker();
            }
        });
    }

    /**
     * Close icon picker modal
     */
    function closeIconPicker() {
        $('#pawfect-enhanced-icon-picker-modal').removeClass('active');
    }

    /**
     * Handle tab switch
     */
    function handleTabSwitch(e) {
        e.preventDefault();

        const tab = $(this);
        const modal = tab.closest('.pawfect-icon-picker-modal');
        const type = tab.data('type');
        const context = modal.data('context') || '';

        // Update active tab
        modal.find('.pawfect-icon-picker-tab').removeClass('active');
        tab.addClass('active');

        // Load icons for the selected type with context
        loadIcons(type, '', context);
    }

    /**
     * Load icons for the specified type
     */
    function loadIcons(type, searchTerm = '', context = '') {
        const grid = $('.pawfect-icon-grid');
        let icons = type === 'phosphor' ? iconLibraries.phosphor : iconLibraries.fontAwesome;

        // If context is service, show service-specific icons first
        if (context === 'service' && type === 'fontawesome') {
            const serviceIcons = {
                // 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'
            };

            // Merge service icons with all icons, prioritizing service icons
            icons = { ...serviceIcons, ...icons };
        }

        grid.empty();

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

            // Filter by search term
            if (searchTerm && !iconName.toLowerCase().includes(searchTerm.toLowerCase()) &&
                !iconClass.toLowerCase().includes(searchTerm.toLowerCase())) {
                return;
            }

            const iconItem = $(`
                <div class="pawfect-icon-item" data-icon="${iconClass}" data-type="${type}">
                    <i class="${iconClass}"></i>
                    <span>${iconName}</span>
                </div>
            `);

            grid.append(iconItem);
        });
    }

    /**
     * Handle icon search
     */
    function handleIconSearch() {
        const searchTerm = $(this).val();
        const modal = $(this).closest('.pawfect-icon-picker-modal');
        const activeTab = $('.pawfect-icon-picker-tab.active').data('type');
        const context = modal.data('context') || '';
        loadIcons(activeTab, searchTerm, context);
    }

    /**
     * Handle icon selection
     */
    function handleIconSelect(e) {
        e.preventDefault();

        const iconItem = $(this);
        const modal = $('#pawfect-enhanced-icon-picker-modal');
        const targetInput = modal.data('target-input');
        const iconClass = iconItem.data('icon');
        const iconName = iconItem.find('span').text();


        if (targetInput && targetInput.length) {

            // Update the input value
            targetInput.val(iconClass);
            targetInput.attr('value', iconClass);

            // Trigger change event to notify customizer
            targetInput.trigger('change');

            // Determine the type of repeater control and refresh accordingly
            const repeaterContainer = targetInput.closest('.customizer-repeater-general-control-repeater-container');
            const controlId = targetInput.closest('.customize-control').attr('id');


            // For social media icons, use the specific refresh function
            if (controlId && controlId.includes('social_media_icons') && repeaterContainer.length > 0 && typeof pawfect_customizer_repeater_refresh_social_icons === 'function') {
                pawfect_customizer_repeater_refresh_social_icons(repeaterContainer);

                // Trigger customizer preview refresh for selective refresh
                if (typeof wp !== 'undefined' && wp.customize && wp.customize.preview) {
                    wp.customize.preview.send('refresh-partial', 'pawfect_social_media_icons');
                }
            }

            // For service content, trigger selective refresh
            if (controlId && controlId.includes('service_content')) {
                if (typeof wp !== 'undefined' && wp.customize && wp.customize.preview) {
                    wp.customize.preview.send('refresh-partial', 'pawfect_service_content');
                }
            }

            // Always call the general refresh function to update all repeater controls
            if (typeof pawfect_customizer_repeater_refresh_general_control_values === 'function') {
                pawfect_customizer_repeater_refresh_general_control_values();
            }

            // Update the icon preview in the input-group-addon (the existing repeater structure)
            const iconPreview = targetInput.siblings('.input-group-addon');
            if (iconPreview.length > 0) {
                // iconClass already includes the full class (e.g., 'fab fa-behance')
                const iconElement = '<i class="' + iconClass + '"></i>';
                iconPreview.empty().append(iconElement);
            } else {
            }

            // Update the enhanced icon picker button
            const targetButton = modal.data('target-button');
            if (targetButton && targetButton.length) {
                const displayIcon = iconClass.replace('fa-', '').replace('fab ', '').replace('fas ', '').replace('far ', '');
                const iconPreview = targetButton.find('.pawfect-icon-preview');
                const iconText = targetButton.find('.pawfect-icon-text');

                iconPreview.html('<i class="' + iconClass + '"></i>');
                iconText.text(displayIcon);
            }

            // Trigger change event to update the repeater data
            targetInput.trigger('change');
            targetInput.trigger('input');

            // Call the repeater refresh function if it exists (from the original repeater JS)
            if (typeof pawfect_customizer_repeater_refresh_social_icons === 'function') {
                const container = targetInput.closest('.customizer-repeater-general-control-repeater-container');
                pawfect_customizer_repeater_refresh_social_icons(container);
            }

            // Also try the general refresh function
            if (typeof pawfect_customizer_repeater_refresh_general_control_values === 'function') {
                pawfect_customizer_repeater_refresh_general_control_values();
            }

            // Update the customizer setting
            const customizeControl = targetInput.closest('[data-customize-setting-link]');
            if (customizeControl.length) {
                const settingId = customizeControl.attr('data-customize-setting-link');
                if (settingId && wp.customize && wp.customize(settingId)) {
                    // Force customizer to recognize the change
                    setTimeout(function () {
                        wp.customize(settingId).trigger('change');
                    }, 100);
                }
            }

        }

        closeIconPicker();
    }

    /**
     * Debug function to check the DOM structure
     */
    function debugRepeaterStructure() {

        // Target specifically the social media repeater
        const socialMediaRepeater = $('#customize-control-pawfect_social_media_icons');
        if (socialMediaRepeater.length === 0) {
            return;
        }


        // Log each icon input found
        socialMediaRepeater.find('.icp-auto').each(function (index) {
            // Debug logging removed
        });
    }




    /**
     * Watch for repeater changes and new items
     */
    function watchForRepeaterChanges() {
        // Watch for new repeater items being added
        $(document).on('click', '#customize-control-pawfect_social_media_icons .customizer-repeater-new-field', function () {
            setTimeout(debugRepeaterStructure, 500);
        });

        // Watch for repeater items being expanded/collapsed
        $(document).on('click', '#customize-control-pawfect_social_media_icons .customizer-repeater-general-control-repeater-container .accordion-section-title', function () {
            setTimeout(debugRepeaterStructure, 300);
        });
        // Enhancement is now handled by fontawesome-iconpicker.js
    }

    // Global function for testing and manual initialization
    window.testEnhancedIconPicker = function () {


        // Try to create modal if it doesn't exist
        if ($('#pawfect-enhanced-icon-picker-modal').length === 0) {
            createIconPickerModal();
        }

        return 'Test completed - check console for results';
    };

    // Force initialization function
    window.forceInitIconPicker = function () {

        // Create modal if it doesn't exist
        if ($('#pawfect-enhanced-icon-picker-modal').length === 0) {
            createIconPickerModal();
        }

        // Debug the structure
        debugRepeaterStructure();

        return 'Force initialization completed';
    };

    // Auto-run force initialization after a delay
    setTimeout(function () {
        window.forceInitIconPicker();
    }, 3000);

    // Also run when user navigates to social media section
    $(document).on('click', 'li[aria-owns="sub-accordion-section-pawfect_social_media_section"]', function () {
        setTimeout(window.forceInitIconPicker, 1000);
    });

    // Also expose the main functions globally for debugging
    window.pawfectEnhancedIconPicker = {
        debugStructure: debugRepeaterStructure,
        createModal: createIconPickerModal,
        loadIcons: loadIcons
    };

})(jQuery);

