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

define([
    'jquery',
    'ko',
    'uiComponent',
    'Magento_Ui/js/modal/modal'
], function ($, ko, Component) {
    'use strict';

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

    return Component.extend({
        defaults: {
            selectors: {
                modal: '.wtai-welcome-new-version-popup-modal',
                overlay: '.wtai-welcome-new-version-popup-overlay',
            },
            classes: {
                modal: 'wtai-welcome-new-version-popup-modal',
                overlay: 'wtai-welcome-new-version-popup-overlay'
            }
        },

        popup: null,
    
        /** @inheritdoc */
        initialize: function () {
            this._super();
    
            self = this;

            const el = document.querySelector('.wtai-welcome-new-version-popup-modal');
            if (el) {
                $('.wtai-welcome-new-version-popup-modal > *').applyBindings(this);
            }
    
            this.initModal();
        },

        /**
         * Initialize history log modal.
         */
        initModal: function () {
            this.popup = $(this.selectors.modal).modal({
                innerScroll: true,
                modalClass: self.classes.modal,
                overlayClass: self.classes.overlay,
                outerClickHandler: function () {
                    $(this.selectors.modal).modal('closeModal');
                }.bind(this),
                buttons: [],
                closed: function () {
                    $(self.selectors.overlay).remove();
                    self.save();
                }
            });

            $(this.selectors.modal).css('display', 'block');

            if (this.showPopupOnLoad) {
                this.popup.modal('openModal');
            }
        },

        /**
         * Save guide steps checkbox
         */
        save: function () {
            var url = self.saveUrl;

            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    type: 'welcome_new_version'
                },
                dataType: 'json',
                showWriteTextAILoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response.message);
                    }
                }
            });
        },

        /**
         * Component-specific close popup function to avoid naming conflicts
         */
        closeNewVersionPopup: function () {
            this.popup.modal('closeModal');
        }
    });
});
