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

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

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

        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]);
                    console.log('KO bindings cleaned on destroy');
                }

                // 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.categoriesModal;
});