/**
 * Entity Selector - Search Module
 * AJAX search, results rendering, category tree, filters, search history
 * @partial _search.js
 */

(function($) {
    'use strict';

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

    window._EntitySelectorMixins.search = {

        // Category tree cache
        categoryTreeCache: null,

        /**
         * Perform AJAX search for entities
         */
        performSearch: function(appendMode) {
            var self = this;

            if (!this.activeGroup) return;

            this.isLoading = true;

            var searchEntity = this.activeGroup.searchEntity;

            // Build request data with sort and filter params
            var limit = appendMode && this.loadMoreCount ? this.loadMoreCount : 20;
            var requestData = {
                ajax: 1,
                action: 'searchTargetEntities',
                trait: 'EntitySelector',
                entity_type: searchEntity,
                q: this.searchQuery,
                limit: limit,
                offset: appendMode ? this.searchOffset : 0,
                sort_by: this.currentSort ? this.currentSort.field : 'name',
                sort_dir: this.currentSort ? this.currentSort.dir : 'ASC'
            };

            // Add refine query if present
            if (this.refineQuery) {
                requestData.refine = this.refineQuery;
                if (this.refineNegate) {
                    requestData.refine_negate = 1;
                }
            }

            // Add product-specific filters
            if (searchEntity === 'products' && this.filters) {
                if (this.filters.inStock) {
                    requestData.filter_in_stock = 1;
                }
                if (this.filters.discounted) {
                    requestData.filter_discounted = 1;
                }
                if (this.filters.priceMin !== null && this.filters.priceMin !== '') {
                    requestData.filter_price_min = this.filters.priceMin;
                }
                if (this.filters.priceMax !== null && this.filters.priceMax !== '') {
                    requestData.filter_price_max = this.filters.priceMax;
                }
                if (this.filters.attributes && this.filters.attributes.length > 0) {
                    requestData.filter_attributes = JSON.stringify(this.filters.attributes);
                }
                if (this.filters.features && this.filters.features.length > 0) {
                    requestData.filter_features = JSON.stringify(this.filters.features);
                }
            }

            // Add entity-specific filters for non-product entities
            if (searchEntity !== 'products' && this.filters) {
                // Product count range (categories, manufacturers, suppliers, attributes, features)
                if (this.filters.productCountMin !== null && this.filters.productCountMin !== '') {
                    requestData.filter_product_count_min = this.filters.productCountMin;
                }
                if (this.filters.productCountMax !== null && this.filters.productCountMax !== '') {
                    requestData.filter_product_count_max = this.filters.productCountMax;
                }

                // Category-specific
                if (searchEntity === 'categories') {
                    if (this.filters.depth) {
                        requestData.filter_depth = this.filters.depth;
                    }
                    if (this.filters.hasProducts) {
                        requestData.filter_has_products = 1;
                    }
                    if (this.filters.hasDescription) {
                        requestData.filter_has_description = 1;
                    }
                    if (this.filters.hasImage) {
                        requestData.filter_has_image = 1;
                    }
                    if (this.filters.salesMin !== null && this.filters.salesMin !== '') {
                        requestData.filter_sales_min = this.filters.salesMin;
                    }
                    if (this.filters.salesMax !== null && this.filters.salesMax !== '') {
                        requestData.filter_sales_max = this.filters.salesMax;
                    }
                    if (this.filters.turnoverMin !== null && this.filters.turnoverMin !== '') {
                        requestData.filter_turnover_min = this.filters.turnoverMin;
                    }
                    if (this.filters.turnoverMax !== null && this.filters.turnoverMax !== '') {
                        requestData.filter_turnover_max = this.filters.turnoverMax;
                    }
                    if (this.filters.activeOnly) {
                        requestData.filter_active = 1;
                    }
                }

                // Manufacturer-specific
                if (searchEntity === 'manufacturers') {
                    if (this.filters.salesMin !== null && this.filters.salesMin !== '') {
                        requestData.filter_sales_min = this.filters.salesMin;
                    }
                    if (this.filters.salesMax !== null && this.filters.salesMax !== '') {
                        requestData.filter_sales_max = this.filters.salesMax;
                    }
                    if (this.filters.turnoverMin !== null && this.filters.turnoverMin !== '') {
                        requestData.filter_turnover_min = this.filters.turnoverMin;
                    }
                    if (this.filters.turnoverMax !== null && this.filters.turnoverMax !== '') {
                        requestData.filter_turnover_max = this.filters.turnoverMax;
                    }
                    if (this.filters.dateAddFrom) {
                        requestData.filter_date_add_from = this.filters.dateAddFrom;
                    }
                    if (this.filters.dateAddTo) {
                        requestData.filter_date_add_to = this.filters.dateAddTo;
                    }
                    if (this.filters.lastProductFrom) {
                        requestData.filter_last_product_from = this.filters.lastProductFrom;
                    }
                    if (this.filters.lastProductTo) {
                        requestData.filter_last_product_to = this.filters.lastProductTo;
                    }
                    if (this.filters.activeOnly) {
                        requestData.filter_active = 1;
                    }
                }

                // Supplier-specific
                if (searchEntity === 'suppliers') {
                    if (this.filters.salesMin !== null && this.filters.salesMin !== '') {
                        requestData.filter_sales_min = this.filters.salesMin;
                    }
                    if (this.filters.salesMax !== null && this.filters.salesMax !== '') {
                        requestData.filter_sales_max = this.filters.salesMax;
                    }
                    if (this.filters.turnoverMin !== null && this.filters.turnoverMin !== '') {
                        requestData.filter_turnover_min = this.filters.turnoverMin;
                    }
                    if (this.filters.turnoverMax !== null && this.filters.turnoverMax !== '') {
                        requestData.filter_turnover_max = this.filters.turnoverMax;
                    }
                    if (this.filters.dateAddFrom) {
                        requestData.filter_date_add_from = this.filters.dateAddFrom;
                    }
                    if (this.filters.dateAddTo) {
                        requestData.filter_date_add_to = this.filters.dateAddTo;
                    }
                    if (this.filters.lastProductFrom) {
                        requestData.filter_last_product_from = this.filters.lastProductFrom;
                    }
                    if (this.filters.lastProductTo) {
                        requestData.filter_last_product_to = this.filters.lastProductTo;
                    }
                    if (this.filters.activeOnly) {
                        requestData.filter_active = 1;
                    }
                }

                // Attribute-specific
                if (searchEntity === 'attributes') {
                    if (this.filters.salesMin !== null && this.filters.salesMin !== '') {
                        requestData.filter_sales_min = this.filters.salesMin;
                    }
                    if (this.filters.salesMax !== null && this.filters.salesMax !== '') {
                        requestData.filter_sales_max = this.filters.salesMax;
                    }
                    if (this.filters.turnoverMin !== null && this.filters.turnoverMin !== '') {
                        requestData.filter_turnover_min = this.filters.turnoverMin;
                    }
                    if (this.filters.turnoverMax !== null && this.filters.turnoverMax !== '') {
                        requestData.filter_turnover_max = this.filters.turnoverMax;
                    }
                    if (this.filters.attributeGroup) {
                        requestData.filter_attribute_group = this.filters.attributeGroup;
                    }
                    if (this.filters.isColor) {
                        requestData.filter_is_color = 1;
                    }
                }

                // Feature-specific
                if (searchEntity === 'features') {
                    if (this.filters.salesMin !== null && this.filters.salesMin !== '') {
                        requestData.filter_sales_min = this.filters.salesMin;
                    }
                    if (this.filters.salesMax !== null && this.filters.salesMax !== '') {
                        requestData.filter_sales_max = this.filters.salesMax;
                    }
                    if (this.filters.turnoverMin !== null && this.filters.turnoverMin !== '') {
                        requestData.filter_turnover_min = this.filters.turnoverMin;
                    }
                    if (this.filters.turnoverMax !== null && this.filters.turnoverMax !== '') {
                        requestData.filter_turnover_max = this.filters.turnoverMax;
                    }
                    if (this.filters.featureGroup) {
                        requestData.filter_feature_group = this.filters.featureGroup;
                    }
                    if (this.filters.isCustom) {
                        requestData.filter_is_custom = 1;
                    }
                }

                // CMS-specific
                if (searchEntity === 'cms') {
                    if (this.filters.activeOnly) {
                        requestData.filter_active = 1;
                    }
                    if (this.filters.indexable) {
                        requestData.filter_indexable = 1;
                    }
                }

                // CMS Categories-specific
                if (searchEntity === 'cms_categories') {
                    if (this.filters.activeOnly) {
                        requestData.filter_active = 1;
                    }
                }

                // Countries-specific
                if (searchEntity === 'countries') {
                    if (this.filters.activeOnly) {
                        requestData.filter_active = 1;
                    }
                    if (this.filters.hasHolidays) {
                        requestData.filter_has_holidays = 1;
                    }
                    if (this.filters.containsStates) {
                        requestData.filter_contains_states = 1;
                    }
                    if (this.filters.zone) {
                        requestData.filter_zone = this.filters.zone;
                    }
                }
            }

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: requestData,
                success: function(response) {
                    self.isLoading = false;

                    if (!response.success) return;

                    // Save to search history if query is not empty and has results
                    if (self.searchQuery && self.searchQuery.length >= 2 && response.total > 0) {
                        self.addToSearchHistory(searchEntity, self.searchQuery);
                    }

                    if (appendMode) {
                        self.searchResults = self.searchResults.concat(response.results || []);
                    } else {
                        self.searchResults = response.results || [];
                    }
                    self.searchTotal = response.total || 0;
                    self.searchOffset = appendMode ? self.searchOffset + (response.results || []).length : (response.results || []).length;

                    self.renderSearchResults(appendMode);
                    self.$dropdown.addClass('show');
                },
                error: function() {
                    self.isLoading = false;
                }
            });
        },

        /**
         * Render search results in the dropdown
         */
        renderSearchResults: function(appendMode) {
            var self = this;
            var trans = this.config.trans || {};
            var $container = this.$dropdown.find('.dropdown-results');

            // Get selected IDs from current picker (to mark as selected)
            // and hidden IDs from sibling exclude pickers with same entity type (to hide completely)
            var selectedIds = [];
            var hiddenIds = [];
            if (this.activeGroup) {
                var $block = this.$wrapper.find('.target-block[data-block-type="' + this.activeGroup.blockType + '"]');
                var $group = $block.find('.selection-group[data-group-index="' + this.activeGroup.groupIndex + '"]');
                var currentSearchEntity = this.activeGroup.searchEntity;
                var currentExcludeIndex = this.activeGroup.excludeIndex;

                if (this.activeGroup.section === 'include') {
                    // For include section, just get current picker's selections
                    var $picker = $group.find('.include-picker');
                    $picker.find('.entity-chip').each(function() {
                        selectedIds.push(String($(this).data('id')));
                    });
                } else {
                    // For exclude section, get current picker's selections AND
                    // collect IDs from sibling exclude rows with same entity type to hide
                    var $currentExcludeRow = $group.find('.exclude-row[data-exclude-index="' + currentExcludeIndex + '"]');
                    var $currentPicker = $currentExcludeRow.find('.exclude-picker');

                    // Get selected IDs from current exclude row
                    $currentPicker.find('.entity-chip').each(function() {
                        selectedIds.push(String($(this).data('id')));
                    });

                    // Get hidden IDs from OTHER exclude rows with the same entity type
                    $group.find('.exclude-row').each(function() {
                        var $row = $(this);
                        var rowIndex = parseInt($row.data('excludeIndex'), 10);

                        // Skip current exclude row
                        if (rowIndex === currentExcludeIndex) return;

                        var $picker = $row.find('.exclude-picker');
                        var rowEntityType = $picker.attr('data-search-entity') || self.activeGroup.blockType;

                        // Only collect if same entity type
                        if (rowEntityType === currentSearchEntity) {
                            $picker.find('.entity-chip').each(function() {
                                hiddenIds.push(String($(this).data('id')));
                            });
                        }
                    });
                }
            }

            // Check if this is a product search
            var isProductSearch = this.activeGroup && this.activeGroup.searchEntity === 'products';
            var isListView = this.viewMode === 'list';

            // Show/hide results header for products in list view
            this.$dropdown.find('.results-header').toggle(isProductSearch && isListView);

            // Build HTML - filter out items that are hidden (selected in sibling exclude rows)
            var visibleResults = this.searchResults.filter(function(item) {
                return hiddenIds.indexOf(String(item.id)) === -1;
            });

            // Update count (show visible count and total, noting hidden items if any)
            var hiddenCount = this.searchResults.length - visibleResults.length;
            var countText = visibleResults.length + ' / ' + this.searchTotal + ' results';
            if (hiddenCount > 0) {
                countText += ' (' + hiddenCount + ' hidden)';
            }
            this.$dropdown.find('.results-count').text(countText);

            var html = '';
            if (visibleResults.length === 0 && !appendMode) {
                html = '<div class="no-results">' + this.esIcon('search') + ' ' + (trans.no_results || 'No results found') + '</div>';
            } else {
                visibleResults.forEach(function(item) {
                    var isSelected = selectedIds.indexOf(String(item.id)) !== -1;
                    var itemClass = 'dropdown-item' + (isSelected ? ' selected' : '');
                    if (item.type === 'product') itemClass += ' result-item-product';

                    html += '<div class="' + itemClass + '" ';
                    html += 'data-id="' + self.escapeAttr(item.id) + '" ';
                    html += 'data-name="' + self.escapeAttr(item.name) + '"';
                    if (item.image) html += ' data-image="' + self.escapeAttr(item.image) + '"';
                    if (item.subtitle) html += ' data-subtitle="' + self.escapeAttr(item.subtitle) + '"';
                    if (item.iso_code) html += ' data-iso="' + self.escapeAttr(item.iso_code) + '"';
                    html += '>';

                    html += '<span class="result-checkbox">' + self.esIcon('check') + '</span>';

                    var searchEntity = self.activeGroup ? self.activeGroup.searchEntity : null;

                    // Countries show flags
                    if (searchEntity === 'countries' && item.iso_code) {
                        var flagUrl = 'https://flagcdn.com/w40/' + item.iso_code.toLowerCase() + '.png';
                        html += '<div class="result-image result-flag"><img src="' + self.escapeAttr(flagUrl) + '" alt="' + self.escapeAttr(item.iso_code) + '" onerror="this.style.display=\'none\';this.nextElementSibling.style.display=\'flex\';"><span class="flag-fallback" style="display:none;">' + self.esIcon('flag') + '</span></div>';
                    } else if (item.image) {
                        html += '<div class="result-image"><img src="' + self.escapeAttr(item.image) + '" alt=""></div>';
                    } else {
                        // Entity-specific icons
                        var iconName = 'widgets'; // default
                        if (searchEntity === 'categories') iconName = 'folder';
                        else if (searchEntity === 'manufacturers') iconName = 'business';
                        else if (searchEntity === 'suppliers') iconName = 'local_shipping';
                        else if (searchEntity === 'attributes') iconName = 'brush';
                        else if (searchEntity === 'features') iconName = 'list';
                        else if (searchEntity === 'cms') iconName = 'description';
                        else if (searchEntity === 'cms_categories') iconName = 'folder';
                        html += '<div class="result-icon">' + self.esIcon(iconName) + '</div>';
                    }

                    html += '<div class="result-info">';
                    html += '<div class="result-name">' + self.escapeHtml(item.name) + '</div>';
                    if (item.subtitle) {
                        // Split multi-line subtitles into separate divs for styling
                        var subtitleLines = item.subtitle.split('\n');
                        html += '<div class="result-subtitle">';
                        subtitleLines.forEach(function(line, idx) {
                            var lineClass = idx === 0 ? 'subtitle-line subtitle-line-primary' : 'subtitle-line subtitle-line-secondary';
                            html += '<div class="' + lineClass + '">' + self.escapeHtml(line) + '</div>';
                        });
                        html += '</div>';
                    }
                    html += '</div>';

                    // Add product-specific columns (price, sale price, stock, sold)
                    if (item.type === 'product') {
                        if (isListView) {
                            // List view: full columns
                            // Regular price
                            html += '<div class="result-col result-col-price">';
                            html += '<span class="col-value">' + (item.regular_price_formatted || item.price_formatted || '') + '</span>';
                            html += '</div>';

                            // Sale price (only if discounted)
                            if (item.has_discount) {
                                html += '<div class="result-col result-col-sale">';
                                html += '<span class="col-value">' + (item.price_formatted || '') + '</span>';
                                html += '</div>';
                            } else {
                                html += '<div class="result-col result-col-sale"></div>';
                            }

                            // Stock column
                            var stockClass = item.stock_status === 'out_of_stock' ? 'stock-out' :
                                             (item.stock_status === 'low_stock' ? 'stock-low' : 'stock-ok');
                            html += '<div class="result-col result-col-stock">';
                            html += '<span class="col-value ' + stockClass + '">' + (item.stock_qty !== undefined ? item.stock_qty : '') + '</span>';
                            html += '</div>';

                            // Sales column
                            html += '<div class="result-col result-col-sales">';
                            html += '<span class="col-value">' + (item.sales_qty !== undefined ? item.sales_qty : '0') + '</span>';
                            html += '</div>';
                        } else {
                            // Grid view: compact info line
                            var gridStockClass = item.stock_status === 'out_of_stock' ? 'stock-out' :
                                                 (item.stock_status === 'low_stock' ? 'stock-low' : '');
                            html += '<div class="result-grid-info">';
                            html += '<span class="grid-price">' + (item.price_formatted || '') + '</span>';
                            if (item.stock_qty !== undefined) {
                                html += '<span class="grid-stock ' + gridStockClass + '">' + item.stock_qty + ' qty</span>';
                            }
                            if (item.has_discount) {
                                html += '<span class="grid-discount">-' + (item.discount_percent || '') + '%</span>';
                            }
                            html += '</div>';
                        }
                    }

                    html += '</div>';
                });
            }

            if (appendMode) {
                $container.append(html);
            } else {
                $container.html(html);
            }

            // Show/hide load more controls and update remaining count
            var hasMore = this.searchResults.length < this.searchTotal;
            var $loadMoreControls = this.$dropdown.find('.load-more-controls');
            $loadMoreControls.toggle(hasMore);

            if (hasMore) {
                var remaining = this.searchTotal - this.searchResults.length;
                $loadMoreControls.find('.remaining-count').text(remaining);

                // Update "All" option in dropdown
                var $select = $loadMoreControls.find('.load-more-select');
                var $allOption = $select.find('option[data-all="true"]');
                if ($allOption.length) {
                    $allOption.val(remaining).text((trans.all || 'All') + ' (' + remaining + ')');
                } else {
                    $select.find('option:last').after('<option value="' + remaining + '" data-all="true">' + (trans.all || 'All') + ' (' + remaining + ')</option>');
                }
            }

            // Ensure dropdown-actions are visible and history button is deactivated
            this.$dropdown.find('.dropdown-actions').show();
            this.$dropdown.find('.btn-show-history').removeClass('active');

            // Disable history button if no search history for current entity type
            var entityType = this.activeGroup ? this.activeGroup.searchEntity : null;
            var hasHistory = entityType && this.getSearchHistory(entityType).length > 0;
            this.$dropdown.find('.btn-show-history').prop('disabled', !hasHistory);
        },

        // NOTE: Tree methods (loadCategoryTree, renderCategoryTree, filterCategoryTree,
        // findTreeDescendants, findTreeAncestors, updateSelectChildrenButtons) are
        // defined in _tree.js which is merged later and takes precedence.

        // =========================================================================
        // Search History
        // =========================================================================

        loadSearchHistory: function() {
            try {
                var stored = localStorage.getItem(this.searchHistoryKey);
                this.searchHistory = stored ? JSON.parse(stored) : {};
            } catch (e) {
                this.searchHistory = {};
            }
        },

        saveSearchHistory: function() {
            try {
                localStorage.setItem(this.searchHistoryKey, JSON.stringify(this.searchHistory));
            } catch (e) {
                // localStorage might be full or unavailable
            }
        },

        addToSearchHistory: function(entityType, query) {
            if (!query || query.length < 2) return;

            if (!this.searchHistory[entityType]) {
                this.searchHistory[entityType] = [];
            }

            var history = this.searchHistory[entityType];

            // Remove if already exists (will re-add at top)
            var existingIndex = history.indexOf(query);
            if (existingIndex !== -1) {
                history.splice(existingIndex, 1);
            }

            // Add at beginning
            history.unshift(query);

            // Trim to max
            if (history.length > this.searchHistoryMax) {
                history = history.slice(0, this.searchHistoryMax);
            }

            this.searchHistory[entityType] = history;
            this.saveSearchHistory();
        },

        removeFromSearchHistory: function(entityType, query) {
            if (!this.searchHistory[entityType]) return;

            var index = this.searchHistory[entityType].indexOf(query);
            if (index !== -1) {
                this.searchHistory[entityType].splice(index, 1);
                this.saveSearchHistory();
            }
        },

        getSearchHistory: function(entityType) {
            return this.searchHistory[entityType] || [];
        },

        showSearchHistory: function(entityType) {
            var history = this.getSearchHistory(entityType);
            var trans = this.config.trans || {};
            var $container = this.$dropdown.find('.dropdown-results');

            // Update header
            this.$dropdown.find('.results-count').text(trans.recent_searches || 'Recent searches');

            // Hide filters, actions, and results header for history view
            this.$dropdown.find('.dropdown-actions').hide();
            this.$dropdown.find('.filter-panel').removeClass('show');
            this.$dropdown.find('.btn-toggle-filters').removeClass('active');
            this.$dropdown.find('.results-header').hide();

            if (!history.length) {
                // No history - just do a regular search
                this.performSearch();
                return;
            }

            // Build history items
            var html = '<div class="search-history-list">';
            for (var i = 0; i < history.length; i++) {
                var query = history[i];
                html += '<div class="history-item" data-query="' + this.escapeAttr(query) + '">';
                html += this.esIcon('schedule');
                html += '<span class="history-query">' + this.escapeHtml(query) + '</span>';
                html += '<button type="button" class="btn-delete-history" title="' + (trans.remove || 'Remove') + '">';
                html += this.esIcon('close');
                html += '</button>';
                html += '</div>';
            }
            html += '</div>';

            $container.html(html);
            this.$dropdown.addClass('show');
        },

        // =========================================================================
        // Filter Methods
        // =========================================================================

        refreshSearch: function() {
            // In tree view mode, re-filter the tree instead of doing a flat AJAX search
            if (this.viewMode === 'tree') {
                this.filterCategoryTree(this.searchQuery || '');
                return;
            }

            this.searchOffset = 0;
            this.loadMoreCount = 20;
            // Reset load more select to default
            if (this.$dropdown) {
                this.$dropdown.find('.load-more-select').val('20');
                // Remove the dynamic "All" option
                this.$dropdown.find('.load-more-select option[data-all="true"]').remove();
            }
            this.performSearch(false);
        },

        clearFilters: function() {
            this.refineQuery = '';
            this.refineNegate = false;
            this.filters = {
                inStock: false,
                discounted: false,
                priceMin: null,
                priceMax: null,
                attributes: [],
                features: [],
                // Entity-specific filters
                productCountMin: null,
                productCountMax: null,
                salesMin: null,
                salesMax: null,
                turnoverMin: null,
                turnoverMax: null,
                depth: null,
                hasProducts: false,
                hasDescription: false,
                hasImage: false,
                activeOnly: true,
                attributeGroup: null,
                featureGroup: null,
                dateAddFrom: null,
                dateAddTo: null,
                lastProductFrom: null,
                lastProductTo: null,
                // Country-specific filters
                hasHolidays: false,
                containsStates: false,
                zone: null
            };

            if (this.$dropdown) {
                var trans = this.config.trans || {};
                this.$dropdown.find('.refine-input').val('').attr('placeholder', trans.refine_short || 'Refine...');
                this.$dropdown.find('.btn-clear-refine').hide();
                this.$dropdown.find('.btn-refine-negate').removeClass('active');
                this.$dropdown.find('.filter-in-stock').prop('checked', false);
                this.$dropdown.find('.filter-discounted').prop('checked', false);
                this.$dropdown.find('.filter-price-min').val('');
                this.$dropdown.find('.filter-price-max').val('');
                this.$dropdown.find('.filter-attr-chip').removeClass('active');
                this.$dropdown.find('.filter-feat-chip').removeClass('active');
                this.$dropdown.find('.filter-group-toggle').removeClass('active has-selection');
                this.$dropdown.find('.filter-row-values').hide();

                // Clear entity-specific filter inputs
                this.$dropdown.find('.filter-product-count-min, .filter-product-count-max').val('');
                this.$dropdown.find('.filter-sales-min, .filter-sales-max').val('');
                this.$dropdown.find('.filter-turnover-min, .filter-turnover-max').val('');
                this.$dropdown.find('.filter-date-add-from, .filter-date-add-to').val('');
                this.$dropdown.find('.filter-last-product-from, .filter-last-product-to').val('');
                this.$dropdown.find('.filter-depth-select').val('');
                this.$dropdown.find('.filter-has-products').prop('checked', false);
                this.$dropdown.find('.filter-has-description').prop('checked', false);
                this.$dropdown.find('.filter-has-image').prop('checked', false);
                this.$dropdown.find('.filter-active-only').prop('checked', true);
                this.$dropdown.find('.filter-attribute-group-select, .filter-feature-group-select').val('');
                // Country filters
                this.$dropdown.find('.filter-has-holidays').prop('checked', false);
                this.$dropdown.find('.filter-contains-states').prop('checked', false);
                this.$dropdown.find('.filter-zone-select').val('');
            }

            this.refreshSearch();
        },

        // Reset filters without triggering a search (used when switching entity types)
        resetFiltersWithoutSearch: function() {
            this.refineQuery = '';
            this.refineNegate = false;
            this.filters = {
                inStock: false,
                discounted: false,
                priceMin: null,
                priceMax: null,
                attributes: [],
                features: [],
                productCountMin: null,
                productCountMax: null,
                salesMin: null,
                salesMax: null,
                turnoverMin: null,
                turnoverMax: null,
                depth: null,
                hasProducts: false,
                hasDescription: false,
                hasImage: false,
                activeOnly: true,
                attributeGroup: null,
                featureGroup: null,
                dateAddFrom: null,
                dateAddTo: null,
                lastProductFrom: null,
                lastProductTo: null,
                // Country-specific filters
                hasHolidays: false,
                containsStates: false,
                zone: null
            };

            if (this.$dropdown) {
                var trans = this.config.trans || {};
                this.$dropdown.find('.refine-input').val('').attr('placeholder', trans.refine_short || 'Refine...');
                this.$dropdown.find('.btn-clear-refine').hide();
                this.$dropdown.find('.btn-refine-negate').removeClass('active');
                this.$dropdown.find('.filter-in-stock').prop('checked', false);
                this.$dropdown.find('.filter-discounted').prop('checked', false);
                this.$dropdown.find('.filter-price-min').val('');
                this.$dropdown.find('.filter-price-max').val('');
                this.$dropdown.find('.filter-attr-chip').removeClass('active');
                this.$dropdown.find('.filter-feat-chip').removeClass('active');
                this.$dropdown.find('.filter-group-toggle').removeClass('active has-selection');
                this.$dropdown.find('.filter-row-values').hide();
                this.$dropdown.find('.filter-product-count-min, .filter-product-count-max').val('');
                this.$dropdown.find('.filter-sales-min, .filter-sales-max').val('');
                this.$dropdown.find('.filter-turnover-min, .filter-turnover-max').val('');
                this.$dropdown.find('.filter-date-add-from, .filter-date-add-to').val('');
                this.$dropdown.find('.filter-last-product-from, .filter-last-product-to').val('');
                this.$dropdown.find('.filter-depth-select').val('');
                this.$dropdown.find('.filter-has-products').prop('checked', false);
                this.$dropdown.find('.filter-has-description').prop('checked', false);
                this.$dropdown.find('.filter-has-image').prop('checked', false);
                this.$dropdown.find('.filter-active-only').prop('checked', true);
                this.$dropdown.find('.filter-attribute-group-select, .filter-feature-group-select').val('');
                // Country filters
                this.$dropdown.find('.filter-has-holidays').prop('checked', false);
                this.$dropdown.find('.filter-contains-states').prop('checked', false);
                this.$dropdown.find('.filter-zone-select').val('');
            }
            // Note: Does NOT call refreshSearch() - caller handles search/load
        },

        updateFilterPanelForEntity: function(entityType) {
            if (!this.$dropdown) {
                return;
            }

            var $panel = this.$dropdown.find('.filter-panel');

            // Hide all filter rows first
            $panel.find('.filter-row').hide();

            // Show/hide tree view option based on entity type
            var $treeOption = this.$dropdown.find('.view-mode-select option.tree-view-option');
            if (entityType === 'categories' || entityType === 'cms_categories') {
                $treeOption.prop('disabled', false).prop('hidden', false);
                // Auto-switch to tree view for categories
                if (this.viewMode !== 'tree') {
                    this.viewMode = 'tree';
                    this.$dropdown.find('.view-mode-select').val('tree');
                    this.$dropdown.removeClass('view-list view-cols-2 view-cols-3 view-cols-4 view-cols-5 view-cols-6 view-cols-7 view-cols-8').addClass('view-tree');
                    this.loadCategoryTree();
                } else {
                    this.loadCategoryTree();
                }
            } else {
                $treeOption.prop('disabled', true).prop('hidden', true);
                // If currently in tree mode, switch back to list
                if (this.viewMode === 'tree') {
                    this.viewMode = 'list';
                    this.$dropdown.find('.view-mode-select').val('list');
                    this.$dropdown.removeClass('view-tree').addClass('view-list');
                }
            }

            // Show entity-specific filter row (prepare visibility, but don't auto-expand panel)
            if (entityType === 'products') {
                // Prepare the correct rows to be visible when panel is shown
                $panel.find('.filter-row-quick').show();
                // Show attribute/feature rows if we have cached data
                if (this.filterableData) {
                    if (this.filterableData.attributes && this.filterableData.attributes.length > 0) {
                        this.$dropdown.find('.filter-row-attributes').show();
                    }
                    if (this.filterableData.features && this.filterableData.features.length > 0) {
                        this.$dropdown.find('.filter-row-features').show();
                    }
                }
            } else if (entityType === 'categories') {
                $panel.find('.filter-row-entity-categories').show();
            } else if (entityType === 'manufacturers') {
                $panel.find('.filter-row-entity-manufacturers').show();
            } else if (entityType === 'suppliers') {
                $panel.find('.filter-row-entity-suppliers').show();
            } else if (entityType === 'attributes') {
                $panel.find('.filter-row-entity-attributes').show();
                this.loadAttributeGroups();
            } else if (entityType === 'features') {
                $panel.find('.filter-row-entity-features').show();
            } else if (entityType === 'cms') {
                $panel.find('.filter-row-entity-cms').show();
            } else if (entityType === 'cms_categories') {
                $panel.find('.filter-row-entity-cms-categories').show();
            } else if (entityType === 'countries') {
                $panel.find('.filter-row-entity-countries').show();
                this.loadZonesForCountryFilter();
            }
        },

        loadAttributeGroups: function() {
            var self = this;
            var $select = this.$dropdown.find('.filter-attribute-group-select');

            // Already loaded?
            if ($select.find('option').length > 1) return;

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    ajax: 1,
                    action: 'getAttributeGroups',
                    trait: 'EntitySelector'
                },
                success: function(response) {
                    if (response.success && response.groups) {
                        $.each(response.groups, function(i, group) {
                            $select.append('<option value="' + group.id + '">' + self.escapeHtml(group.name) + ' (' + group.count + ')</option>');
                        });
                    }
                }
            });
        },

        loadFeatureGroups: function() {
            var self = this;
            var $select = this.$dropdown.find('.filter-feature-group-select');

            // Already loaded?
            if ($select.find('option').length > 1) return;

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    ajax: 1,
                    action: 'getFeatureGroups',
                    trait: 'EntitySelector'
                },
                success: function(response) {
                    if (response.success && response.groups) {
                        $.each(response.groups, function(i, group) {
                            $select.append('<option value="' + group.id + '">' + self.escapeHtml(group.name) + ' (' + group.count + ')</option>');
                        });
                    }
                }
            });
        }
    };

})(jQuery);
