;(function($){
    function liveEditorHandler() {
        $('.eicon-close').on('click', function () {
            $('body').attr('data-htmega-live-editor-load', 'true');
            closeModal(true);
        });
        $(document).on('click', '.htmega-tm-live-editor-modal-iframe', function (e) {
            if ($(e.target).closest(".dialog-lightbox-widget-content").length < 1) {
                closeModal();
            }
        });
        elementor.channels.editor.on('createTempEvent', function (e) {
            let widgetId = getTemplateKey(e),
                $modalContainer = $('.htmega-tm-live-editor-modal-iframe'),
                htmegaEditorIframe = $modalContainer.find("#htmega-live-editor-iframe-control"),
                $lightboxLoading = $modalContainer.find(".dialog-lightbox-loading"),
                lightboxType = $modalContainer.find(".dialog-type-lightbox"),
                tempSelectorId = e.model.attributes.name.split('_live')[0],
                liveTempId = 'live_temp_content',
                settingsToChange = {};

            lightboxType.show();
            $modalContainer.show();
            $lightboxLoading.show();
            htmegaEditorIframe.contents().find("#elementor-loading").show();
            htmegaEditorIframe.css("z-index", "-1");

            $.ajax({
                type: 'POST',
                url: liveEditor.ajaxurl,
                dataType: 'JSON',
                data: {
                    action: 'htmega_live_editor_handler',
                    security: liveEditor.nonce,
                    key: widgetId,
                },
                success: function (res) {
                    htmegaEditorIframe.attr("src", res.data.url);
                    htmegaEditorIframe.attr("data-htmega-temp-id", res.data.id);

                    htmegaEditorIframe.on("load", function () {
                        $lightboxLoading.hide();
                        htmegaEditorIframe.show();
                        $modalContainer.find('.htmega-live-editor-title').css('display', 'flex');
                        htmegaEditorIframe.contents().find("#elementor-loading").hide();
                        htmegaEditorIframe.css("z-index", "1");
                    });
                    clearInterval(window.htmegaLiveEditorInterval);

                    window.htmegaLiveEditorInterval = setInterval(function () {

                        let loadTemplate = $('body').attr('data-htmega-live-editor-load');

                        if ('true' === loadTemplate) {
                            $('body').attr('data-htmega-live-editor-load', 'false');

                            settingsToChange[tempSelectorId] = '';
                            getUpdateTitle(res.data.id).then(
                                function(value) {
                                   settingsToChange[liveTempId] = value.data.post_title;
                                  $(".htmega-live-temp-title").removeClass("control-hidden");
                                   $e.run('document/elements/settings', { container: e.container, settings: settingsToChange, options: { external: !0 } });
                                }
                            );
                        }
                    }, 1000);
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
    }

    function tempValidityChecker(tempID) {

        if ( '' !== tempID ) {
            $.ajax({
                type: 'POST',
                url: liveEditor.ajaxurl,
                dataType: 'JSON',
                data: {
                    action: 'htmega_temp_validity_status',
                    security: liveEditor.nonce,
                    templateID: tempID,
                },
                error: function (err) {
                    console.log(err);
                }
            });
        }
    }

    /**
     * Generate the template key
     * @param {Object} e click event
     * @return {string}
     */
    function getTemplateKey(e) {
        var widget = e.options.container.view.$el,
            control_id = e._parent.model.attributes._id ? e._parent.model.attributes._id : '';

        return widget.data('id') + control_id;
    }

    async function getUpdateTitle(id) {
        let result;
        try {
            result = $.ajax({
                type: 'POST',
                url: liveEditor.ajaxurl,
                dataType: 'JSON',
                data: {
                    action: 'htmega_get_update_title',
                    security: liveEditor.nonce,
                    id: id
                },
            });
            return result;
        } catch (error) {
            console.error(error);
        }
    }

    function closeModal(inserted = false) {

        $('.htmega-tm-live-editor-modal-iframe').css('display', 'none');

        $(".htmega-live-temp-title input").attr('disabled', 'true');

        if (!inserted) {
            var tempId = $(".htmega-tm-live-editor-modal-iframe #htmega-live-editor-iframe-control").attr('data-htmega-temp-id');

            if (undefined !== tempId && '' !== tempId) {
                tempValidityChecker(tempId);
            }
        }
        // Reset temp id/src attribute.
        $(".htmega-tm-live-editor-modal-iframe #htmega-live-editor-iframe-control").attr({
            'data-htmega-temp-id': '',
            'src': ''
        });
    }

    function checkLiveTemplateControl(sectionName, elementorEditor) {

        setTimeout(function () {

            $(".htmega-live-temp-title input").each(function (index, input) {
                $(input).attr('disabled', 'true');
                if ('' != $(input).val()) {
                    $(input).closest(".htmega-live-temp-title").removeClass("control-hidden");
                }
            });

        }, 1000);
    }

    elementor.channels.editor.on('section:activated', checkLiveTemplateControl);

    $(window).on('elementor:init', liveEditorHandler);


})(jQuery);