/**
 * Entity Selector - Methods Module
 * Method dropdown rendering, value pickers, combination picker
 * @partial _methods.js
 *
 * EXTRACTION SOURCE: assets/js/admin/entity-selector.js
 * Lines: 6760-6848 (initMethodDropdowns, enhanceMethodSelect)
 *        6849-7051 (showMethodDropdownMenu, buildMethodDropdownMenuHtml, closeMethodDropdownMenu)
 *        7053-7138 (populateTiles, applyRangeInputConstraints, showRangeInputError)
 *        7139-7380 (combination picker methods)
 *        7382-7550 (updateMethodInfoPlaceholder, getBuiltInMethodHelp)
 *        7748-7888 (buildSortOptions, updateModifierButtonState, updateMethodSelectorLock)
 *
 * Contains:
 * - initMethodDropdowns() - Initialize styled dropdowns
 * - enhanceMethodSelect() - Convert select to styled dropdown
 * - showMethodDropdownMenu() - Show method selection menu
 * - buildMethodDropdownMenuHtml() - Build menu HTML
 * - closeMethodDropdownMenu() - Close dropdown menu
 * - updateMethodTrigger() - Update trigger display
 * - populateTiles() - Build multi-select tiles
 * - applyRangeInputConstraints() - Set numeric input constraints
 * - showRangeInputError() - Display validation error
 * - loadCombinationAttributeGroups() - Load attribute groups for picker
 * - loadCombinationAttributeValues() - Load values for attribute group
 * - restoreCombinationSelections() - Restore saved combination state
 * - updateCombinationData() - Save combination selection
 * - updateCombinationGroupCounts() - Update selection counts
 * - updateMethodInfoPlaceholder() - Show method help
 * - getBuiltInMethodHelp() - Get help text for methods
 * - buildSortOptions() - Build sort dropdown options
 * - updateModifierButtonState() - Update modifier toggle state
 * - updateMethodSelectorLock() - Lock/unlock method selector
 */

