(function () {
    var $ = jQuery;

    function handleLiveEditor() {

        // close model events.
        $('.eicon-close').on('click', closeModal);

        $('#pa-insert-live-temp').on('click', function () {
            $('body').attr('data-pa-liveeditor-load', 'true');
            closeModal(true);
        });

        $(document).on('click', '.premium-live-editor-iframe-modal', function (e) {
            if ($(e.target).closest(".dialog-lightbox-widget-content").length < 1) {
                closeModal();
            }
        });

        // resize model event.
        $('.premium-live-editor-iframe-modal .premium-expand').on('click', function () {

            if ($(this).find(' > i').hasClass('eicon-frame-expand')) {
                $(this).find('i.eicon-frame-expand').removeClass('eicon-frame-expand').addClass('eicon-frame-minimize').attr('title', 'Minimize');
                $('.premium-live-editor-iframe-modal').addClass('premium-modal-expanded');

            } else {
                minimizeModal(this);
            }
        });

        elementor.channels.editor.on('createLiveTemp', function (e) {

            // Iframe elements.
            var $modalContainer = $('.premium-live-editor-iframe-modal'),
                paIframe = $modalContainer.find("#pa-live-editor-control-iframe"),
                $lightboxLoading = $modalContainer.find(".dialog-lightbox-loading"),
                lightboxType = $modalContainer.find(".dialog-type-lightbox");

            var tempType = getTemplateType(e),
                isRepeaterItem = e._parent.$childViewContainer.hasClass('elementor-repeater-row-controls'),
                currentSettings = isRepeaterItem ? e._parent.model.attributes : e._parent.model.attributes.settings.attributes;

            if ('grid' === tempType) {
                var tempSelectorId = 'pa_grid_template_id';
            } else if ('loop' === tempType) {
                var tempSelectorId = 'pa_loop_template_id';
            } else {

                /**
                 * Template selector control ID.
                 *
                 * Used to determine which live template control we're dealing with. and also to determine the live template control ID.
                 *
                 * The live template control ID is ALWAYS generated by appending '_live' to the (original) template selector control ID.
                 * Ex: In carousel widget, template selector is 'premium_carousel_repeater_item' -> the live template button is 'premium_carousel_repeater_item_live'.
                 * So, we remove the '_live' part to get the original template selector control ID.
                 */
                var tempSelectorId = e.model.attributes.name.split('_live')[0];
            }


            var tempSelectorValue = currentSettings[tempSelectorId] || '',
                hasTemplateId = 'loop' === tempType || 'grid' === tempType ? (tempSelectorValue && '' !== tempSelectorValue) : false;

            // Show modal. -> in all cases.
            lightboxType.show();
            $modalContainer.show();
            $lightboxLoading.show();
            paIframe.contents().find("#elementor-loading").show();
            paIframe.css("z-index", "-1");


            if (hasTemplateId) {
                var tempUrl = liveEditor.adminUrl + 'post.php?post=' + tempSelectorValue + '&action=elementor';

                paIframe.attr("src", tempUrl);
                paIframe.attr("data-premium-temp-id", tempSelectorValue);

                if ('loop' === tempType) {
                    paIframe.attr("data-premium-temp-type", tempType);
                }

                paIframe.on("load", function () {
                    $lightboxLoading.hide();
                    paIframe.show();
                    $modalContainer.find('#premium-live-temp-title').hide(); // Hide the template title input for existing templates.
                    $modalContainer.find('.premium-live-editor-title').css('display', 'flex');
                    paIframe.contents().find("#elementor-loading").hide();
                    paIframe.css("z-index", "1");
                });

                updateSettings(e, tempType, tempSelectorValue, tempSelectorId, tempSelectorValue);
            } else {
                // it's not a loop || grid with existing template ID.
                // it's either a new template or an existing template without ID (non-loop/grid).

                /**
                 * If the template selector control has a value, it means we're editing an existing template.
                 */
                if (tempSelectorValue) {
                    var options = {
                        action: 'pa_get_editor_template', // Retrieves the existing template.
                        security: liveEditor.nonce,
                        tempTitle: tempSelectorValue,
                        type: tempType
                    };

                } else {

                    var widgetId = getTemplateKey(e); // widgetId ( + controlId in case of repeater controls )

                    /**
                     * Case 1: Widgets that have two live templates in the same repeater item. Ex: Multiscroll.
                     * Case 2: Widgets that have two live templates in the same widget but not in a repeater. Ex: Content Toggle (second content).
                     *
                     * We're appending '2' instead of a random number to the widgetId to distinguish between the two templates and be able to reconstruct the correct widget ID.
                     */
                    if ('right_side_template' === tempSelectorId || 'premium_content_toggle_second_content_templates' === tempSelectorId) {
                        widgetId += '2';
                    }

                    var options = {
                        action: 'handle_live_editor', // Creates a new template or retrieves the existing one.
                        security: liveEditor.nonce,
                        key: widgetId,
                        type: tempType
                    };
                }

                // Proceed with AJAX request to create/retrieve the template.
                $.ajax({
                    type: 'POST',
                    url: liveEditor.ajaxurl,
                    dataType: 'JSON',
                    data: options,
                    success: function (res) {
                        console.log(res);

                        paIframe.attr("src", res.data.url); // Set the iframe src to load the template editor.
                        paIframe.attr("data-premium-temp-id", res.data.id); // Set the template ID as a data attribute to check its validity on modal close.

                        if ('loop' === tempType) {
                            paIframe.attr("data-premium-temp-type", tempType);
                        }

                        $('#premium-live-temp-title').val(res.data.title); // Set the template title input value.

                        paIframe.on("load", function () {
                            $lightboxLoading.hide();
                            paIframe.show();
                            $modalContainer.find('.premium-live-editor-title').removeClass('pa-show-title-input pa-hide-title-input').addClass('pa-' + (tempSelectorValue ? 'hide' : 'show') + '-title-input').css('display', 'flex');
                            paIframe.contents().find("#elementor-loading").hide();
                            paIframe.css("z-index", "1");
                        });

                        updateSettings(e, tempType, res.data.id, tempSelectorId, tempSelectorValue);
                    },
                    error: function (err) {
                        console.log(err);
                    }
                });

            }
        });
    }

    /**
     * Helper Functions.
     */

    function checkTempValidity(tempID, tempType) {

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

    /**
     * Generates the template key.
     *
     * The widget var is a jQuery object of the widget => contains the widget data-id.
     * The controlId var is the ID of the repeater item or '' in case it's a non-repeater control.
     * This is used to generate unique keys in case of repeater controls.
     *
     * @param {Object} e click event
     * @return {string}
     */
    function getTemplateKey(e) {
        var widget = e.options.container.view.$el,
            controlId = e._parent.model.attributes._id || '';

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

    /**
     * Check the template type.
     * Returns 'loop' or 'grid' or '' depending on the button class.
     *
     * @param {Object} e click event
     * @return {string}
     */
    function getTemplateType(e) {
        var classes = e.model.attributes.button_type;

        if (classes.includes('loop-temp')) {
            return 'loop';
        } else if (classes.includes('grid-temp')) {
            return 'grid';
        }
        // return classes.includes('loop-temp') ? 'loop' : '';
    }

    function minimizeModal(_this) {

        $(_this).find('i.eicon-frame-minimize').removeClass('eicon-frame-minimize').addClass('eicon-frame-expand').attr('title', 'Expand');
        $('.premium-live-editor-iframe-modal').removeClass('premium-modal-expanded');
    }

    function updateTemplateTitle(title, id) {

        $.ajax({
            type: 'POST',
            url: liveEditor.ajaxurl,
            dataType: 'JSON',
            data: {
                action: 'update_template_title',
                security: liveEditor.nonce,
                title: title,
                id: id
            },
            success: function (res) {
                console.log('Template Title Updated.');
            },
            error: function (err) {
                console.log(err);
            }
        });
    }

    function closeModal(inserted = false) {

        $('.premium-live-editor-iframe-modal').css('display', 'none').find('.premium-live-editor-title').removeClass('pa-show-title-input pa-hide-title-input');

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

        minimizeModal($('.premium-live-editor-iframe-modal .premium-expand'));

        if (!inserted) {
            var tempId = $(".premium-live-editor-iframe-modal #pa-live-editor-control-iframe").attr('data-premium-temp-id'),
                tempType = $(".premium-live-editor-iframe-modal #pa-live-editor-control-iframe").attr('data-premium-temp-type');

            if (undefined !== tempId && '' !== tempId) {
                checkTempValidity(tempId, tempType);
            }
        }

        // reset temp id/src attribute.
        $(".premium-live-editor-iframe-modal #pa-live-editor-control-iframe").attr({
            'data-premium-temp-id': '',
            'data-premium-temp-type': '',
            'src': ''
        });
    }

    function updateSettings(e,tempType, tempId, tempSelectorId, tempSelectorValue) {

        clearInterval(window.paLiveEditorInterval);

        window.paLiveEditorInterval = setInterval(function () {

            /**
             * Default: live_temp_content.
             * In widgets where there are two live templates in the same widget (not in a repeater) or in the same repeater item, we use a different control name for the second template.
             */
            var liveTempId = ['premium_content_toggle_second_content_templates', 'fixed_template', 'right_side_template'].includes(tempSelectorId) ? 'live_temp_content_extra' : 'live_temp_content';

            var loadTemplate = $('body').attr('data-pa-liveeditor-load'),
                settingsToChange = {};

            if ('true' === loadTemplate) {
                $('body').attr('data-pa-liveeditor-load', 'false');

                if (['loop', 'grid'].includes(tempType)) {
                    settingsToChange['pa_' + tempType + '_live_temp_id'] = tempId;
                }

                // update the controls values if template selector is not set.
                if (!tempSelectorValue) {
                    settingsToChange[liveTempId] = $('#premium-live-temp-title').val(); // set the live template control value to the current template title.
                    settingsToChange[tempSelectorId] = ''; // reset the original template selector control value to ''.
                    $(".premium-live-temp-title").removeClass("control-hidden"); // Show the template title control after it's updated.
                } else {
                    /**
                     * Re-update the original template selector control value to re-render the view.
                     * This is needed in case the user changed the template content, it guarantees the template is updated accordingly.
                     */
                    settingsToChange[tempSelectorId] = tempSelectorValue;
                    $(".premium-live-temp-title").addClass("control-hidden");
                }

                if (Object.keys(settingsToChange).length) {
                    $e.run('document/elements/settings', { container: e.container, settings: settingsToChange, options: { external: !0 } });
                }

                var tempTitle = $('#premium-live-temp-title').val();
                if (tempTitle && tempTitle !== res.data.title) {
                    updateTemplateTitle(tempTitle, res.data.id);
                }
            }

        }, 1000);
    }

    function checkLiveTemplateControl() {

        setTimeout(function () {

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

            $('.premium-cf-form-id input').attr('disabled', 'true');

        }, 500);
    }

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

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

})(jQuery);