define([
    'jquery',
    'uiRegistry',
    'Magento_Ui/js/form/element/ui-select'
], function ($, registry, UiSelect) {
    'use strict';

    return UiSelect.extend({
        initialize: function () {
            this._super();
            this._ensureArrayValue();

            this._defaultLevelsVisibility = this._getLevelsVisibility();

            this._isLoadingOptions = false;
            this._initStoreListener();
            this._initDropdownListener();
            this._initGridReloadListener();

            return this;
        },

        isLabelDecoration: function () {
            return false;
        },

        isSelected: function (value) {
            this._ensureArrayValue();

            var currentValue = this.value(),
                strValue = String(value);

            if (!Array.isArray(currentValue)) {
                return false;
            }

            return currentValue.some(function (item) {
                return String(item) === strValue;
            });
        },

        isSelectedValue: function (option) {
            if (!option) {
                return false;
            }

            return this.isSelected(option.value);
        },

        getSelected: function () {
            this._ensureArrayValue();

            var selectedValues = this.value(),
                valueMap = {},
                flat = [],
                result = [];

            if (!Array.isArray(selectedValues) || !selectedValues.length) {
                return [];
            }

            selectedValues.forEach(function (val) {
                valueMap[String(val)] = true;
            });

            this._flattenOptions(this.options(), flat);

            flat.forEach(function (opt) {
                if (!opt || opt.value === null || opt.value === undefined) {
                    return;
                }

                if (valueMap[String(opt.value)]) {
                    result.push(opt);
                }
            });

            return result;
        },

        _flattenOptions: function (options, output) {
            if (!Array.isArray(options)) {
                return;
            }

            options.forEach(function (opt) {
                if (!opt) {
                    return;
                }

                output.push(opt);

                if (Array.isArray(opt.optgroup) && opt.optgroup.length) {
                    this._flattenOptions(opt.optgroup, output);
                }
            }, this);
        },

        /**
         * Reinitialize category options when the grid reloads.
         */
        _initGridReloadListener: function () {
            if (this._gridReloadBound) {
                return;
            }

            if (!this.ns) {
                return;
            }

            var dataSourceName = this.ns + '.' + this.ns + '_data_source',
                self = this;

            var dataSource = registry.get(dataSourceName);
            if (!dataSource || typeof dataSource.on !== 'function') {
                return;
            }

            this._gridReloadBound = true;

            dataSource.on('reload', function () {
                window.setTimeout(function () {
                    self._reloadCategoryOptions();
                }, 0);
            });
        },

        /**
         * Remove selected item from value array with type normalization
         */
        removeSelected: function (value) {
            var currentValue = this.value(),
                strValue = String(value);

            if (!Array.isArray(currentValue)) {
                return this;
            }

            this.value(currentValue.filter(function (item) {
                return String(item) !== strValue;
            }));

            return this;
        },

        toggleOptionSelected: function (data, index, event) {
            var option = (data && data.option) ? data.option : data,
                value = option ? option.value : null,
                current;

            if (option && option.optgroup) {
                if (value === null || value === undefined || value === '') {
                    return this;
                }

                value = String(value);

                this._ensureArrayValue();
                current = this.value();

                if (!Array.isArray(current)) {
                    current = [];
                }

                if (current.indexOf(value) === -1) {
                    current.push(value);
                } else {
                    current = current.filter(function (item) {
                        return String(item) !== value;
                    });
                }

                this.value(current);

                return this;
            }

            return this._super(data, index, event);
        },

        onUpdate: function () {
            this._ensureArrayValue();
            return this._super();
        },

        onFocusIn: function (data, event) {
            var options = this.options(),
                self = this;

            if (Array.isArray(options)) {
                var openAll = function (opts) {
                    opts.forEach(function (opt) {
                        if (opt && opt.optgroup && Array.isArray(opt.optgroup) && opt.optgroup.length) {
                            // Directly set visible observable to true
                            if (opt.visible && typeof opt.visible === 'function') {
                                opt.visible(true);
                            } else {
                                opt.visible = true;
                            }
                            // Also try showLevels if it exists
                            if (typeof self.showLevels === 'function') {
                                self.showLevels(opt);
                            }
                            // Recursively open children
                            openAll(opt.optgroup);
                        }
                    });
                };
                openAll(options);
            }
            
            return this._super(data, event);
        },

        _ensureArrayValue: function () {
            if (!this.multiple) {
                return;
            }

            var value = this.value();

            if (value === undefined || value === null || value === '') {
                this.value([]);
                return;
            }

            if (!Array.isArray(value)) {
                this.value([value]);
            }
        },

        /**
         * Listen for store view changes and refresh available category options.
         */
        _initStoreListener: function () {
            var storeComponentName = this.storeComponent,
                storeComponent;

            if (!storeComponentName) {
                return;
            }

            storeComponent = registry.get(storeComponentName);

            if (!storeComponent || !storeComponent.value || !storeComponent.value.subscribe) {
                return;
            }

            storeComponent.value.subscribe(function () {
                this.value([]); // Keep selected categories to update labels based on new store
                this._reloadCategoryOptions();
            }, this);

            this._reloadCategoryOptions();
        },

        _initDropdownListener: function () {
            if (!this.listVisible || !this.listVisible.subscribe) {
                return;
            }

            this.listVisible.subscribe(function (visible) {
                if (visible) {
                    if (this.expandOnOpen) {
                        this.expandAll();
                    }
                }
            }, this);
        },

        _reloadCategoryOptions: function () {
            var storeId = this._getCurrentStoreId(),
                url = this.categoriesUrl;

            if (!url) {
                return;
            }

            if (this._isLoadingOptions) {
                return;
            }

            this._isLoadingOptions = true;

            this.loading(true);

            $.ajax({
                url: url,
                type: 'GET',
                data: {
                    store_id: storeId,
                    form_key: window.FORM_KEY
                },
                dataType: 'json',
                showLoader: false
            }).done(function (response) {
                if (response && response.success && Array.isArray(response.options)) {
                    this.options(response.options);

                    if (typeof this.cacheOptions === 'function') {
                        this.cacheOptions();
                    }

                    // Update active filters to reflect new category labels
                    var parentComponent = registry.get(this.parentName);
                    if (parentComponent && typeof parentComponent.updateActive === 'function') {
                        parentComponent.updateActive();
                    }
                }
                    console.log('_reloadCategoryOptions loaded');

            }.bind(this)).always(function () {
                this.loading(false);
                this._isLoadingOptions = false;
            }.bind(this));
        },

        _getCurrentStoreId: function () {
            var storeComponentName = this.storeComponent,
                storeComponent;

            if (!storeComponentName) {
                return 0;
            }

            storeComponent = registry.get(storeComponentName);

            if (!storeComponent || !storeComponent.value) {
                return 0;
            }

            return storeComponent.value() || 0;
        },

        _getLevelsVisibility: function () {
            if (typeof this.levelsVisibility === 'function') {
                return this.levelsVisibility();
            }

            return this.levelsVisibility;
        },

        _setLevelsVisibility: function (value) {
            if (typeof this.levelsVisibility === 'function') {
                this.levelsVisibility(value);
                return;
            }

            this.levelsVisibility = value;
        }
    });
});
