/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

define([
    'jquery',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'mage/translate',
    'collapsible'
], function ($, Component, _, editData, product, $t) {
    'use strict';

    /**
     * @var {Component} self
     */
    var self;

    return Component.extend({
        defaults: {
            collapsibleSelector: '.wtai-store-scope .dropdown',
            allStoreViews: $t('All store views'),
            allStoreViewsValue: 0,
            storeName: '',
            productTypeLabel: '',
            hasProductType: false,
            storesAvailable: [],
            widgetsInitialized: false
        },

        /** @inheritdoc */
        initialize: function () {
            this._super();

            self = this;

            self.initDropdown();

            product.storeScope.subscribe(function (storeScope) {
                self.storeName(storeScope);
            });

            product.stores.subscribe(function (stores) {
                self.storesAvailable(stores);
            });

            product.productTypeLabel.subscribe(function (productTypeLabel) {
                self.productTypeLabel(productTypeLabel);
            });

            product.hasProductType.subscribe(function (hasProductType) {
                self.hasProductType(hasProductType);
            });

            editData.opened.subscribe(function (opened) {
                if (opened && !self.widgetsInitialized) {
                    self.initDropdown();
                    self.widgetsInitialized = true;
                }
            });
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe(['storeName', 'productTypeLabel', 'storesAvailable','hasProductType']);

            return this;
        },

        /**
         * Init dropdown
         */
        initDropdown: function () {
            $(self.collapsibleSelector).collapsible({
                collapsible: true,
                openedState: 'active',
                active: false
            });

            $(document).on('click', function (e) {
                if (
                    !$(self.collapsibleSelector).is(e.target) &&
                    !$(self.collapsibleSelector).has(e.target).length &&
                    $(self.collapsibleSelector).data('collapsible')
                ) {
                    $(self.collapsibleSelector).collapsible('deactivate');
                }
            });
        },

        /**
         * Check if current store is selected
         *
         * @param {string} label
         * @returns {boolean}
         */
        isCurrent: function (label = this.allStoreViews) {
            return self.storeName() === label.trim();
        }
    });
});
