/**
 * Elementor Icon Picker for Product Display
 */

(function ($) {
    'use strict';

    // Global icon picker object
    window.proddispElementorIconPicker = {

        /**
         * Initialize icon picker
         */
        init: function ($container, options) {
            var self = this;
            var settings = $.extend({
                context: '',
                showPopular: true,
                showCategories: true,
                value: '',
                onChange: function () { }
            }, options);

            // Store settings
            $container.data('settings', settings);

            // Load icons
            this.loadIcons($container);

            // Bind events
            this.bindEvents($container);

            // Set initial value
            if (settings.value) {
                this.selectIcon($container, settings.value);
            }
        },

        /**
         * Load icons into the picker
         */
        loadIcons: function ($container) {
            var self = this;
            var settings = $container.data('settings');
            var $dropdown = $container.find('.icon-picker-dropdown');
            var $categories = $dropdown.find('.icon-categories');

            // Check if icons are available
            if (typeof proddispElementorIcons === 'undefined' || !proddispElementorIcons.icons) {
                $categories.html('<div class="no-icons-found"><p>Icons not loaded</p></div>');
                return;
            }

            var iconLibrary = proddispElementorIcons.icons;
            var html = '';

            // Add popular icons if enabled
            if (settings.showPopular) {
                html += this.renderPopularIcons();
            }

            // Add categorized icons
            if (settings.showCategories) {
                var prioritizedCategories = this.getPrioritizedCategories(iconLibrary, settings.context);

                prioritizedCategories.forEach(function (categoryName) {
                    if (iconLibrary[categoryName]) {
                        var isContextual = self.isContextualCategory(categoryName, settings.context);
                        html += self.renderCategory(categoryName, iconLibrary[categoryName], isContextual);
                    }
                });
            }

            $categories.html(html);
        },

        /**
         * Render popular icons section
         */
        renderPopularIcons: function () {
            var popularIcons = {
                'fas fa-shopping-cart': 'Shopping Cart',
                'fas fa-heart': 'Heart',
                'far fa-heart': 'Heart Outline',
                'fas fa-eye': 'Eye',
                'fas fa-balance-scale': 'Balance Scale',
                'fas fa-star': 'Star',
                'fas fa-share': 'Share',
                'fas fa-search': 'Search',
                'fas fa-user': 'User',
                'fas fa-cog': 'Settings'
            };

            var html = '<div class="icon-category popular-icons">';
            html += '<h4 class="category-title"><i class="fas fa-star"></i> Popular Icons</h4>';
            html += '<div class="icon-grid">';

            Object.keys(popularIcons).forEach(function (iconClass) {
                html += '<button class="icon-option" data-icon="' + iconClass + '" title="' + popularIcons[iconClass] + '">';
                html += '<i class="' + iconClass + '"></i>';
                html += '</button>';
            });

            html += '</div></div>';
            return html;
        },

        /**
         * Render category section
         */
        renderCategory: function (categoryName, icons, isContextual) {
            var html = '<div class="icon-category' + (isContextual ? ' contextual-category' : '') + '">';
            html += '<h4 class="category-title">';

            if (isContextual) {
                html += '<i class="fas fa-thumbtack"></i> ';
            }

            html += categoryName;

            if (isContextual) {
                html += '<span class="contextual-badge">Suggested</span>';
            }

            html += '</h4>';
            html += '<div class="icon-grid">';

            Object.keys(icons).forEach(function (iconClass) {
                html += '<button class="icon-option" data-icon="' + iconClass + '" title="' + icons[iconClass] + '">';
                html += '<i class="' + iconClass + '"></i>';
                html += '</button>';
            });

            html += '</div></div>';
            return html;
        },

        /**
         * Get prioritized categories based on context
         */
        getPrioritizedCategories: function (iconLibrary, context) {
            var contextMap = {
                'cart': ['Shopping & E-commerce', 'Actions & Interactions'],
                'addtocart': ['Shopping & E-commerce', 'Actions & Interactions'],
                'wishlist': ['Actions & Interactions', 'User & People'],
                'compare': ['Actions & Interactions', 'Interface & Controls'],
                'quickview': ['Actions & Interactions', 'Media & Files'],
                'share': ['Communication & Social', 'Actions & Interactions'],
                'search': ['Interface & Controls', 'Actions & Interactions'],
                'filter': ['Interface & Controls', 'Actions & Interactions'],
                'user': ['User & People', 'Security & Safety'],
                'settings': ['Interface & Controls', 'Technology & Devices']
            };

            var contextualCategories = contextMap[context.toLowerCase()] || [];
            var allCategories = Object.keys(iconLibrary);
            var prioritized = [...contextualCategories];

            allCategories.forEach(function (cat) {
                if (prioritized.indexOf(cat) === -1) {
                    prioritized.push(cat);
                }
            });

            return prioritized;
        },

        /**
         * Check if category is contextual
         */
        isContextualCategory: function (categoryName, context) {
            var contextMap = {
                'cart': ['Shopping & E-commerce', 'Actions & Interactions'],
                'addtocart': ['Shopping & E-commerce', 'Actions & Interactions'],
                'wishlist': ['Actions & Interactions', 'User & People'],
                'compare': ['Actions & Interactions', 'Interface & Controls'],
                'quickview': ['Actions & Interactions', 'Media & Files']
            };

            var contextualCategories = contextMap[context.toLowerCase()] || [];
            return contextualCategories.indexOf(categoryName) !== -1;
        },

        /**
         * Bind events
         */
        bindEvents: function ($container) {
            var self = this;
            var settings = $container.data('settings');

            // Toggle dropdown
            $container.on('click', '.icon-picker-trigger', function (e) {
                e.preventDefault();
                e.stopPropagation();

                var $dropdown = $container.find('.icon-picker-dropdown');
                var isOpen = $dropdown.is(':visible');

                // Close all other dropdowns
                $('.icon-picker-dropdown').hide();

                if (!isOpen) {
                    $dropdown.show();
                    $container.find('.icon-search-input').focus();
                }
            });

            // Icon selection
            $container.on('click', '.icon-option', function (e) {
                e.preventDefault();
                var iconClass = $(this).data('icon');
                self.selectIcon($container, iconClass);
                settings.onChange(iconClass);
            });

            // Search functionality
            $container.on('input', '.icon-search-input', function () {
                var searchTerm = $(this).val().toLowerCase();
                self.filterIcons($container, searchTerm);
            });

            // Close dropdown when clicking outside
            $(document).on('click', function (e) {
                if (!$container.is(e.target) && $container.has(e.target).length === 0) {
                    $container.find('.icon-picker-dropdown').hide();
                }
            });
        },

        /**
         * Select an icon
         */
        selectIcon: function ($container, iconClass) {
            var $trigger = $container.find('.icon-picker-trigger');
            var $selectedIcon = $trigger.find('.selected-icon');

            // Update display
            $selectedIcon.html('<i class="icon-display ' + iconClass + '"></i><span class="icon-class">' + iconClass + '</span>');

            // Update selected state
            $container.find('.icon-option').removeClass('selected');
            $container.find('.icon-option[data-icon="' + iconClass + '"]').addClass('selected');

            // Close dropdown
            $container.find('.icon-picker-dropdown').hide();
        },

        /**
         * Filter icons based on search term
         */
        filterIcons: function ($container, searchTerm) {
            var $categories = $container.find('.icon-category');

            if (!searchTerm) {
                $categories.show();
                $container.find('.icon-option').show();
                return;
            }

            $categories.each(function () {
                var $category = $(this);
                var $icons = $category.find('.icon-option');
                var hasVisibleIcons = false;

                $icons.each(function () {
                    var $icon = $(this);
                    var iconClass = $icon.data('icon') || '';
                    var iconTitle = $icon.attr('title') || '';

                    var matches = iconClass.toLowerCase().indexOf(searchTerm) !== -1 ||
                        iconTitle.toLowerCase().indexOf(searchTerm) !== -1;

                    if (matches) {
                        $icon.show();
                        hasVisibleIcons = true;
                    } else {
                        $icon.hide();
                    }
                });

                if (hasVisibleIcons) {
                    $category.show();
                } else {
                    $category.hide();
                }
            });
        }
    };

    // Initialize when Elementor panel is ready
    $(window).on('elementor:init', function () {
        // Wait for panel to be ready
        elementor.hooks.addAction('panel/open_editor/widget', function (panel, model, view) {
            setTimeout(function () {
                // Initialize any icon pickers in the current panel
                $('.proddisp-elementor-icon-picker').each(function () {
                    var $this = $(this);
                    if (!$this.data('initialized')) {
                        $this.data('initialized', true);
                        // Icon picker will be initialized via the control template
                    }
                });
            }, 100);
        });
    });

})(jQuery);