/**
 * @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/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/gallery',
    'WriteTextAI_WriteTextAI/js/model/signalr',
    'jquery/ui',
    'Magento_Ui/js/modal/modal'
], function ($, confirm, textfields, gallery, signalRModel) {

    $.widget('writetextai.editModal', $.mage.modal, {
        /**
         * Close modal.
         */
        closeModal: function () {
            var superCall = this._super.bind(this),
                generating = signalRModel.generating(),
                hasChanges = textfields.originalPageTitle() !==
                        textfields.pageTitle() ||
                    textfields.originalPageDescription() !==
                        textfields.pageDescription() ||
                    textfields.originalProductDescription() !==
                        textfields.productDescription() ||
                    textfields.originalProductShortDescription() !==
                        textfields.productShortDescription() ||
                    textfields.originalOpenGraph() !== textfields.openGraph(),
                unsavedImage = gallery.images().some(image => {
                    return image.original_writetext_alt !== image.writetext_alt;
                }),
                unsavedTexts = (hasChanges|| unsavedImage) && !generating;
                
            
            if (unsavedTexts) {
                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.editModal;
});