(function($) {
    const seoaiAjaxUrl = wpApiSettings.root;
    tinymce.create('tinymce.plugins.seoaic_button', {
        init : function(ed, url) {
            ed.addButton('seoaic_button', {
                title : 'SEOAI Commands',
                classes: 'seoaic-button',
                disabled: true,
                image : url + '/../img/s-logo.png',
                onclick : function() {
                    ed.windowManager.open({
                        title: 'Choose an Action',
                        id: 'seoaic_improve_content_popup',
                        width: 210,
                        height: 500,
                        body: [
                            {
                                type: 'button',
                                name: 'translation',
                                text: 'Translation',
                                onclick: function(e) {
                                    const selectedText = ed.selection.getContent();
                                    let languages = [];

                                    jQuery.ajax({
                                        url: seoaiAjaxUrl + 'seoaic/v1/get-languages-options',
                                        headers: {
                                            'X-WP-Nonce': wpApiSettings.nonce
                                        },
                                        contentType: "application/json",
                                        dataType: "json",
                                        type: 'POST',
                                        data: {},
                                        success: function(response) {
                                            if (response.success) {
                                                languages = response.data.languages.map(lang => ({ text: lang.label, value: lang.value }));

                                                ed.windowManager.open({
                                                    title: 'Select Language',
                                                    id: 'seoaic_improve_language_popup',
                                                    body: [
                                                        {
                                                            type: 'listbox',
                                                            name: 'language',
                                                            id: 'seoaic_improve_language',
                                                            values: languages,
                                                            size: 1,
                                                        }
                                                    ],
                                                    buttons: [
                                                        {
                                                            text: 'OK',
                                                            id: 'seoaic_improve_language_popup_ok',
                                                            subtype: 'primary',
                                                            onclick: function(dialog) {
                                                                const language = jQuery('#seoaic_improve_language-open span').text();

                                                                seoaicTinymceAjax(ed, 'translate', {language: language})
                                                            }
                                                        },
                                                        {
                                                            text: 'Cancel',
                                                            id: 'seoaic_improve_language_popup_close',
                                                            onclick: 'close'
                                                        }
                                                    ]
                                                });
                                            }
                                        },
                                        error: function(xhr, status, error) {
                                            alert('Error retrieving languages.');
                                        }
                                    });
                                }
                            },
                            {
                                type: 'button',
                                name: 'summary',
                                text: 'Summary',
                                onclick: function(e) {
                                    seoaicTinymceAjax(ed, 'make-summary', {fake: true})
                                }
                            },
                            {
                                type: 'button',
                                name: 'improve',
                                text: 'Improve',
                                onclick: function(e) {
                                    const selectedText = ed.selection.getContent();

                                    ed.windowManager.open({
                                        title: 'PROMPT',
                                        id: 'seoaic_custom_mce_prompt_popup',
                                        body: {
                                            type: 'textbox',
                                            name: 'additionalText',
                                            id: 'seoaic_improve_prompt',
                                            multiline: true,
                                            minWidth: 300,
                                            minHeight: 100
                                        },
                                        buttons: [
                                            {
                                                text: 'OK',
                                                subtype: 'primary',
                                                id: 'seoaic_improve_prompt_modal_ok',
                                                onclick: function(dialog) {
                                                    const prompt = jQuery('#seoaic_improve_prompt').val();
                                                    seoaicTinymceAjax(ed, 'improve-content', {prompt: prompt})
                                                }
                                            },
                                            {
                                                text: 'Cancel',
                                                onclick: 'close',
                                                id: 'seoaic_improve_prompt_modal_close'
                                            }
                                        ]
                                    });
                                }
                            },
                            {
                                type: 'button',
                                name: 'fix_grammar',
                                text: 'Fix Grammar',
                                onclick: function(e) {
                                    const selectedText = ed.selection.getContent();
                                    const data = {
                                        clientId: 1,
                                        content: selectedText
                                    };

                                    if (selectedText) {
                                        jQuery.ajax({
                                            url: seoaiAjaxUrl + 'seoaic/v1/commands/fix-grammar',
                                            headers: {
                                                'X-WP-Nonce': wpApiSettings.nonce
                                            },
                                            method: 'POST',
                                            data: JSON.stringify(data),
                                            contentType: "application/json",
                                            dataType: "json",
                                            beforeSend: function () {
                                                seoaicLoader('add');
                                                ed.windowManager.close();
                                            },
                                            success: function(response) {
                                                if (response.success) {
                                                    ed.selection.setContent(response.data[0].content);
                                                } else {
                                                    alert('Fix Grammar failed.');
                                                }
                                                seoaicLoader('remove');
                                            },
                                        });
                                    }  else {
                                        alert('Please select some text and enter additional text.');
                                    }
                                }
                            },
                            {
                                type: 'button',
                                name: 'rephrase',
                                text: 'Rephrase',
                                onclick: function(e) {
                                    seoaicTinymceAjax(ed, 'rephrase', {fake: true})
                                }
                            },
                            {
                                type: 'button',
                                name: 'shorten',
                                text: 'Shorten',
                                onclick: function(e) {
                                    seoaicTinymceAjax(ed, 'shorten', {fake: true})
                                }
                            },
                            {
                                type: 'button',
                                name: 'simplify',
                                text: 'Simplify',
                                onclick: function(e) {
                                    seoaicTinymceAjax(ed, 'simplify', {fake: true})
                                }
                            },
                            {
                                type: 'button',
                                name: 'paraphrase',
                                text: 'Paraphrase',
                                onclick: function(e) {
                                    seoaicTinymceAjax(ed, 'paraphrase', {fake: true})
                                }
                            },
                            {
                                type: 'button',
                                name: 'write_more',
                                text: 'Write more',
                                onclick: function(e) {
                                    seoaicTinymceAjax(ed, 'write-more', {fake: true})
                                }
                            },
                            {
                                type: 'button',
                                name: 'rewrite',
                                text: 'Rewrite ...',
                                onclick: function(e) {
                                    ed.windowManager.open({
                                        title: 'Make It More',
                                        body: [
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Rewrite For Experts',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'rewrite', {audience: 'experts'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Rewrite For Beginners',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'rewrite', {audience: 'beginners'})
                                                }
                                            }
                                        ],
                                        buttons: [
                                            {
                                                text: 'Cancel',
                                                onclick: 'close',
                                                id: 'seoaic_improve_prompt_modal_close'
                                            }
                                        ]
                                    });
                                }
                            },
                            {
                                type: 'button',
                                name: 'change_tone',
                                text: 'Change tone ...',
                                onclick: function(e) {
                                    ed.windowManager.open({
                                        title: 'Change tone',
                                        body: [
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Academic',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'academic'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Creative',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'creative'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Professional',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'professional'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Funny',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'funny'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Serious',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'serious'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Friendly',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'friendly'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Compelling',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'compelling'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Engaging',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'engaging'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Happy',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'happy'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Persuasive',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'persuasive'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Authoritative',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'authoritative'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Sarcastic',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'change-tone', {tone: 'sarcastic'})
                                                }
                                            },
                                        ],
                                        buttons: [
                                            {
                                                text: 'Cancel',
                                                onclick: 'close',
                                                id: 'seoaic_improve_prompt_modal_close'
                                            }
                                        ]
                                    });
                                }
                            },
                            {
                                type: 'button',
                                name: 'make_it_more',
                                text: 'Make it more ...',
                                onclick: function(e) {
                                    ed.windowManager.open({
                                        title: 'Make It More',
                                        body: [
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Detailed',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'make-it-more', {style: 'detailed'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Descriptive',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'stylmake-it-moreize', {style: 'descriptive'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Engaging',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'make-it-more', {style: 'engaging'})
                                                }
                                            },
                                            {
                                                type: 'button',
                                                name: 'summary',
                                                text: 'Generic',
                                                onclick: function(e) {
                                                    seoaicTinymceAjax(ed, 'make-it-more', {style: 'generic'})
                                                }
                                            }
                                        ],
                                        buttons: [
                                            {
                                                text: 'Cancel',
                                                onclick: 'close',
                                                id: 'seoaic_improve_prompt_modal_close'
                                            }
                                        ]
                                    });
                                }
                            }
                        ],
                        buttons: [
                            {
                                text: 'Close',
                                onclick: 'close',
                                id: 'seoaic_improve_modal_close'
                            }
                        ]
                    });
                },
            });

            ed.on('SelectionChange', function(e) {
                ed.controlManager.setDisabled('seoaic_button', !!ed.selection.isCollapsed());
            });
        },
        createControl : function(n, cm) {
            return null;
        }
    });
    tinymce.PluginManager.add('seoaic_button', tinymce.plugins.seoaic_button);

    function seoaicLoader($action = '') {
        if ($action === 'add') {
            jQuery('body').addClass('seoaic-mce-loading');
            jQuery('.seoaic-mce-loading #wp-content-wrap').after('<div class="lds-dual-ring"></div>');
            jQuery('.seoaic-mce-loading .wp-block-post-content').after('<div class="lds-dual-ring"></div>');
        } else {
            jQuery('body').removeClass('seoaic-mce-loading');
            jQuery('.seoaic-mce-loading .lds-dual-ring').remove();
        }
    }

    function seoaicTinymceAjax(ed, url, params = {}) {
        let title = jQuery('input[name="post_title"]').val();

        if (typeof title === 'undefined' || title === null || title.trim() === '') {
            title = jQuery('.edit-post-visual-editor__post-title-wrapper .wp-block-post-title').text();
        }

        const selectedText = ed.selection.getContent();

        if (selectedText && params) {
            let data = {
                clientId: 1,
                title: title,
                content: selectedText
            };

            Object.assign(data, params);

            jQuery.ajax({
                url: seoaiAjaxUrl + 'seoaic/v1/commands/' + url,
                headers: {
                    'X-WP-Nonce': wpApiSettings.nonce
                },
                method: 'POST',
                data: JSON.stringify(data),
                contentType: "application/json",
                dataType: "json",
                beforeSend: function () {
                    seoaicLoader('add');
                    ed.windowManager.close();
                    ed.windowManager.close();
                },
                success: function(response) {
                    if (response.success) {
                        ed.selection.setContent(response.data.content);
                    }
                    seoaicLoader('remove');
                },
            });
        }  else {
            alert('Please select some text and enter additional text.');
        }
    }

    let activeEditor = null;

    $(document).off('click', '.seoaic-tiny-mce-generate-image').on('click', '.seoaic-tiny-mce-generate-image', function () {
        activeEditor = tinymce.get($(this).closest('.wp-editor-wrap').find('textarea').attr('id'));

        const popupHtml = `
            <div id="seoaic-popup-overlay">
                <div class="seoaic-image-generation-wrap">
                    <div class="seoaic-logo"></div>
                    <div class="seoaic-block-title">Generate Image by SEOAI</div>
                    <div class="seoaic-prompt">
                        <div class="description">Image Prompt</div>
                        <textarea id="seoaic-image-prompt" placeholder="Put your image description here"></textarea>
                        <div class="button-wrap">
                            <button class="seoaic-image-generate"><span>Generate</span></button>
                            <button class="seoaic-popup-cancel"><span>Cancel</span></button>
                        </div>
                    </div>
                    <div class="seoaic-image-generated-wrap">
                        <div class="description">Choose the image.</div>
                        <div class="seoaic-generated-image"></div>
                        <div class="button-wrap">
                            <button id="seoaic-image-use"><span>Use</span></button>
                            <button class="seoaic-image-generate"><span class="dashicon dashicons dashicons-update" style="font-size: 24px; width: 24px; height: 24px;"></span><span>Regenerate</span></button>
                            <button id="seoaic-image-improve"><span class="dashicon dashicons dashicons-arrow-up-alt" style="font-size: 24px; width: 24px; height: 24px;"></span><span>Improve</span></button>
                            <button class="seoaic-popup-cancel"><span>Cancel</span></button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        $('body').append(popupHtml);

        $(document).off('click', '#seoaic-image-use').on('click', '#seoaic-image-use', function () {
            const imgElement = document.querySelector('.seoaic-image-template.selected img');
            const dataAttributes = imgElement.dataset;

            let data = {
                image: {
                    url: imgElement.src,
                    title: imgElement.alt,
                    image_prompt: dataAttributes.imagePrompt,
                    user_prompt: dataAttributes.userPrompt
                }
            };

            jQuery.ajax({
                url: seoaiAjaxUrl + 'seoaic/v1/blocks/generate-image/save-image',
                headers: {
                    'X-WP-Nonce': wpApiSettings.nonce,
                },
                method: 'POST',
                data: JSON.stringify(data),
                contentType: "application/json",
                dataType: "json",
                success: function (response) {
                    if (response && response.success && response.data && response.data.sizes) {
                        const imageUrl = response.data.sizes.full;
                        if (imageUrl) {
                            const imageHtml = `<img src="${imageUrl}" alt="${imgElement.alt}" />`;
                            activeEditor.insertContent(imageHtml);
                        } else {
                            console.error('Image URL is missing in the response.');
                        }
                    } else {
                        console.error('Invalid response data:', response);
                    }
                    $('#seoaic-popup-overlay').remove();
                },
                error: function (xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                }
            });
        });

        $(document).on('click', '.seoaic-popup-cancel', function () {
            $('#seoaic-popup-overlay').remove();
        });

        $(document).on('click', '.seoaic-image-template', function () {
            $('.seoaic-image-template').removeClass('selected');
            $(this).addClass('selected');
        });

        $(document).on('click', '#seoaic-image-improve', function () {
            $('.seoaic-image-generation-wrap .seoaic-prompt').show();
            $('.seoaic-image-generation-wrap .seoaic-image-generated-wrap').hide();
        });

        $(document).off('click', '.seoaic-image-generate').on('click', '.seoaic-image-generate', function () {
            const textArea = $('#seoaic-image-prompt');
            const userInput = textArea.val();

            if (userInput.length === 0) {
                textArea.addClass('highlight-error');
                textArea.focus();

                setTimeout(() => {
                    textArea.removeClass('highlight-error');
                }, 2000);

                return;
            }

            $('.seoaic-image-generation-wrap .seoaic-prompt').hide();
            $('.seoaic-image-generation-wrap .seoaic-image-generated-wrap').show();

            let data = {
                user_prompt: userInput
            };

            const container = document.querySelector('.seoaic-generated-image');

            jQuery.ajax({
                url: seoaiAjaxUrl + 'seoaic/v1/blocks/generate-image/generate-images',
                headers: {
                    'X-WP-Nonce': wpApiSettings.nonce,
                },
                method: 'POST',
                data: JSON.stringify(data),
                contentType: "application/json",
                dataType: "json",
                beforeSend: function () {
                    container.insertAdjacentHTML('beforeend', loadingContent());
                },
                success: function (response) {
                    const template = generateImageTemplate(response);
                    $('.waiting-template').remove();
                    container.insertAdjacentHTML('beforeend', template);

                    const templates = container.querySelectorAll('.seoaic-image-template');

                    if (templates.length > 1) {
                        templates[0].classList.remove('active');
                        $('.seoaic-image-generated-wrap .description').show();
                        $('.seoaic-image-generated-wrap .seoaic-image-template').removeClass('selected');
                    } else if (templates.length === 1) {
                        templates[0].classList.add('selected');
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                }
            });
        });

    });

    function generateImageTemplate(response) {
        if (!response.success || !response.data || !response.data.image) {
            return `<p>${response.message}</p>`;
        }

        const imageUrl = response.data.image.url;
        const title = response.data.image.title;
        const userPrompt = response.data.image.user_prompt;
        const imagePrompt = response.data.image.image_prompt;

        return `
            <div class="seoaic-image-template">
                <img src="${imageUrl}" alt="${title}" data-image-prompt="${imagePrompt}" data-user-prompt="${userPrompt}" />
            </div>
        `;
    }

    function loadingContent() {
        return `
            <div class="seoaic-image-template waiting-template">
                <div class="loading-icon">
                    <div class="loader-ellipsis small show"></div>
                    <div class="waiting">Generation may take up to 30 seconds</div> 
                </div>
            </div>
        `;
    }

    $(document).on('click', '#seoaic-generate-thumbnail-button', function(e) {
        e.preventDefault();
        const prompt = $('#seoaic-thumbnail-prompt').val();
        const width = $('#width_value').val();
        const height = $('#height_value').val();
        const postId = $('#post_ID').val();

        let data = {
            prompt: prompt,
            width: width,
            height: height
        };

        jQuery.ajax({
            url: seoaiAjaxUrl + `seoaic/v1/post/${postId}/thumbnail-generate`,
            headers: {
                'X-WP-Nonce': wpApiSettings.nonce
            },
            method: 'POST',
            data: JSON.stringify(data),
            contentType: "application/json",
            dataType: "json",
            beforeSend: function () {
                $('#seoaic-generate-thumbnail-button').addClass('is-busy');
            },
            success: function(response) {
                if (response.success && response.data.attachment) {
                    const attachmentId = response.data.attachment.id;
                    updatePostThumbnail(postId, attachmentId, response.data.attachment.sizes.large);
                } else {
                    console.log('Error: Could not generate thumbnail.');
                }

                $('#seoaic-generate-thumbnail-button').removeClass('is-busy');
            },
        });
    });

    function updatePostThumbnail(postId, attachmentId, thumbnailUrl) {
        const mediaUploadLink = `/wp-admin/media-upload.php?post_id=${postId}&type=image&TB_iframe=1`;
        const thumbnailContainer = $('#postimagediv');
        const setThumbnailLink = thumbnailContainer.find('.thickbox');

        if (setThumbnailLink.length) {
            setThumbnailLink.html(`
                <a href="${mediaUploadLink}" class="thickbox" title="Edit Thumbnail">
                    <img src="${thumbnailUrl}" style="max-width:100%; height:auto;" />
                </a>
            `);
            $('#_thumbnail_id').val(attachmentId);

            if (!thumbnailContainer.find('#set-post-thumbnail-desc').length) {
                thumbnailContainer.find('.inside').append(`
                    <p class="hide-if-no-js howto" id="set-post-thumbnail-desc">Click the image to edit or update</p>
                    <p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail">Remove featured image</a></p>
                `);
            }
        }
    }

    const ranges = [
        {id: 'width_value', outputId: 'width_value_output'},
        {id: 'height_value', outputId: 'height_value_output'}
    ];

    ranges.map((item) => {
        if (!document.getElementById(item.id)) {
            return;
        }

        document.getElementById(item.id).addEventListener('input', function () {
            document.getElementById(item.outputId).textContent = this.value;
        });
    })
})(jQuery);
