/**
 * Entity Selector - Filters Module
 * Filter panel, filter state management
 * @partial _filters.js
 *
 * EXTRACTION SOURCE: assets/js/admin/entity-selector.js
 * Lines: 6605-6758 (filter methods)
 *
 * Contains:
 * - clearFilters() - Reset all filters
 * - resetFiltersWithoutSearch() - Reset without triggering search
 * - updateFilterPanelForEntity() - Show/hide filters based on entity type
 * - loadFilterableData() - Load attributes/features for filter panel
 * - renderFilterDropdowns() - Render attribute/feature group toggles
 * - showFilterGroupValues() - Show values for a filter group
 * - hideFilterGroupValues() - Hide filter values row
 * - updateFilterToggleStates() - Update toggle states based on selections
 */

(function($) {
    'use strict';

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

    window._EntitySelectorMixins.filters = {

        clearFilters: 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('');
                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, .filter-price-max').val('');
                this.$dropdown.find('.filter-attr-chip, .filter-feat-chip').removeClass('active');
                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-depth-select').val('');
                this.$dropdown.find('.filter-has-products').prop('checked', false);
                this.$dropdown.find('.filter-active-only').prop('checked', true);
                // 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();
        },

        resetFiltersWithoutSearch: function() {
            // Same as clearFilters but doesn't trigger search
            // Used when switching entity types
            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
            };
        },

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

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

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

            // Show filters for current entity type
            $panel.find('.filter-row[data-entity="' + entityType + '"]').show();
            $panel.find('.filter-row-entity-' + entityType.replace('_', '-')).show();

            // Show/hide tree view option based on entity type
            var isCategory = (entityType === 'categories' || entityType === 'cms_categories');
            this.$dropdown.find('.tree-view-option').toggle(isCategory);

            // Default to tree view for categories (only if currently on list mode)
            if (isCategory && this.viewMode === 'list') {
                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');
            } else if (!isCategory && this.viewMode === 'tree') {
                // If switching away from categories while in tree mode, switch to list
                this.viewMode = 'list';
                this.$dropdown.find('.view-mode-select').val('list');
                this.$dropdown.removeClass('view-tree view-cols-2 view-cols-3 view-cols-4 view-cols-5 view-cols-6 view-cols-7 view-cols-8').addClass('view-list');
            }

            // Load zones for countries filter
            if (entityType === 'countries') {
                this.loadZonesForCountryFilter();
            }

            // Update sort options for entity type
            this.updateSortOptionsForEntity(entityType);
        },

        /**
         * Show/hide sort options based on entity type
         * Options with data-entities attribute are only shown for matching entities
         */
        updateSortOptionsForEntity: function(entityType) {
            if (!this.$dropdown) {
                return;
            }

            var $select = this.$dropdown.find('.sort-field-select');
            var currentValue = $select.val();
            var hasCurrentOption = false;

            $select.find('option').each(function() {
                var $option = $(this);
                var entities = $option.data('entities');

                // Options without data-entities are universal (always shown)
                if (!entities) {
                    $option.show();
                    if ($option.val() === currentValue) {
                        hasCurrentOption = true;
                    }
                    return;
                }

                // Check if this entity type is in the allowed list
                var allowedEntities = entities.split(',');
                var isAllowed = allowedEntities.indexOf(entityType) !== -1;

                $option.toggle(isAllowed);

                if (isAllowed && $option.val() === currentValue) {
                    hasCurrentOption = true;
                }
            });

            // If current sort field is not available for this entity, reset to 'name'
            if (!hasCurrentOption) {
                $select.val('name');
                this.currentSort.field = 'name';
            }
        },

        loadFilterableData: function() {
            var self = this;

            if (this.filterableData) {
                this.renderFilterDropdowns();
                return;
            }

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    ajax: 1,
                    action: 'getTargetFilterableAttributes',
                    trait: 'EntitySelector'
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data) {
                        self.filterableData = response.data;
                        self.renderFilterDropdowns();
                    }
                }
            });
        },

        renderFilterDropdowns: function() {
            if (!this.$dropdown || !this.filterableData) return;

            var self = this;

            // Render attribute group toggle buttons
            var $attrContainer = this.$dropdown.find('.filter-attributes-container');
            $attrContainer.empty();

            if (this.filterableData.attributes && this.filterableData.attributes.length > 0) {
                this.filterableData.attributes.forEach(function(group) {
                    var html = '<button type="button" class="filter-group-toggle" data-group-id="' + group.id + '" data-type="attribute" data-group-name="' + self.escapeAttr(group.name) + '">';
                    html += '<span class="toggle-name">' + group.name + '</span>';
                    if (group.count !== undefined) {
                        html += '<span class="toggle-count clickable" data-group-id="' + group.id + '" data-type="attribute" data-group-name="' + self.escapeAttr(group.name) + '">' + self.esIcon('visibility') + ' ' + group.count + '</span>';
                    }
                    html += '</button>';
                    $attrContainer.append(html);
                });
                this.$dropdown.find('.filter-row-attributes').show();
            }

            // Render feature group toggle buttons
            var $featContainer = this.$dropdown.find('.filter-features-container');
            $featContainer.empty();

            if (this.filterableData.features && this.filterableData.features.length > 0) {
                this.filterableData.features.forEach(function(group) {
                    var html = '<button type="button" class="filter-group-toggle" data-group-id="' + group.id + '" data-type="feature" data-group-name="' + self.escapeAttr(group.name) + '">';
                    html += '<span class="toggle-name">' + group.name + '</span>';
                    if (group.count !== undefined) {
                        html += '<span class="toggle-count clickable" data-group-id="' + group.id + '" data-type="feature" data-group-name="' + self.escapeAttr(group.name) + '">' + self.esIcon('visibility') + ' ' + group.count + '</span>';
                    }
                    html += '</button>';
                    $featContainer.append(html);
                });
                this.$dropdown.find('.filter-row-features').show();
            }
        },

        showFilterGroupValues: function(groupId, type) {
            if (!this.filterableData) return;

            var self = this;
            var groups = type === 'attribute' ? this.filterableData.attributes : this.filterableData.features;
            var group = groups.find(function(g) { return g.id == groupId; });

            if (!group) return;

            // Hide all values rows first, then show the correct one
            this.$dropdown.find('.filter-row-values').hide();

            // Target the correct values row based on type
            var valuesRowClass = type === 'attribute' ? '.filter-row-attr-values' : '.filter-row-feat-values';
            var $filterRowValues = this.$dropdown.find(valuesRowClass);
            var $valuesContainer = $filterRowValues.find('.filter-values-container');
            $valuesContainer.empty();

            // Add group label
            var html = '<span class="filter-values-label">' + group.name + ':</span>';

            // Add chips
            group.values.forEach(function(val) {
                var isActive = type === 'attribute'
                    ? self.filters.attributes.indexOf(val.id) !== -1
                    : self.filters.features.indexOf(val.id) !== -1;
                var activeClass = isActive ? ' active' : '';
                var chipClass = type === 'attribute' ? 'filter-attr-chip' : 'filter-feat-chip';
                var colorStyle = val.color ? ' style="--chip-color: ' + val.color + '"' : '';
                var colorClass = val.color ? ' has-color' : '';

                html += '<button type="button" class="filter-chip ' + chipClass + activeClass + colorClass + '" data-id="' + val.id + '" data-group-id="' + groupId + '"' + colorStyle + '>';
                if (val.color) {
                    html += '<span class="chip-color-dot"></span>';
                }
                html += '<span class="chip-name">' + val.name + '</span>';
                if (val.count !== undefined) {
                    html += '<span class="chip-count">(' + val.count + ')</span>';
                }
                html += '</button>';
            });

            $valuesContainer.html(html);

            // Add close button as sibling (outside filter-values-container, inside filter-row-values)
            $filterRowValues.find('.btn-close-values').remove();
            $filterRowValues.append('<button type="button" class="btn-close-values">' + this.esIcon('close') + '</button>');
            $filterRowValues.show();

            // Scroll into view if needed
            var rowValues = $filterRowValues[0];
            if (rowValues) {
                rowValues.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
        },

        hideFilterGroupValues: function() {
            this.$dropdown.find('.filter-row-values').hide();
            this.$dropdown.find('.filter-group-toggle').removeClass('active');
        },

        updateFilterToggleStates: function() {
            if (!this.$dropdown || !this.filterableData) return;

            var self = this;

            // Update attribute group toggles
            if (this.filterableData.attributes) {
                this.filterableData.attributes.forEach(function(group) {
                    var $toggle = self.$dropdown.find('.filter-group-toggle[data-group-id="' + group.id + '"][data-type="attribute"]');
                    var hasActiveInGroup = group.values.some(function(val) {
                        return self.filters.attributes.indexOf(val.id) !== -1;
                    });
                    $toggle.toggleClass('has-selection', hasActiveInGroup);
                });
            }

            // Update feature group toggles
            if (this.filterableData.features) {
                this.filterableData.features.forEach(function(group) {
                    var $toggle = self.$dropdown.find('.filter-group-toggle[data-group-id="' + group.id + '"][data-type="feature"]');
                    var hasActiveInGroup = group.values.some(function(val) {
                        return self.filters.features.indexOf(val.id) !== -1;
                    });
                    $toggle.toggleClass('has-selection', hasActiveInGroup);
                });
            }
        },

        /**
         * Load zones for country filter dropdown
         */
        loadZonesForCountryFilter: function() {
            var self = this;

            if (this.zonesLoaded || !this.$dropdown) {
                return;
            }

            var $select = this.$dropdown.find('.filter-zone-select');
            if (!$select.length) {
                return;
            }

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    ajax: 1,
                    action: 'getZonesForFilter',
                    trait: 'EntitySelector'
                },
                success: function(response) {
                    if (response.success && response.zones && response.zones.length > 0) {
                        var trans = self.config.trans || {};
                        $select.empty();
                        $select.append('<option value="">' + (trans.all_zones || 'All zones') + '</option>');

                        response.zones.forEach(function(zone) {
                            $select.append('<option value="' + zone.id + '">' + self.escapeHtml(zone.name) + '</option>');
                        });

                        self.zonesLoaded = true;
                    }
                }
            });
        }
    };

})(jQuery);
