/**
 * Entity Selector - Core Module
 * Factory, initialization, state management
 * @partial _core.js
 *
 * IMPORTANT: This file must be loaded LAST in the concatenation order
 * as it combines all mixins from other partials.
 *
 * EXTRACTION SOURCE: assets/js/admin/entity-selector.js
 * Lines: 15-55 (createTargetConditionsInstance, state variables)
 *        56-110 (init method)
 *        108-132 (observeNewSelects)
 *        7889-7951 (Factory object, window export, document ready)
 *
 * Contains:
 * - createTargetConditionsInstance() - Factory function
 * - State variable initialization
 * - init() - Main initialization method
 * - observeNewSelects() - MutationObserver for dynamic selects
 * - loadExistingSelections() - Restore saved state
 * - TargetConditions factory object
 * - window.TargetConditions export
 * - Document ready auto-initialization
 */

(function($) {
    'use strict';

    /**
     * Create a new TargetConditions instance
     * Each instance is independent and manages its own wrapper/state
     */
    function createTargetConditionsInstance() {
        // Base instance object with state variables
        var instance = {
            config: {},
            $wrapper: null,
            $dropdown: null,
            activeGroup: null, // { blockType, groupIndex, section: 'include'|'exclude' }
            searchTimeout: null,
            searchResults: [],
            searchTotal: 0,
            searchOffset: 0,
            searchQuery: '',
            isLoading: false,
            loadMoreCount: 20,
            // Sort, filter, view state
            viewMode: 'list',
            currentSort: { field: 'name', dir: 'ASC' },
            refineQuery: '',
            refineNegate: false,
            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, // Default to active only
                attributeGroup: null,
                featureGroup: null,
                dateAddFrom: null,
                dateAddTo: null,
                lastProductFrom: null,
                lastProductTo: null,
                // Country-specific filters
                hasHolidays: false,
                containsStates: false,
                zone: null
            },
            filterableData: null,
            // Search history
            searchHistory: {},
            searchHistoryMax: 10,
            searchHistoryKey: 'targetConditionsSearchHistory',
            // Chips visibility
            maxVisibleChips: 20,
            // Method dropdown references
            $methodDropdownMenu: null,
            $methodDropdownSelect: null,
            $methodDropdownTrigger: null,
            // Preview state
            $previewPopover: null,
            $activeBadge: null,
            $previewList: null,
            previewLoadedCount: 0,
            previewBlockType: null,
            allPreviewData: null,
            // Count update timeout
            countUpdateTimeout: null,

            init: function(options) {
                this.config = $.extend({
                    id: 'target-conditions',
                    name: 'target_conditions',
                    namePrefix: 'target_',
                    mode: 'multi', // Global mode: 'multi' or 'single'
                    blocks: {},
                    ajaxUrl: '',
                    trans: {}
                }, options);

                this.$wrapper = $('[data-entity-selector-id="' + this.config.id + '"]');

                if (!this.$wrapper.length) {
                    return;
                }

                // Global single mode - hide "Add Group" buttons
                if (this.config.mode === 'single') {
                    this.$wrapper.find('.btn-add-group').hide();
                    this.$wrapper.find('.group-excludes').hide();
                    this.$wrapper.find('.group-modifiers').hide();
                }

                // Add fullwidth class to parent form-group (skip for form-group layout)
                var hasLayoutFormGroup = this.$wrapper.hasClass('layout-form-group');
                var $entitySelectorFormGroup = this.$wrapper.closest('.entity-selector-form-group');

                if (!hasLayoutFormGroup && !$entitySelectorFormGroup.length) {
                    var $formGroup = this.$wrapper.closest('.form-group');
                    $formGroup.addClass('condition-trait-fullwidth');
                    $formGroup.find('.col-lg-offset-3').removeClass('col-lg-offset-3');
                }

                this.createDropdown();
                this.bindEvents();
                this.loadExistingSelections();
                this.loadSearchHistory();

                // Initialize styled method dropdowns
                this.initMethodDropdowns();

                // Watch for dynamically added selects
                this.observeNewSelects();

                // Update counts on page load
                var self = this;
                setTimeout(function() {
                    self.updateTabBadges();
                    self.updateAllConditionCounts();
                }, 100);
            },

            observeNewSelects: function() {
                var self = this;

                if (typeof MutationObserver === 'undefined') {
                    return;
                }

                var observer = new MutationObserver(function(mutations) {
                    mutations.forEach(function(mutation) {
                        if (mutation.addedNodes.length) {
                            $(mutation.addedNodes).find('.include-method-select, .exclude-method-select').each(function() {
                                self.enhanceMethodSelect($(this));
                            });
                        }
                    });
                });

                observer.observe(this.$wrapper[0], {
                    childList: true,
                    subtree: true
                });
            },

            loadExistingSelections: function() {
                // TODO: Extract full implementation from original
                // Reads JSON from hidden input and populates chips
            }
        };

        // Merge all mixins into the instance
        // Each mixin adds its methods to window._EntitySelectorMixins
        var mixins = window._EntitySelectorMixins || {};

        // Merge utils mixin
        if (mixins.utils) {
            $.extend(instance, mixins.utils);
        }

        // Merge events mixin
        if (mixins.events) {
            $.extend(instance, mixins.events);
        }

        // Merge dropdown mixin
        if (mixins.dropdown) {
            $.extend(instance, mixins.dropdown);
        }

        // Merge search mixin
        if (mixins.search) {
            $.extend(instance, mixins.search);
        }

        // Merge filters mixin
        if (mixins.filters) {
            $.extend(instance, mixins.filters);
        }

        // Merge chips mixin
        if (mixins.chips) {
            $.extend(instance, mixins.chips);
        }

        // Merge groups mixin
        if (mixins.groups) {
            $.extend(instance, mixins.groups);
        }

        // Merge methods mixin
        if (mixins.methods) {
            $.extend(instance, mixins.methods);
        }

        // Merge preview mixin
        if (mixins.preview) {
            $.extend(instance, mixins.preview);
        }

        // Merge tree mixin
        if (mixins.tree) {
            $.extend(instance, mixins.tree);
        }

        // Merge validation mixin
        if (mixins.validation) {
            $.extend(instance, mixins.validation);
        }

        return instance;
    }

    // Factory object for creating and managing instances
    var TargetConditions = {
        instances: [],

        // Create and initialize a new instance
        create: function(options) {
            var instance = createTargetConditionsInstance();
            instance.init(options);
            this.instances.push(instance);
            return instance;
        },

        // For backwards compatibility - init creates a new instance
        init: function(options) {
            return this.create(options);
        },

        // Validate all instances - returns true if all valid
        validateAll: function() {
            var allValid = true;
            for (var i = 0; i < this.instances.length; i++) {
                if (!this.instances[i].validate()) {
                    allValid = false;
                }
            }
            return allValid;
        }
    };

    // Export to window
    window.TargetConditions = TargetConditions;

    // Auto-initialize on document ready
    $(document).ready(function() {
        // Auto-initialize from data-config attributes on wrapper elements
        $('[data-entity-selector-id]').each(function() {
            var configData = $(this).data('config');
            if (configData) {
                TargetConditions.create(configData);
            }
        });

        // Tips box toggle handler
        $(document).on('click', '.target-tips-box .tips-header', function(e) {
            e.preventDefault();
            $(this).closest('.target-tips-box').toggleClass('expanded');
        });

        // Form submission validation for required target conditions
        $(document).on('submit', 'form', function(e) {
            var $form = $(this);
            if ($form.find('.target-conditions-trait[data-required]').length > 0) {
                if (!TargetConditions.validateAll()) {
                    e.preventDefault();
                    return false;
                }
            }
        });
    });

})(jQuery);
