jQuery(function ($) {

    const blocks = {
        message: null,
        overlayCSS: {
            background: '#fff',
            opacity: 0.6
        }
    }
    let DEFAULT_CONTENT_SHOWN_CLASS = 'yith-ywf-email-field__row--empty-value',
        INITIAL_TEXT_EDITOR_HEIGHT = 300,
        saveTimeout                 = false;

    function syncEditors() {
        if ('tinyMCE' in window && 'triggerSave' in window.tinyMCE) {
            window.tinyMCE.triggerSave();
        }
    }

    function getFormDataObject(formElement) {

        var data = {};

        for (let field of formElement) {
            var re = new RegExp('(\\[.*?\\])', 'gmi'),
                is_array = field.name.match(re),
                dataKey = is_array && is_array[0] ? field.name.replace(re, '') : field.name,
                dataValue = field.value;

            if (is_array) {
                var subKey = is_array[0].replace('[', '').replace(']', '');
                var currValues = data[dataKey] || {};
                currValues[subKey] = dataValue;
                data[dataKey] = currValues;
            } else {
                data[dataKey] = dataValue;
            }
        }

        return data;
    }

    function update_preview( element, body, heading ) {
        var emailWrapper = element.closest( '.yith-ywf-emails__email' ),
            emailKey     = emailWrapper.data( 'email' ),
            emailId      = '.' + element.closest( '.yith-ywf-emails__email' ).data( 'email-id' );


        var data = {
            email: emailKey,
            action: ywf_admin_email.actions.reload_email_preview,
            security:ywf_admin_email.nonces.reload_email_preview,
            body:    body,
            heading: heading
        };


        $.ajax( {
            type       : "POST",
            dataType: 'json',
            data,
            url:ywf_admin_email.ajax_url,
            beforeSend: function () {
                $(emailId).block(blocks);
            },
            success: function (response) {
                $( emailId ).html( response.data );
                $( document ).trigger( 'yith-ywf-email-customizer' );
            }
        });
    }

    $(document)
        .on(
            'click',
            '.yith-ywf-emails__email__save',
            function () {

                syncEditors();

                var target = $(this),
                    emailWrapper = target.closest('.yith-ywf-emails__email'),
                    emailKey = emailWrapper.data('email'),
                    optionsForm = emailWrapper.find('form'),
                    buttonTextElement = target.find('.yith-ywf-emails__email__save__text'),
                    saveMessage = target.data('save-message'),
                    savedMessage = target.data('saved-message'),
                    setSaved = function (saved) {
                        if (saved) {
                            target.addClass('is-saved');
                            buttonTextElement.html(savedMessage);
                        } else {
                            target.removeClass('is-saved');
                            buttonTextElement.html(saveMessage);
                        }
                    };

                var data = {
                    email: emailKey,
                    action: ywf_admin_email.actions.update_email,
                    security:ywf_admin_email.nonces.update_email,
                    data: getFormDataObject(optionsForm.serializeArray())
                };

                setSaved(false);
                if (saveTimeout) {
                    clearTimeout(saveTimeout);
                }

                $.ajax( {
                    type       : "POST",
                    dataType: 'json',
                    data,
                    url:ywf_admin_email.ajax_url,
                    beforeSend: function () {
                        target.block(blocks);
                    },
                    success: function (response) {
                        if (response.success) {
                            emailWrapper.find('.email_style_selector').trigger('change');
                        }

                        setSaved(true);

                        saveTimeout = setTimeout(
                            function () {
                                target.unblock();
                                setSaved(false);
                            },
                            1000
                        );
                    }
                });
            }
        )
        .on(
            'click',
            '.yith-ywf-emails__email__toggle-editing',
            function (e) {
                e.preventDefault();
                var target = $(this),
                    email = target.closest('.yith-ywf-emails__email'),
                    options = email.find('.yith-ywf-emails__email__options'),
                    textAreas = email.find('textarea.wp-editor-area');

                if (textAreas.length) {
                    textAreas.each(
                        function () {
                            var id = $(this).attr('id');
                            if ('tinymce' in window) {
                                var editor = window.tinymce.get(id);
                                if (editor) {
                                    editor.theme.resizeTo(undefined, INITIAL_TEXT_EDITOR_HEIGHT);
                                }
                            }
                        }
                    );
                }

                if (email.is('.yith-ywf-emails__email--open')) {
                    email.removeClass('yith-ywf-emails__email--open');
                    options.slideUp();
                } else {
                    email.addClass('yith-ywf-emails__email--open');
                    options.slideDown();
                    options.find('.email_style_selector').trigger('change')
                }
            }
        )
        .on(
            'click',
            '.yith-ywf-email-field__edit',
            function (e) {
                e.preventDefault();
                var row = $(this).closest('.yith-ywf-email-field__row'),
                    defaultContent = row.data('default-content'),
                    textArea = row.find('textarea.wp-editor-area'),
                    id = textArea.attr('id');

                if ('tinymce' in window) {
                    var editor = window.tinymce.get(id);
                    if (editor) {
                        editor.theme.resizeTo(undefined, INITIAL_TEXT_EDITOR_HEIGHT);
                        editor.setContent(defaultContent.replace(/\r?\n/g, '<br />'));
                    } else {
                        textArea.val(defaultContent);
                    }
                }

                row.removeClass(DEFAULT_CONTENT_SHOWN_CLASS);
            }
        )
        .on(
            'change',
            '.yith-ywf-emails__email__toggle-active .on_off',
            function () {

                window.onbeforeunload = null;

                var checkbox     = $( this ),
                    toggle       = checkbox.closest( '.yith-ywf-emails__email__toggle-active' ),
                    emailWrapper = checkbox.closest( '.yith-ywf-emails__email' ),
                    emailKey     = emailWrapper.data( 'email' );


                var data = {
                    email: emailKey,
                    action: ywf_admin_email.actions.switch_email_activation,
                    security:ywf_admin_email.nonces.switch_email_activation,
                    enabled: checkbox.is( ':checked' ) ? 'yes' : 'no'
                };

                $.ajax( {
                    type       : "POST",
                    dataType: 'json',
                    data,
                    url:ywf_admin_email.ajax_url,
                    beforeSend: function () {
                        toggle.block(blocks);
                    },
                    success: function (response) {
                        toggle.unblock();
                    }
                });

            }
        )
        .on(
            'keyup input',
            '.mail-heading',
            function () {

                var emailWrapper = $( this ).closest( '.yith-ywf-emails__email' ),
                    textarea     = emailWrapper.find( 'textarea.wp-editor-area' ),
                    id           = textarea.attr( 'id' ),
                    text         = $( this ).val(),
                    def          = $( this ).attr( 'placeholder' ),
                    body;

                if ( 'tinymce' in window ) {
                    var editor = window.tinymce.get( id );
                    if ( editor ) {
                        body = editor.getContent();
                    } else {
                        body = textarea.val();
                    }
                }

                if ( '' === body ) {
                    body = textarea.closest( '.yith-ywf-email-field__row' ).data( 'default-content' )
                }

                update_preview( $( this ), body, ('' !== text ? text : def) );

            }
        )
        .on(
            'tinymce-editor-setup',
            function ( event, editor ) {
                editor.on(
                    'KeyUp',
                    function ( e ) {
                        var element      = $( '#' + editor.id ),
                            heading = $('.' + element.closest( '.yith-ywf-emails__email' ).data( 'email-id' )+' .mail-heading');
                        update_preview( element,  e.target.innerHTML, heading.val() );

                    }
                );
            }
        )
        .on(
            'click',
            '.yith-ywf-email-field__use-default',
            function () {
                var row      = $( this ).closest( '.yith-ywf-email-field__row' ),
                    textArea = row.find( 'textarea.wp-editor-area' ),
                    id       = textArea.attr( 'id' );

                if ( 'tinymce' in window ) {
                    var editor = window.tinymce.get( id );
                    if ( editor ) {
                        editor.setContent( '' );
                    } else {
                        textArea.val( '' );
                    }
                }

                row.addClass( DEFAULT_CONTENT_SHOWN_CLASS );
            }
        );
});