(function($) {
    'use strict';

    window._EntitySelectorMixins = window._EntitySelectorMixins || {};

    window._EntitySelectorMixins.methods = {

        /**
         * Initialize styled method dropdowns for all method selects
         */
        initMethodDropdowns: function() {
            var self = this;
            this.$wrapper.find('.include-method-select').each(function() {
                self.enhanceMethodSelect($(this));
            });
            this.$wrapper.find('.exclude-method-select').each(function() {
                self.enhanceMethodSelect($(this));
            });
            this.initMethodInfoPlaceholders();
        },

        /**
         * Initialize info placeholders for all existing method selects
         */
        initMethodInfoPlaceholders: function() {
            var self = this;
            this.$wrapper.find('.selection-group').each(function() {
                var $group = $(this);
                var $block = $group.closest('.target-block');
                var blockType = $block.data('blockType') || 'products';

                // Include method info
                var includeMethod = $group.find('.include-method-select').val() || 'all';
                self.updateMethodInfoPlaceholder($group.find('.method-selector-wrapper'), includeMethod, blockType);

                // Exclude methods info
                $group.find('.exclude-row').each(function() {
                    var $row = $(this);
                    var excludeMethod = $row.find('.exclude-method-select').val();
                    if (excludeMethod) {
                        self.updateMethodInfoPlaceholder($row.find('.method-selector-wrapper'), excludeMethod, blockType);
                    }
                });
            });
        },

        /**
         * Enhance a single method select with styled dropdown
         */
        enhanceMethodSelect: function($select) {
            var self = this;

            if (!$select.length || $select.data('methodDropdownInit')) {
                return;
            }
            $select.data('methodDropdownInit', true);

            $select.addClass('method-select-hidden');

            var $selectedOption = $select.find('option:selected');
            var selectedIcon = $selectedOption.data('icon') || 'arrow_drop_down';
            var selectedLabel = $selectedOption.text();

            var triggerHtml = '<div class="method-dropdown-trigger">';
            triggerHtml += this.esIcon(selectedIcon, 'method-trigger-icon');
            triggerHtml += '<span class="method-trigger-label">' + this.escapeHtml(selectedLabel) + '</span>';
            triggerHtml += this.esIcon('arrow_drop_down', 'method-trigger-caret');
            triggerHtml += '</div>';

            var $trigger = $(triggerHtml);
            $select.after($trigger);

            $trigger.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();

                var $wrapper = $select.closest('.method-selector-wrapper');
                if ($wrapper.hasClass('selector-locked')) {
                    return;
                }

                self.showMethodDropdownMenu($select, $trigger);
            });

            $select.on('change.methodDropdown', function() {
                self.updateMethodTrigger($select, $trigger);
            });
        },

        /**
         * Update the trigger display to match current selection
         */
        updateMethodTrigger: function($select, $trigger) {
            var $selectedOption = $select.find('option:selected');
            var selectedIcon = $selectedOption.data('icon') || 'arrow_drop_down';
            var selectedLabel = $selectedOption.text();

            $trigger.find('.method-trigger-icon').replaceWith(this.esIcon(selectedIcon, 'method-trigger-icon'));
            $trigger.find('.method-trigger-label').text(selectedLabel);
        },

        /**
         * Show the method dropdown menu
         */
        showMethodDropdownMenu: function($select, $trigger) {
            var self = this;

            this.closeMethodDropdownMenu();

            var menuHtml = this.buildMethodDropdownMenuHtml($select);
            var $menu = $(menuHtml);

            var triggerOffset = $trigger.offset();
            var triggerWidth = $trigger.outerWidth();
            var triggerHeight = $trigger.outerHeight();

            $menu.css({
                position: 'absolute',
                top: triggerOffset.top + triggerHeight + 2,
                left: triggerOffset.left,
                minWidth: triggerWidth,
                zIndex: 10001
            });

            $('body').append($menu);
            this.$methodDropdownMenu = $menu;
            this.$methodDropdownSelect = $select;
            this.$methodDropdownTrigger = $trigger;

            $menu.on('click', '.method-dropdown-item', function(e) {
                e.preventDefault();
                e.stopPropagation();

                var value = $(this).data('value');
                $select.val(value).trigger('change');
                self.closeMethodDropdownMenu();
            });

            $(document).on('click.methodDropdown', function(e) {
                if (!$(e.target).closest('.method-dropdown-menu, .method-dropdown-trigger').length) {
                    self.closeMethodDropdownMenu();
                }
            });

            $(document).on('keydown.methodDropdown', function(e) {
                if (e.keyCode === 27) {
                    self.closeMethodDropdownMenu();
                }
            });
        },

        /**
         * Build the dropdown menu HTML
         */
        buildMethodDropdownMenuHtml: function($select) {
            var self = this;
            var html = '<div class="method-dropdown-menu">';

            // Render ungrouped options first
            $select.children('option').each(function() {
                var $el = $(this);
                var icon = $el.data('icon') || 'star';
                var label = $el.text();
                var value = $el.val();
                var isSelected = $el.is(':selected');

                html += '<div class="method-dropdown-item' + (isSelected ? ' selected' : '') + '" data-value="' + self.escapeAttr(value) + '">';
                html += self.esIcon(icon, 'method-item-icon');
                html += '<span class="method-item-label">' + self.escapeHtml(label) + '</span>';
                if (isSelected) {
                    html += self.esIcon('check', 'method-item-check');
                }
                html += '</div>';
            });

            // Render optgroups
            $select.children('optgroup').each(function() {
                var $optgroup = $(this);
                var groupLabel = $optgroup.attr('label') || '';

                html += '<div class="method-dropdown-optgroup">';
                html += '<div class="method-optgroup-label">' + self.escapeHtml(groupLabel) + '</div>';
                html += '<div class="method-optgroup-items">';

                $optgroup.children('option').each(function() {
                    var $el = $(this);
                    var icon = $el.data('icon') || 'settings';
                    var label = $el.text();
                    var value = $el.val();
                    var isSelected = $el.is(':selected');

                    html += '<div class="method-dropdown-item' + (isSelected ? ' selected' : '') + '" data-value="' + self.escapeAttr(value) + '">';
                    html += self.esIcon(icon, 'method-item-icon');
                    html += '<span class="method-item-label">' + self.escapeHtml(label) + '</span>';
                    if (isSelected) {
                        html += self.esIcon('check', 'method-item-check');
                    }
                    html += '</div>';
                });

                html += '</div>'; // close items
                html += '</div>'; // close optgroup
            });

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

        /**
         * Close the method dropdown menu
         */
        closeMethodDropdownMenu: function() {
            if (this.$methodDropdownMenu) {
                this.$methodDropdownMenu.remove();
                this.$methodDropdownMenu = null;
            }
            this.$methodDropdownSelect = null;
            this.$methodDropdownTrigger = null;
            $(document).off('click.methodDropdown keydown.methodDropdown');
        },

        /**
         * Populate tiles for multi_select_tiles value picker
         */
        populateTiles: function($picker, options, exclusive) {
            var self = this;
            var $container = $picker.find('.multi-select-tiles');
            $container.empty();

            if (exclusive) {
                $container.attr('data-exclusive', 'true');
            } else {
                $container.removeAttr('data-exclusive');
            }

            $.each(options, function(key, optData) {
                var label = typeof optData === 'object' ? optData.label : optData;
                var icon = typeof optData === 'object' && optData.icon ? optData.icon : null;
                var color = typeof optData === 'object' && optData.color ? optData.color : null;

                var tileClass = 'tile-option';
                if (color) {
                    tileClass += ' tile-color-' + color;
                }

                var $tile = $('<button>', {
                    type: 'button',
                    class: tileClass,
                    'data-value': key
                });

                if (icon) {
                    $tile.append($('<i>', { class: icon }));
                }
                $tile.append($('<span>', { class: 'tile-label', text: label }));

                $container.append($tile);
            });
        },

        /**
         * Apply step/min constraints to numeric range inputs
         */
        applyRangeInputConstraints: function($picker, step, min) {
            var $inputs = $picker.find('.range-min-input, .range-max-input');

            if (typeof step !== 'undefined' && step !== null) {
                $inputs.attr('step', step);
            } else {
                $inputs.attr('step', 'any');
            }

            if (typeof min !== 'undefined' && min !== null) {
                $inputs.attr('min', min);
            } else {
                $inputs.removeAttr('min');
            }
        },

        /**
         * Show error message on range input
         */
        showRangeInputError: function($input, message) {
            var $container = $input.closest('.multi-range-input-row');

            $container.find('.range-input-error').remove();
            $container.find('.range-min-input, .range-max-input').removeClass('has-error');

            $input.addClass('has-error');
            var $error = $('<span>', {
                class: 'range-input-error',
                text: message
            });
            $container.append($error);

            setTimeout(function() {
                $input.removeClass('has-error');
                $error.fadeOut(200, function() {
                    $(this).remove();
                });
            }, 3000);
        },

        /**
         * Load attribute groups for combination picker
         */
        loadCombinationAttributeGroups: function($picker) {
            var self = this;
            var trans = this.config.trans || {};
            var $container = $picker.find('.combination-groups-container');

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    ajax: 1,
                    action: 'getAttributeGroups',
                    trait: 'TargetConditions'
                },
                success: function(response) {
                    $container.empty();

                    if (!response.success || !response.groups || response.groups.length === 0) {
                        $container.html('<span class="combination-empty">' +
                            self.escapeHtml(trans.no_attribute_groups || 'No attribute groups found') +
                            '</span>');
                        return;
                    }

                    response.groups.forEach(function(group) {
                        var $groupDiv = $('<div>', {
                            class: 'comb-attr-group',
                            'data-group-id': group.id
                        });

                        var $groupHeader = $('<div>', { class: 'comb-attr-group-header' });
                        $groupHeader.append($('<span>', {
                            class: 'comb-attr-group-name',
                            text: group.name
                        }));
                        $groupHeader.append($('<span>', {
                            class: 'comb-attr-group-count',
                            text: '0'
                        }));

                        var $toolbar = $('<div>', { class: 'comb-attr-toolbar' });
                        $toolbar.append($('<button>', {
                            type: 'button',
                            class: 'comb-toolbar-btn comb-select-all',
                            title: trans.select_all || 'Select all',
                            html: self.esIcon('check_box')
                        }));
                        $toolbar.append($('<button>', {
                            type: 'button',
                            class: 'comb-toolbar-btn comb-select-none',
                            title: trans.clear || 'Clear',
                            html: self.esIcon('check_box_outline_blank')
                        }));
                        $toolbar.append($('<input>', {
                            type: 'text',
                            class: 'comb-attr-search',
                            placeholder: trans.filter_results || 'Filter...'
                        }));

                        var $valuesContainer = $('<div>', {
                            class: 'comb-attr-values',
                            'data-loaded': 'false'
                        });
                        $valuesContainer.append($('<span>', {
                            class: 'comb-attr-loading',
                            html: self.esIcon('progress_activity', 'es-spin')
                        }));

                        $groupDiv.append($groupHeader);
                        $groupDiv.append($toolbar);
                        $groupDiv.append($valuesContainer);
                        $container.append($groupDiv);

                        self.loadCombinationAttributeValues($picker, group.id, $valuesContainer);
                    });
                },
                error: function() {
                    $container.html('<span class="combination-error">' +
                        self.escapeHtml(trans.error_loading || 'Error loading attribute groups') +
                        '</span>');
                }
            });
        },

        /**
         * Load attribute values for a specific group
         */
        loadCombinationAttributeValues: function($picker, groupId, $container) {
            var self = this;
            var trans = this.config.trans || {};

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    ajax: 1,
                    action: 'getAttributeValues',
                    trait: 'TargetConditions',
                    id_attribute_group: groupId
                },
                success: function(response) {
                    $container.empty();
                    $container.attr('data-loaded', 'true');

                    if (!response.success || !response.values || response.values.length === 0) {
                        $container.html('<span class="comb-attr-empty">' +
                            self.escapeHtml(trans.no_values || 'No values') +
                            '</span>');
                        return;
                    }

                    response.values.forEach(function(value) {
                        var productCount = parseInt(value.product_count) || 0;
                        var $valueBtn = $('<button>', {
                            type: 'button',
                            class: 'comb-attr-value',
                            'data-value-id': value.id,
                            'data-group-id': groupId,
                            'data-name': value.name.toLowerCase()
                        });
                        $valueBtn.append($('<span>', {
                            class: 'comb-attr-value-name',
                            text: value.name
                        }));
                        if (productCount > 0) {
                            $valueBtn.append($('<span>', {
                                class: 'comb-attr-value-count',
                                text: productCount
                            }));
                        }
                        $container.append($valueBtn);
                    });

                    self.restoreCombinationSelections($picker);
                },
                error: function() {
                    $container.html('<span class="comb-attr-error">' +
                        self.escapeHtml(trans.error_loading || 'Error') +
                        '</span>');
                }
            });
        },

        /**
         * Restore previously selected combination values from hidden input
         */
        restoreCombinationSelections: function($picker) {
            var $dataInput = $picker.find('.include-values-data, .exclude-values-data').first();
            var dataStr = $dataInput.val() || '{}';
            var data;

            try {
                data = JSON.parse(dataStr);
            } catch (e) {
                return;
            }

            var attributes = data.attributes || data;
            var mode = data.mode || 'products';

            $picker.find('.comb-mode-radio[value="' + mode + '"]').prop('checked', true);

            $.each(attributes, function(groupId, valueIds) {
                if (!Array.isArray(valueIds)) return;

                valueIds.forEach(function(valueId) {
                    $picker.find('.comb-attr-value[data-group-id="' + groupId + '"][data-value-id="' + valueId + '"]')
                        .addClass('selected');
                });
            });

            this.updateCombinationGroupCounts($picker);
        },

        /**
         * Update hidden input with current combination selections
         */
        updateCombinationData: function($picker) {
            var attributes = {};

            $picker.find('.comb-attr-value.selected').each(function() {
                var groupId = $(this).data('groupId').toString();
                var valueId = $(this).data('valueId');

                if (!attributes[groupId]) {
                    attributes[groupId] = [];
                }
                attributes[groupId].push(valueId);
            });

            var $combPicker = $picker.find('.combination-attributes-picker');
            var configMode = $combPicker.data('combinationMode') || this.config.combinationMode || 'products';
            var mode;

            if (configMode === 'toggle') {
                mode = $picker.find('.comb-mode-radio:checked').val() || 'products';
            } else {
                mode = configMode;
            }

            var data = {
                mode: mode,
                attributes: attributes
            };

            var $dataInput = $picker.find('.include-values-data, .exclude-values-data').first();
            $dataInput.val(JSON.stringify(data));

            this.updateCombinationGroupCounts($picker);
        },

        /**
         * Update the count badges on each attribute group
         */
        updateCombinationGroupCounts: function($picker) {
            $picker.find('.comb-attr-group').each(function() {
                var $group = $(this);
                var count = $group.find('.comb-attr-value.selected').length;
                $group.find('.comb-attr-group-count').text(count);

                if (count > 0) {
                    $group.addClass('has-selections');
                } else {
                    $group.removeClass('has-selections');
                }
            });
        },

        /**
         * Update the info placeholder based on method and block type
         */
        updateMethodInfoPlaceholder: function($headerRow, method, blockType) {
            var $placeholder = $headerRow.find('.method-info-placeholder');
            if (!$placeholder.length) return;

            $placeholder.empty();

            var methodHelp = this.config.methodHelp || {};
            var blockHelp = methodHelp[blockType] || methodHelp['products'] || {};
            var helpContent = blockHelp[method] || this.getBuiltInMethodHelp(method);

            if (helpContent) {
                var $infoWrapper = $('<span>', {
                    class: 'mpr-info-wrapper',
                    'data-details': helpContent
                });
                $infoWrapper.append($(this.esIcon('info')));
                $placeholder.append($infoWrapper);

                // Let prestashop-admin info-tooltip.js handle this element
                if (window.MPRInfoTooltip) {
                    window.MPRInfoTooltip.init();
                }
            }
        },

        /**
         * Get built-in help content for targeting methods
         */
        getBuiltInMethodHelp: function(method) {
            var trans = this.config.trans || {};
            var html = '';

            switch (method) {
                case 'all':
                    html = '<strong>' + this.escapeHtml(trans.help_all_title || 'All Items') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_all_desc || 'Selects all items without any filtering.') + '</p>';
                    break;

                case 'specific':
                    html = '<strong>' + this.escapeHtml(trans.help_specific_title || 'Specific Items') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_specific_desc || 'Search and select individual items by name, reference, or ID.') + '</p>';
                    break;

                case 'by_category':
                    html = '<strong>' + this.escapeHtml(trans.help_category_title || 'By Category') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_category_desc || 'Select items belonging to specific categories. Includes subcategories.') + '</p>';
                    break;

                case 'by_manufacturer':
                    html = '<strong>' + this.escapeHtml(trans.help_manufacturer_title || 'By Manufacturer') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_manufacturer_desc || 'Select items from specific manufacturers/brands.') + '</p>';
                    break;

                case 'by_supplier':
                    html = '<strong>' + this.escapeHtml(trans.help_supplier_title || 'By Supplier') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_supplier_desc || 'Select items from specific suppliers.') + '</p>';
                    break;

                case 'by_tag':
                    html = '<strong>' + this.escapeHtml(trans.help_tag_title || 'By Tag') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_tag_desc || 'Select items with specific tags assigned.') + '</p>';
                    break;

                case 'by_attribute':
                    html = '<strong>' + this.escapeHtml(trans.help_attribute_title || 'By Attribute') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_attribute_desc || 'Select items with specific attribute values (e.g., Color: Red).') + '</p>';
                    break;

                case 'by_feature':
                    html = '<strong>' + this.escapeHtml(trans.help_feature_title || 'By Feature') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_feature_desc || 'Select items with specific feature values (e.g., Material: Cotton).') + '</p>';
                    break;

                case 'by_combination':
                    html = '<strong>' + this.escapeHtml(trans.help_combination_title || 'Combination Targeting') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_combination_desc || 'Select items by combination attributes.') + '</p>';
                    html += '<p><strong>' + this.escapeHtml(trans.help_combination_logic || 'Logic:') + '</strong></p>';
                    html += '<ul>';
                    html += '<li>' + this.escapeHtml(trans.help_combination_within || 'Within group: OR (Red OR Blue)') + '</li>';
                    html += '<li>' + this.escapeHtml(trans.help_combination_between || 'Between groups: AND (Color AND Size)') + '</li>';
                    html += '</ul>';
                    break;

                case 'by_carrier':
                    html = '<strong>' + this.escapeHtml(trans.help_carrier_title || 'By Carrier') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_carrier_desc || 'Select items available with specific carriers.') + '</p>';
                    break;

                case 'by_condition':
                    html = '<strong>' + this.escapeHtml(trans.help_condition_title || 'By Condition') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_condition_desc || 'Filter by product condition: New, Used, or Refurbished.') + '</p>';
                    break;

                case 'by_visibility':
                    html = '<strong>' + this.escapeHtml(trans.help_visibility_title || 'By Visibility') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_visibility_desc || 'Filter by where products are visible in the store.') + '</p>';
                    break;

                case 'by_active_status':
                    html = '<strong>' + this.escapeHtml(trans.help_active_title || 'By Active Status') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_active_desc || 'Filter by whether products are enabled or disabled.') + '</p>';
                    break;

                case 'by_stock_status':
                    html = '<strong>' + this.escapeHtml(trans.help_stock_title || 'By Stock Status') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_stock_desc || 'Filter by stock availability: In stock, Out of stock, or Low stock.') + '</p>';
                    break;

                case 'by_on_sale':
                case 'by_has_specific_price':
                case 'by_is_virtual':
                case 'by_is_pack':
                case 'by_has_combinations':
                case 'by_available_for_order':
                case 'by_online_only':
                case 'by_has_related':
                case 'by_has_customization':
                case 'by_has_attachments':
                case 'by_has_additional_shipping':
                    html = '<strong>' + this.escapeHtml(trans.help_boolean_title || 'Yes/No Filter') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_boolean_desc || 'Filter products by this property.') + '</p>';
                    break;

                case 'by_name_pattern':
                case 'by_reference_pattern':
                case 'by_description_pattern':
                case 'by_long_description_pattern':
                case 'by_ean13_pattern':
                case 'by_upc_pattern':
                case 'by_isbn_pattern':
                case 'by_mpn_pattern':
                case 'by_meta_title_pattern':
                case 'by_meta_description_pattern':
                    html = '<strong>' + this.escapeHtml(trans.help_pattern_title || 'Pattern Matching') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_pattern_desc || 'Match text using patterns with wildcards.') + '</p>';
                    html += '<div><code>*</code> ' + this.escapeHtml(trans.help_pattern_wildcard || 'any text') + '</div>';
                    html += '<div><code>{number}</code> ' + this.escapeHtml(trans.help_pattern_number || 'any number') + '</div>';
                    html += '<div><code>{letter}</code> ' + this.escapeHtml(trans.help_pattern_letter || 'single letter A-Z') + '</div>';
                    break;

                case 'by_id_range':
                case 'by_price_range':
                case 'by_weight_range':
                case 'by_quantity_range':
                case 'by_position_range':
                    html = '<strong>' + this.escapeHtml(trans.help_range_title || 'Numeric Range') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_range_desc || 'Filter by numeric values within specified ranges.') + '</p>';
                    html += '<p>' + this.escapeHtml(trans.help_range_tip || 'Leave min or max empty for open-ended ranges.') + '</p>';
                    break;

                case 'by_date_added':
                case 'by_date_updated':
                    html = '<strong>' + this.escapeHtml(trans.help_date_title || 'Date Range') + '</strong>';
                    html += '<p>' + this.escapeHtml(trans.help_date_desc || 'Filter by date within a specific period.') + '</p>';
                    break;

                default:
                    break;
            }

            return html;
        },

        /**
         * Build sort options HTML for a specific block type
         */
        buildSortOptions: function(blockType) {
            var options = [];

            switch (blockType) {
                case 'products':
                    options = [
                        { value: 'sales', label: 'Best sellers' },
                        { value: 'date_add', label: 'Newest' },
                        { value: 'price', label: 'Price' },
                        { value: 'name', label: 'Name' },
                        { value: 'position', label: 'Position' },
                        { value: 'quantity', label: 'Stock quantity' },
                        { value: 'random', label: 'Random' }
                    ];
                    break;

                case 'categories':
                    options = [
                        { value: 'name', label: 'Name' },
                        { value: 'position', label: 'Position' },
                        { value: 'product_count', label: 'Product count' },
                        { value: 'total_sales', label: 'Best sellers' },
                        { value: 'newest_products', label: 'Newest products' },
                        { value: 'date_add', label: 'Creation date' },
                        { value: 'random', label: 'Random' }
                    ];
                    break;

                case 'manufacturers':
                case 'suppliers':
                    options = [
                        { value: 'name', label: 'Name' },
                        { value: 'product_count', label: 'Product count' },
                        { value: 'total_sales', label: 'Best sellers' },
                        { value: 'newest_products', label: 'Newest products' },
                        { value: 'random', label: 'Random' }
                    ];
                    break;

                case 'cms':
                case 'cms_categories':
                    options = [
                        { value: 'name', label: 'Name' },
                        { value: 'position', label: 'Position' },
                        { value: 'random', label: 'Random' }
                    ];
                    break;

                default:
                    options = [
                        { value: 'name', label: 'Name' },
                        { value: 'random', label: 'Random' }
                    ];
            }

            var html = '';
            for (var i = 0; i < options.length; i++) {
                html += '<option value="' + this.escapeAttr(options[i].value) + '">' +
                        this.escapeHtml(options[i].label) + '</option>';
            }

            return html;
        },

        /**
         * Update the modifier toggle button state
         */
        updateModifierButtonState: function($group) {
            var limit = $group.find('.group-modifier-limit').val();
            var sortBy = $group.find('.group-modifier-sort').val();
            var $modifiers = $group.find('.group-modifiers');
            var $btn = $group.find('.btn-toggle-modifiers');
            var trans = this.config.trans || {};

            $btn.find('.modifier-summary').remove();

            if (limit || sortBy) {
                $modifiers.addClass('has-values');

                var summary = [];
                if (limit) {
                    summary.push((trans.top || 'Top') + ' ' + limit);
                }
                if (sortBy) {
                    var sortLabel = $group.find('.group-modifier-sort option:selected').text();
                    summary.push(sortLabel);
                }

                var $arrow = $btn.find('.toggle-arrow');
                $('<span class="modifier-summary">' + this.escapeHtml(summary.join(', ')) + '</span>').insertBefore($arrow);
            } else {
                $modifiers.removeClass('has-values');
            }
        },

        /**
         * Lock/unlock method selector when excludes are present
         */
        updateMethodSelectorLock: function($group, locked) {
            var $select = $group.find('.include-method-select');
            var $wrapper = $select.closest('.method-selector-wrapper');
            var trans = this.config.trans || {};

            if (locked) {
                $select.prop('disabled', true);

                if (!$wrapper.length) {
                    $select.wrap('<div class="method-selector-wrapper"></div>');
                    $wrapper = $select.parent('.method-selector-wrapper');
                }

                $wrapper.addClass('selector-locked');
                if (!$wrapper.find('.lock-indicator').length) {
                    var lockHtml = '<span class="mpr-info-wrapper lock-indicator">' +
                        this.esIcon('lock') +
                        '<span class="mpr-tooltip">' +
                        (trans.remove_excludes_first || 'Remove all exceptions to change selection type') +
                        '</span>' +
                        '</span>';
                    var $countEl = $wrapper.find('.condition-match-count');
                    if ($countEl.length) {
                        $countEl.before(lockHtml);
                    } else {
                        $wrapper.append(lockHtml);
                    }
                }
            } else {
                $select.prop('disabled', false);
                if ($wrapper.length) {
                    $wrapper.removeClass('selector-locked');
                    $wrapper.find('.mpr-info-wrapper.lock-indicator').remove();
                } else {
                    $select.siblings('.mpr-info-wrapper.lock-indicator').remove();
                }
            }
        }
    };

})(jQuery);
