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

define([
    'jquery',
    'Magento_Ui/js/modal/confirm',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/categories/model/signalr',
    'jquery/ui',
    'Magento_Ui/js/modal/modal'
], function ($, confirm, textfields, signalRModel) {

    $.widget('writetextai.categoriesModal', $.mage.modal, {
        /**
         * Close modal.
         */
        closeModal: function () {
            var superCall = this._super.bind(this),
                hasChanges = textfields.originalPageTitle() !== textfields.pageTitle() ||
                    textfields.originalPageDescription() !== textfields.pageDescription() ||
                    textfields.originalCategoryDescription() !== textfields.categoryDescription(),
                generating = signalRModel.generating();

            if (hasChanges && !generating) {
                confirm({
                    content: $.mage.__('You have unsaved changes. Are you sure you want to leave this page?'),
                    buttons: [{
                        text: $.mage.__('Cancel'),
                        class: 'action-secondary action-dismiss',
                        click: function (event) {
                            this.closeModal(event);
                        }
                    }, {
                        text: $.mage.__('Ok'),
                        class: 'action-primary action-accept',
                        click: function (event) {
                            superCall();
                            this.closeModal(event);
                        }
                    }]
                });
            } else {
                superCall();
            }
        },
    });

    return $.writetextai.categoriesModal;
});