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

define([
    'jquery',
    'ko',
    'Magento_Ui/js/modal/confirm',
    'WriteTextAI_WriteTextAI/js/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/gallery',
    'WriteTextAI_WriteTextAI/js/model/signalr',
    'WriteTextAI_WriteTextAI/js/categories/model/signalr',
    'text!WriteTextAI_WriteTextAI/template/modal/edit-modal.html',
    'jquery/ui',
    'Magento_Ui/js/modal/modal'
], function ($, ko, confirm, textfields, gallery, signalRModel, categoriesSignalRModel, editModalTemplate) {

    $.widget('writetextai.editModal', $.mage.modal, {
        options: {
            editTitleStatusText: ko.observable(''),
            slideTpl: editModalTemplate
        },

        /** Called when widget is created **/
        _create: function () {
            this._super();
            var self = this;

            console.log('editModal widget _create() called');

            /** Define observable (use a consistent name) */
            var observable = this.options.editTitleStatusText || ko.observable('');

            /** Subscribe to SignalR updates */
            signalRModel.editTitleStatusText.subscribe(function (statusText) {
                observable(statusText);
            });

            /** Wait for modal DOM to render (200ms is usually enough) */
            setTimeout(function () {
                var $modal = self.element.closest('.modal-inner-wrap');
                if ($modal.length) {
                    var $container = $modal.find('.wtai-preparing-loading-container');
                    /** Apply Knockout bindings */
                    var viewModel = {
                        editTitleStatusText: observable
                    };

                    /** Clean previous bindings if re-initialized */
                    if ($container[0].__ko_bound__) {
                        ko.cleanNode($modal[0]);
                    }

                    ko.applyBindings(viewModel, $container[0]);
                    $container[0].__ko_bound__ = true;
                }
            }, 200);
        },

        /**
         * 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();
            }
        },

        destroy: function () {
            var $modal = this.element.find('.modal-inner-wrap');

            if ($modal.length && $modal.data('ko-bound')) {
                /** Find the container you bound Knockout to */
                var $container = $modal.find('.wtai-preparing-loading-container');

                /** Clean KO bindings */
                if ($container.length && ko.dataFor($container[0])) {
                    ko.cleanNode($container[0]);
                }

                /** Remove the flag so bindings can be applied again if modal is recreated */
                $modal.removeData('ko-bound');
            }

            /** Call the parent destroy */
            this._super();
        }
    });

    return $.writetextai.editModal;
});