function isEditOrNewPostPage() {
    var bodyClasses = document.body.classList;
    var isPostNewPage = bodyClasses.contains('post-new-php');
    var isPostPage = bodyClasses.contains('post-php');
    var isAiautotoolPage = bodyClasses.contains('aiautotool_input');

    var isAiPostInUrl = window.location.href.includes('ai_post');
    var isAiSinglePostInUrl = window.location.href.includes('ai_single_post');

    return isPostNewPage || isPostPage || isAiautotoolPage || isAiPostInUrl || isAiSinglePostInUrl;
}

function hideAiautotoolWritingPanel() {
    if (document.getElementById('aiautotool-hide-writing-panel-style')) {
        return;
    }

    var style = document.createElement('style');
    style.id = 'aiautotool-hide-writing-panel-style';
    style.textContent = '#aiautotool_bar_right .aiautotool-writing-panel,.aiautotool-writing-panel{display:none!important;visibility:hidden!important;height:0!important;margin:0!important;padding:0!important;overflow:hidden!important;}';
    document.head.appendChild(style);
}

function removeAiautotoolWritingPanel() {
    document.querySelectorAll('#aiautotool-writing-panel, .aiautotool-writing-panel').forEach(function (panel) {
        panel.remove();
    });
}

function aiautotoolGetMediaSearchBaseUrl() {
    const aipostSettings = window.aipost || {};
    const globalSettings = window.aiautotool_js_setting || {};
    const baseUrl = aipostSettings.media_search_base_url || globalSettings.media_search_base_url || 'https://aplugin.aiautotool.com';

    return String(baseUrl).replace(/\/+$/, '');
}

function aiautotoolGetMediaSearchUrl(path) {
    return aiautotoolGetMediaSearchBaseUrl() + '/' + String(path).replace(/^\/+/, '');
}

function aiautotoolEscapeHtml(value) {
    return String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

hideAiautotoolWritingPanel();

document.addEventListener('DOMContentLoaded', function () {
    hideAiautotoolWritingPanel();
    removeAiautotoolWritingPanel();

    // Chờ cho đến khi trang hoàn toàn tải xong
    window.onload = function () {
        // Khai báo editor sau khi trang đã tải xong
        if (typeof tinyMCE !== "undefined") {
            var editor = tinyMCE.activeEditor;
            // console.log('co editor'); // Debug removed
            // create_buttoneditor();

            if (editor) {
                var tabbar = document.createElement('div');
                tabbar.id = 'tabbar';
                tabbar.className = 'mce-toolbar-grp mce-inline-toolbar-grp  mce-panel ';
                tabbar.style.display = 'none';
                let svg_UIFindImage = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M7 7C5.34315 7 4 8.34315 4 10C4 11.6569 5.34315 13 7 13C8.65685 13 10 11.6569 10 10C10 8.34315 8.65685 7 7 7ZM6 10C6 9.44772 6.44772 9 7 9C7.55228 9 8 9.44772 8 10C8 10.5523 7.55228 11 7 11C6.44772 11 6 10.5523 6 10Z" fill="currentColor" /><path fill-rule="evenodd" clip-rule="evenodd" d="M3 3C1.34315 3 0 4.34315 0 6V18C0 19.6569 1.34315 21 3 21H21C22.6569 21 24 19.6569 24 18V6C24 4.34315 22.6569 3 21 3H3ZM21 5H3C2.44772 5 2 5.44772 2 6V18C2 18.5523 2.44772 19 3 19H7.31374L14.1924 12.1214C15.364 10.9498 17.2635 10.9498 18.435 12.1214L22 15.6863V6C22 5.44772 21.5523 5 21 5ZM21 19H10.1422L15.6066 13.5356C15.9971 13.145 16.6303 13.145 17.0208 13.5356L21.907 18.4217C21.7479 18.7633 21.4016 19 21 19Z" fill="currentColor" /></svg>';

                var findImgButton = document.createElement('button');
                findImgButton.className = 'aiautotool_btn_v1 aiautotool_btn_v13';
                findImgButton.id = 'find-img-button';
                findImgButton.innerHTML = '<i class="fa-solid fa-image"></i> Find Img';

                var youtubeButton = document.createElement('button');
                youtubeButton.id = 'youtube-button';
                youtubeButton.className = ' aiautotool_btn_v1 aiautotool_btn_v13';


                youtubeButton.innerHTML = '<i class="fa-solid fa-video"></i> Find Video';

                var writeButton = document.createElement('button');
                writeButton.id = 'write-button';
                writeButton.className = 'aiautotool_btn_v1 aiautotool_btn_v13 ';
                writeButton.innerHTML = '<i class="fa-solid fa-pen-nib"></i> Write';

                var divdrop = document.createElement('div');
                divdrop.className = 'aiautotool_dropdown';
                // Đảm bảo dropdown container có position relative
                divdrop.style.position = 'relative';
                divdrop.style.display = 'inline-block';

                var bardrewrite = document.createElement('button');
                bardrewrite.id = 'bardrewrite';
                bardrewrite.className = ' aiautotool_btn_v1 aiautotool_btn_v13   ';


                bardrewrite.innerHTML = '<i class="fa-solid fa-pen-nib"></i> Rewrite';


                var submenu = document.createElement('div');
                submenu.className = 'aiautotool_dropdown-content';
                submenu.style.display = 'none';
                var columnDiv = document.createElement('div');
                columnDiv.className = 'column';

                // Tạo các menu items và gắn event listeners ngay
                var submenuItem1 = document.createElement('div');
                submenuItem1.className = 'mce-menu-item';
                submenuItem1.id = 'submenuItem1';
                submenuItem1.innerHTML = '<i class="fa-solid fa-arrow-down-long" style="margin-right:6px; color:#6b7280;"></i> Shorter';
                submenuItem1.style.cursor = 'pointer';
                submenuItem1.style.padding = '8px 12px';
                submenuItem1.style.textAlign = 'left';
                submenuItem1.addEventListener('mouseenter', function () {
                    this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
                });
                submenuItem1.addEventListener('mouseleave', function () {
                    this.style.backgroundColor = '';
                });

                var submenuItem2 = document.createElement('div');
                submenuItem2.className = 'mce-menu-item';
                submenuItem2.id = 'submenuItem2';
                submenuItem2.innerHTML = '<i class="fa-solid fa-arrow-up-long" style="margin-right:6px; color:#6b7280;"></i> Longer';
                submenuItem2.style.cursor = 'pointer';
                submenuItem2.style.padding = '8px 12px';

                submenuItem2.style.textAlign = 'left';
                submenuItem2.addEventListener('mouseenter', function () {
                    this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
                });
                submenuItem2.addEventListener('mouseleave', function () {
                    this.style.backgroundColor = '';
                });

                var submenuItem3 = document.createElement('div');
                submenuItem3.className = 'mce-menu-item';
                submenuItem3.id = 'submenuItem3';
                submenuItem3.innerHTML = '<i class="fa-solid fa-briefcase" style="margin-right:6px; color:#6b7280;"></i> Professional';
                submenuItem3.style.cursor = 'pointer';
                submenuItem3.style.padding = '8px 12px';
                submenuItem3.style.textAlign = 'left';

                submenuItem3.addEventListener('mouseenter', function () {
                    this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
                });
                submenuItem3.addEventListener('mouseleave', function () {
                    this.style.backgroundColor = '';
                });

                var submenuRemoteRewrite = document.createElement('div');
                submenuRemoteRewrite.className = 'mce-menu-item';
                submenuRemoteRewrite.id = 'submenuRemoteRewrite';
                submenuRemoteRewrite.innerHTML = '<i class="fa-solid fa-globe" style="margin-right:6px; color:#6b7280;"></i> Remote Content & Rewrite';
                submenuRemoteRewrite.style.cursor = 'pointer';
                submenuRemoteRewrite.style.padding = '8px 12px';
                submenuRemoteRewrite.style.textAlign = 'left';
                submenuRemoteRewrite.addEventListener('mouseenter', function () {
                    this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
                });
                submenuRemoteRewrite.addEventListener('mouseleave', function () {
                    this.style.backgroundColor = '';
                });

                columnDiv.appendChild(submenuItem1);
                columnDiv.appendChild(submenuItem2);
                columnDiv.appendChild(submenuItem3);
                columnDiv.appendChild(submenuRemoteRewrite);
                submenu.appendChild(columnDiv);

                // Đảm bảo button có position relative để submenu định vị đúng
                bardrewrite.style.position = 'relative';

                // Tạo một bridge element vô hình để lấp đầy khoảng trống giữa button và submenu
                var submenuBridge = document.createElement('div');
                submenuBridge.style.position = 'absolute';
                submenuBridge.style.top = '100%';
                submenuBridge.style.left = '0';
                submenuBridge.style.width = '100%';
                submenuBridge.style.height = '8px'; // Chiều cao để lấp đầy khoảng trống
                submenuBridge.style.zIndex = '999998';
                submenuBridge.style.backgroundColor = 'transparent';
                submenuBridge.style.pointerEvents = 'auto';
                submenuBridge.style.marginTop = '0';

                // Cải thiện CSS cho submenu - đặt ngay sát button, dùng margin-top âm để loại bỏ khoảng trống
                submenu.style.position = 'absolute';
                submenu.style.top = '100%';
                submenu.style.left = '0';
                submenu.style.minWidth = '200px';
                submenu.style.zIndex = '999999';
                submenu.style.backgroundColor = '#f9f9f9';
                submenu.style.boxShadow = '0 8px 16px 0 rgba(0,0,0,0.2)';
                submenu.style.borderRadius = '4px';
                submenu.style.marginTop = '-8px'; // Margin âm để submenu gần button, lấp đầy khoảng trống
                submenu.style.padding = '4px 0';
                submenu.style.paddingTop = '8px'; // Padding-top để bù lại margin âm

                // Thêm bridge vào button trước
                bardrewrite.appendChild(submenuBridge);
                // Thêm submenu vào button sau bridge
                bardrewrite.appendChild(submenu);

                // Sử dụng timeout để tránh submenu bị ẩn quá nhanh
                let submenuTimeout;
                var showSubmenu = function () {
                    clearTimeout(submenuTimeout);
                    submenu.style.display = 'block';
                };

                var hideSubmenu = function () {
                    submenuTimeout = setTimeout(function () {
                        submenu.style.display = 'none';
                    }, 150);
                };

                // Event listeners cho button
                bardrewrite.addEventListener('mouseenter', showSubmenu);
                bardrewrite.addEventListener('mouseleave', hideSubmenu);

                // Event listeners cho bridge element - QUAN TRỌNG để lấp đầy khoảng trống
                // Bridge sẽ giữ submenu hiển thị khi chuột di chuyển qua khoảng trống
                submenuBridge.addEventListener('mouseenter', showSubmenu);
                submenuBridge.addEventListener('mouseleave', function () {
                    // Không ẩn submenu ngay khi rời khỏi bridge, để người dùng có thể di chuyển vào submenu
                    // Timeout sẽ được xử lý bởi submenu's mouseleave
                });

                // Event listeners cho submenu
                submenu.addEventListener('mouseenter', showSubmenu);
                submenu.addEventListener('mouseleave', hideSubmenu);

                // Event listeners cho columnDiv
                columnDiv.addEventListener('mouseenter', showSubmenu);
                columnDiv.addEventListener('mouseleave', hideSubmenu);

                // Event listeners cho divdrop (dropdown container) - QUAN TRỌNG
                divdrop.addEventListener('mouseenter', showSubmenu);
                divdrop.addEventListener('mouseleave', hideSubmenu);

                divdrop.appendChild(bardrewrite);

                // Tạo dropdown container cho ChatGPT button
                var chatgptDropdown = document.createElement('div');
                chatgptDropdown.className = 'aiautotool_dropdown';
                chatgptDropdown.style.position = 'relative';
                chatgptDropdown.style.display = 'inline-block';

                var chatgptButton = document.createElement('button');
                chatgptButton.id = 'chatgpt-button';
                chatgptButton.className = 'aiautotool_btn_v1 aiautotool_btn_v13';
                chatgptButton.innerHTML = '<i class="fa-solid fa-pen-nib"></i> Write More';
                chatgptButton.style.position = 'relative';

                // Tạo submenu cho ChatGPT dropdown
                var chatgptSubmenu = document.createElement('div');
                chatgptSubmenu.className = 'aiautotool_dropdown-content';
                chatgptSubmenu.style.display = 'none';
                var chatgptColumnDiv = document.createElement('div');
                chatgptColumnDiv.className = 'column';

                // Tạo các menu items cho các model
                // Gemini 2.5 Flash
                var chatgptMenuItem1 = document.createElement('div');
                chatgptMenuItem1.className = 'mce-menu-item';
                chatgptMenuItem1.id = 'chatgptMenuItem1';
                chatgptMenuItem1.innerHTML = '<i class="fa-solid fa-robot" style="margin-right:6px; color:#6b7280;"></i> Gemini 2.5 flask';
                chatgptMenuItem1.style.cursor = 'pointer';
                chatgptMenuItem1.style.padding = '8px 12px';
                chatgptMenuItem1.style.textAlign = 'left';
                chatgptMenuItem1.addEventListener('mouseenter', function () {
                    this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
                });
                chatgptMenuItem1.addEventListener('mouseleave', function () {
                    this.style.backgroundColor = '';
                });

                // GPT-4o
                var chatgptMenuItem2 = document.createElement('div');
                chatgptMenuItem2.className = 'mce-menu-item';
                chatgptMenuItem2.id = 'chatgptMenuItem2';
                chatgptMenuItem2.innerHTML = '<i class="fa-solid fa-brain" style="margin-right:6px; color:#6b7280;"></i> GPT-4o';
                chatgptMenuItem2.style.cursor = 'pointer';
                chatgptMenuItem2.style.padding = '8px 12px';
                chatgptMenuItem2.style.textAlign = 'left';
                chatgptMenuItem2.addEventListener('mouseenter', function () {
                    this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
                });
                chatgptMenuItem2.addEventListener('mouseleave', function () {
                    this.style.backgroundColor = '';
                });

                // Mistral Large
                var chatgptMenuItem3 = document.createElement('div');
                chatgptMenuItem3.className = 'mce-menu-item';
                chatgptMenuItem3.id = 'chatgptMenuItem3';
                chatgptMenuItem3.innerHTML = '<i class="fa-solid fa-bolt" style="margin-right:6px; color:#6b7280;"></i> Mistral Large';
                chatgptMenuItem3.style.cursor = 'pointer';
                chatgptMenuItem3.style.padding = '8px 12px';
                chatgptMenuItem3.style.textAlign = 'left';
                chatgptMenuItem3.addEventListener('mouseenter', function () {
                    this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
                });
                chatgptMenuItem3.addEventListener('mouseleave', function () {
                    this.style.backgroundColor = '';
                });

                // Llama 3
                var chatgptMenuItem4 = document.createElement('div');
                chatgptMenuItem4.className = 'mce-menu-item';
                chatgptMenuItem4.id = 'chatgptMenuItem4';
                chatgptMenuItem4.innerHTML = '<i class="fa-solid fa-code" style="margin-right:6px; color:#6b7280;"></i> Llama 3';
                chatgptMenuItem4.style.cursor = 'pointer';
                chatgptMenuItem4.style.padding = '8px 12px';
                chatgptMenuItem4.style.textAlign = 'left';
                chatgptMenuItem4.addEventListener('mouseenter', function () {
                    this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
                });
                chatgptMenuItem4.addEventListener('mouseleave', function () {
                    this.style.backgroundColor = '';
                });

                // Thêm các menu items vào column
                chatgptColumnDiv.appendChild(chatgptMenuItem1);
                chatgptColumnDiv.appendChild(chatgptMenuItem2);
                chatgptColumnDiv.appendChild(chatgptMenuItem3);
                chatgptColumnDiv.appendChild(chatgptMenuItem4);
                chatgptSubmenu.appendChild(chatgptColumnDiv);

                // Tạo bridge element cho ChatGPT dropdown
                var chatgptSubmenuBridge = document.createElement('div');
                chatgptSubmenuBridge.style.position = 'absolute';
                chatgptSubmenuBridge.style.top = '100%';
                chatgptSubmenuBridge.style.left = '0';
                chatgptSubmenuBridge.style.width = '100%';
                chatgptSubmenuBridge.style.height = '8px';
                chatgptSubmenuBridge.style.zIndex = '999998';
                chatgptSubmenuBridge.style.backgroundColor = 'transparent';
                chatgptSubmenuBridge.style.pointerEvents = 'auto';
                chatgptSubmenuBridge.style.marginTop = '0';

                // CSS cho ChatGPT submenu
                chatgptSubmenu.style.position = 'absolute';
                chatgptSubmenu.style.top = '100%';
                chatgptSubmenu.style.left = '0';
                chatgptSubmenu.style.minWidth = '200px';
                chatgptSubmenu.style.zIndex = '999999';
                chatgptSubmenu.style.backgroundColor = '#f9f9f9';
                chatgptSubmenu.style.boxShadow = '0 8px 16px 0 rgba(0,0,0,0.2)';
                chatgptSubmenu.style.borderRadius = '4px';
                chatgptSubmenu.style.marginTop = '-8px';
                chatgptSubmenu.style.padding = '4px 0';
                chatgptSubmenu.style.paddingTop = '8px';

                // Thêm bridge và submenu vào button
                chatgptButton.appendChild(chatgptSubmenuBridge);
                chatgptButton.appendChild(chatgptSubmenu);

                // Sử dụng timeout để tránh submenu bị ẩn quá nhanh
                let chatgptSubmenuTimeout;
                var showChatgptSubmenu = function () {
                    clearTimeout(chatgptSubmenuTimeout);
                    chatgptSubmenu.style.display = 'block';
                };

                var hideChatgptSubmenu = function () {
                    chatgptSubmenuTimeout = setTimeout(function () {
                        chatgptSubmenu.style.display = 'none';
                    }, 150);
                };

                // Event listeners cho ChatGPT button
                chatgptButton.addEventListener('mouseenter', showChatgptSubmenu);
                chatgptButton.addEventListener('mouseleave', hideChatgptSubmenu);

                // Event listeners cho bridge element
                chatgptSubmenuBridge.addEventListener('mouseenter', showChatgptSubmenu);
                chatgptSubmenuBridge.addEventListener('mouseleave', function () {
                    // Không ẩn submenu ngay khi rời khỏi bridge
                });

                // Event listeners cho submenu
                chatgptSubmenu.addEventListener('mouseenter', showChatgptSubmenu);
                chatgptSubmenu.addEventListener('mouseleave', hideChatgptSubmenu);

                // Event listeners cho columnDiv
                chatgptColumnDiv.addEventListener('mouseenter', showChatgptSubmenu);
                chatgptColumnDiv.addEventListener('mouseleave', hideChatgptSubmenu);

                // Event listeners cho dropdown container
                chatgptDropdown.addEventListener('mouseenter', showChatgptSubmenu);
                chatgptDropdown.addEventListener('mouseleave', hideChatgptSubmenu);

                // Thêm button vào dropdown container
                chatgptDropdown.appendChild(chatgptButton);

                // Thêm button gợi ý hình ảnh
                var suggestImageButton = document.createElement('button');
                suggestImageButton.id = 'suggest-image-button';
                suggestImageButton.className = 'aiautotool_btn_v1 aiautotool_btn_v13';
                suggestImageButton.innerHTML = '<i class="fa-solid fa-magic"></i> Suggest Images';

                // Thêm button Write with Agent (AI Agent SSE)
                var writeAgentButton = document.createElement('button');
                writeAgentButton.id = 'write-agent-button';
                writeAgentButton.className = 'aiautotool_btn_v1 aiautotool_btn_v13';
                writeAgentButton.innerHTML = '<i class="fa-solid fa-robot"></i> Write with Agent';
                writeAgentButton.title = 'Use AI Agent to write article with image, categories, and tags';

                tabbar.appendChild(youtubeButton);
                tabbar.appendChild(findImgButton);
                tabbar.appendChild(chatgptDropdown);
                tabbar.appendChild(suggestImageButton);
                tabbar.appendChild(writeAgentButton);
                tabbar.appendChild(divdrop);

                document.body.appendChild(tabbar);

                // Attach event listeners - các element đã được tạo ở trên
                if (submenuItem1) {
                    submenuItem1.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        submenu.style.display = 'none';

                        // Thực hiện công việc khi bấm vào Submenu Item 1
                        open_box_aiautotool();
                        openTab('aiContentTab');
                        var selectedText = '';
                        if (editor.selection) {
                            selectedText = editor.selection.getContent({ format: 'text' });
                        }
                        var titleValue = selectedText;

                        var post_language = get_lang();

                        if (post_language.length) {
                            // Nếu tồn tại, lấy giá trị của #aiautotool_title
                            post_language = post_language;

                        } else {
                            post_language = langcheck;
                        }


                        if (!selectedText.trim()) {
                            if (Swal) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Please select text in the content.',
                                    icon: 'error',
                                    confirmButtonText: 'Close'
                                });
                            } else {
                                alert('Please select text in the content');
                            }

                            return;
                        }
                        var divId = "outbard"; // Thay đổi ID của div tại đây


                        if (languageCodes.hasOwnProperty(post_language)) {
                            langcheck = languageCodes[post_language];

                        }

                        sendbardToServerrewrite(titleValue, divId, 'bardrewrite', langcheck, 'Make text shorten.')
                            .catch((error) => {
                                console.error('Error rewriting text:', error);
                                if (typeof showError === 'function') {
                                    showError('Failed to rewrite text. Please try again.');
                                } else if (typeof Swal !== 'undefined') {
                                    Swal.fire({
                                        title: 'Error!',
                                        text: 'Failed to rewrite text. Please try again.',
                                        icon: 'error',
                                        confirmButtonText: 'Close'
                                    });
                                } else {
                                    alert('Failed to rewrite text: ' + (error.message || 'Unknown error'));
                                }
                            });
                    });
                }

                if (submenuItem2) {
                    submenuItem2.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        submenu.style.display = 'none';

                        open_box_aiautotool();
                        openTab('aiContentTab');
                        var selectedText = '';
                        if (editor.selection) {
                            selectedText = editor.selection.getContent({ format: 'text' });
                        }
                        var titleValue = selectedText;

                        var post_language = get_lang();

                        if (post_language.length) {
                            // Nếu tồn tại, lấy giá trị của #aiautotool_title
                            post_language = post_language;

                        } else {
                            post_language = langcheck;
                        }


                        if (!titleValue.trim()) {
                            if (Swal) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Please select text in the content.',
                                    icon: 'error',
                                    confirmButtonText: 'Close'
                                });
                            } else {
                                alert('Please select text in the content');
                            }

                            return;
                        }
                        var divId = "outbard"; // Thay đổi ID của div tại đây


                        if (languageCodes.hasOwnProperty(post_language)) {
                            langcheck = languageCodes[post_language];

                        }

                        sendbardToServerrewrite(titleValue, divId, 'bardrewrite', langcheck, 'Make text longer tone of voice.')
                            .catch((error) => {
                                console.error('Error rewriting text:', error);
                                if (typeof showError === 'function') {
                                    showError('Failed to rewrite text. Please try again.');
                                } else if (typeof Swal !== 'undefined') {
                                    Swal.fire({
                                        title: 'Error!',
                                        text: 'Failed to rewrite text. Please try again.',
                                        icon: 'error',
                                        confirmButtonText: 'Close'
                                    });
                                } else {
                                    alert('Failed to rewrite text: ' + (error.message || 'Unknown error'));
                                }
                            });
                    });
                }

                if (submenuItem3) {
                    submenuItem3.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        submenu.style.display = 'none';

                        open_box_aiautotool();
                        openTab('aiContentTab');
                        var selectedText = '';
                        if (editor.selection) {
                            selectedText = editor.selection.getContent({ format: 'text' });
                        }
                        var titleValue = selectedText;

                        var post_language = get_lang();

                        if (post_language.length) {
                            // Nếu tồn tại, lấy giá trị của #aiautotool_title
                            post_language = post_language;

                        } else {
                            post_language = langcheck;
                        }


                        if (!titleValue.trim()) {
                            if (Swal) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Please select text in the content.',
                                    icon: 'error',
                                    confirmButtonText: 'Close'
                                });
                            } else {
                                alert('Please select text in the content');
                            }

                            return;
                        }
                        var divId = "outbard"; // Thay đổi ID của div tại đây


                        if (languageCodes.hasOwnProperty(post_language)) {
                            langcheck = languageCodes[post_language];

                        }

                        sendbardToServerrewrite(titleValue, divId, 'bardrewrite', langcheck, 'Make text use professional tone of voice.')
                            .catch((error) => {
                                console.error('Error rewriting text:', error);
                                if (typeof showError === 'function') {
                                    showError('Failed to rewrite text. Please try again.');
                                } else if (typeof Swal !== 'undefined') {
                                    Swal.fire({
                                        title: 'Error!',
                                        text: 'Failed to rewrite text. Please try again.',
                                        icon: 'error',
                                        confirmButtonText: 'Close'
                                    });
                                } else {
                                    alert('Failed to rewrite text: ' + (error.message || 'Unknown error'));
                                }
                            });
                    });
                }

                if (submenuRemoteRewrite) {
                    submenuRemoteRewrite.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        submenu.style.display = 'none';

                        if (typeof showRemoteRewriteModal === 'function') {
                            showRemoteRewriteModal();
                        } else {
                            alert('Remote Rewrite module not loaded.');
                        }
                    });
                }

                // Event listeners cho ChatGPT dropdown menu items
                if (chatgptMenuItem1) {
                    chatgptMenuItem1.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        chatgptSubmenu.style.display = 'none';

                        // Lấy selected text từ editor
                        open_box_aiautotool();
                        openTab('aiContentTab');
                        var selectedText = '';
                        if (editor.selection) {
                            selectedText = editor.selection.getContent({ format: 'text' });
                        }

                        var post_language = get_lang();
                        if (post_language.length) {
                            post_language = post_language;
                        } else {
                            post_language = langcheck;
                        }

                        if (!selectedText.trim()) {
                            if (Swal) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Please select text in the content.',
                                    icon: 'error',
                                    confirmButtonText: 'Close'
                                });
                            } else {
                                alert('Please select text in the content');
                            }
                            return;
                        }

                        var divId = "outbard";
                        if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                            langcheck = languageCodes[post_language];
                        }

                        // Tạo prompt để viết thêm nội dung
                        var writeMorePrompt = 'Viết thêm nội dung chi tiết và mở rộng cho đoạn văn sau:\n\n' + selectedText + '\n\nYêu cầu: Viết thêm nội dung một cách tự nhiên, chi tiết, và liên quan đến đoạn văn đã cho. Giữ nguyên phong cách và giọng điệu. không hỏi lại tôi. không nói thêm điều gì ngoài nội dung cần viết';

                        var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
                        if (sendFn) {
                            sendFn(writeMorePrompt, divId, 'writemore', langcheck, 'gemini-2.5-flash-lite')
                                .catch((error) => {
                                    console.error('Error generating content with Gemini 2.5 Flash:', error);
                                    if (typeof showError === 'function') {
                                        showError('Failed to generate content. Please try again.');
                                    } else if (typeof Swal !== 'undefined') {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'Failed to generate content. Please try again.',
                                            icon: 'error',
                                            confirmButtonText: 'Close'
                                        });
                                    } else {
                                        alert('Failed to generate content: ' + (error.message || 'Unknown error'));
                                    }
                                });
                        }
                    });
                }

                if (chatgptMenuItem2) {
                    chatgptMenuItem2.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        chatgptSubmenu.style.display = 'none';

                        // Lấy selected text từ editor
                        open_box_aiautotool();
                        openTab('aiContentTab');
                        var selectedText = '';
                        if (editor.selection) {
                            selectedText = editor.selection.getContent({ format: 'text' });
                        }

                        var post_language = get_lang();
                        if (post_language.length) {
                            post_language = post_language;
                        } else {
                            post_language = langcheck;
                        }

                        if (!selectedText.trim()) {
                            if (Swal) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Please select text in the content.',
                                    icon: 'error',
                                    confirmButtonText: 'Close'
                                });
                            } else {
                                alert('Please select text in the content');
                            }
                            return;
                        }

                        var divId = "outbard";
                        if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                            langcheck = languageCodes[post_language];
                        }

                        // Tạo prompt để viết thêm nội dung
                        var writeMorePrompt = 'Viết thêm nội dung chi tiết và mở rộng cho đoạn văn sau:\n\n' + selectedText + '\n\nYêu cầu: Viết thêm nội dung một cách tự nhiên, chi tiết, và liên quan đến đoạn văn đã cho. Giữ nguyên phong cách và giọng điệu. tuân thủ chỉ viết nội dung, không hỏi lại tôi. không nói thêm điều gì ngoài nội dung cần viết';

                        var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
                        if (sendFn) {
                            sendFn(writeMorePrompt, divId, 'writemore', langcheck, 'gpt-5-mini')
                                .catch((error) => {
                                    console.error('Error generating content with GPT-4o:', error);
                                    if (typeof showError === 'function') {
                                        showError('Failed to generate content. Please try again.');
                                    } else if (typeof Swal !== 'undefined') {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'Failed to generate content. Please try again.',
                                            icon: 'error',
                                            confirmButtonText: 'Close'
                                        });
                                    } else {
                                        alert('Failed to generate content: ' + (error.message || 'Unknown error'));
                                    }
                                });
                        }
                    });
                }

                if (chatgptMenuItem3) {
                    chatgptMenuItem3.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        chatgptSubmenu.style.display = 'none';

                        // Lấy selected text từ editor
                        open_box_aiautotool();
                        openTab('aiContentTab');
                        var selectedText = '';
                        if (editor.selection) {
                            selectedText = editor.selection.getContent({ format: 'text' });
                        }

                        var post_language = get_lang();
                        if (post_language.length) {
                            post_language = post_language;
                        } else {
                            post_language = langcheck;
                        }

                        if (!selectedText.trim()) {
                            if (Swal) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Please select text in the content.',
                                    icon: 'error',
                                    confirmButtonText: 'Close'
                                });
                            } else {
                                alert('Please select text in the content');
                            }
                            return;
                        }

                        var divId = "outbard";
                        if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                            langcheck = languageCodes[post_language];
                        }

                        // Tạo prompt để viết thêm nội dung
                        var writeMorePrompt = 'Viết thêm nội dung chi tiết và mở rộng cho đoạn văn sau:\n\n' + selectedText + '\n\nYêu cầu: Viết thêm nội dung một cách tự nhiên, chi tiết, và liên quan đến đoạn văn đã cho. Giữ nguyên phong cách và giọng điệu.không hỏi lại tôi. không nói thêm điều gì ngoài nội dung cần viết';

                        var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
                        if (sendFn) {
                            sendFn(writeMorePrompt, divId, 'writemore', langcheck, '')
                                .catch((error) => {
                                    console.error('Error generating content with Mistral Large:', error);
                                    if (typeof showError === 'function') {
                                        showError('Failed to generate content. Please try again.');
                                    } else if (typeof Swal !== 'undefined') {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'Failed to generate content. Please try again.',
                                            icon: 'error',
                                            confirmButtonText: 'Close'
                                        });
                                    } else {
                                        alert('Failed to generate content: ' + (error.message || 'Unknown error'));
                                    }
                                });
                        }
                    });
                }

                if (chatgptMenuItem4) {
                    chatgptMenuItem4.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        chatgptSubmenu.style.display = 'none';

                        // Lấy selected text từ editor
                        open_box_aiautotool();
                        openTab('aiContentTab');
                        var selectedText = '';
                        if (editor.selection) {
                            selectedText = editor.selection.getContent({ format: 'text' });
                        }

                        var post_language = get_lang();
                        if (post_language.length) {
                            post_language = post_language;
                        } else {
                            post_language = langcheck;
                        }

                        if (!selectedText.trim()) {
                            if (Swal) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Please select text in the content.',
                                    icon: 'error',
                                    confirmButtonText: 'Close'
                                });
                            } else {
                                alert('Please select text in the content');
                            }
                            return;
                        }

                        var divId = "outbard";
                        if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                            langcheck = languageCodes[post_language];
                        }

                        // Tạo prompt để viết thêm nội dung
                        var writeMorePrompt = 'Viết thêm nội dung chi tiết và mở rộng cho đoạn văn sau:\n\n' + selectedText + '\n\nYêu cầu: Viết thêm nội dung một cách tự nhiên, chi tiết, và liên quan đến đoạn văn đã cho. Giữ nguyên phong cách và giọng điệu. không hỏi lại tôi. không nói thêm điều gì ngoài nội dung cần viết';

                        var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
                        if (sendFn) {
                            sendFn(writeMorePrompt, divId, 'writemore', langcheck, '')
                                .catch((error) => {
                                    console.error('Error generating content with Llama 3:', error);
                                    if (typeof showError === 'function') {
                                        showError('Failed to generate content. Please try again.');
                                    } else if (typeof Swal !== 'undefined') {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'Failed to generate content. Please try again.',
                                            icon: 'error',
                                            confirmButtonText: 'Close'
                                        });
                                    } else {
                                        alert('Failed to generate content: ' + (error.message || 'Unknown error'));
                                    }
                                });
                        }
                    });
                }

                editor.on('mouseup keyup', function () {
                    // Kiểm tra xem có văn bản nào đang được chọn hay không
                    if (editor.selection) {
                        var selectedText = editor.selection.getContent({ format: 'text' });
                        if (selectedText != '') {

                            var Writingstyle = jQuery('#Writingstyle').val();

                            var Writingtone = jQuery('#Writingtone').val();

                            var selectionRange = editor.selection.getRng();
                            var selectionRect = selectionRange.getBoundingClientRect();

                            // Tính toán vị trí của tabbar
                            var editorRect = editor.getContainer().getBoundingClientRect();
                            var tabbarLeft = editorRect.left + selectionRect.left;
                            var tabbarTop = editorRect.top + selectionRect.bottom + window.pageYOffset;

                            // Hiển thị tabbar
                            tabbar.style.display = 'block';
                            tabbar.style.top = (tabbarTop - 50) + 'px';
                            tabbar.style.left = tabbarLeft + 'px';



                            // Gắn sự kiện cho các nút trong tabbar
                            youtubeButton.addEventListener('click', function (event) {
                                open_box_aiautotool();
                                openTab('videoTab');
                                jQuery('.infodiv').hide();
                                event.stopPropagation();
                                console.log('Find Video clicked');
                                console.log('Selected text:', selectedText);
                                // Gọi API tìm ảnh
                                // jQuery('#video_list_find').html('<div id="loading-icon" class="loader" style="display:block;width:100% !important;:100% !important"></div>');
                                showLoading();
                                openTab('videoTab');

                                jQuery.ajax({
	                                    url: aiautotoolGetMediaSearchUrl('youtubesearch'),
                                    type: 'GET',
                                    contentType: 'application/json',
                                    data: { q: selectedText },
                                    success: function (r) {
                                        if (r.result) {
                                            hideLoading();
                                            jQuery('#video_list_find').html('');

                                            r.result.forEach(function (video) {
                                                console.log(video)
                                                jQuery('#video_list_find').prepend('<div data-id="' + video.id + '" class="Youtube_thumb "><img src="' + video.thumbnails[0].url + '" /></div>');
                                            });
                                        }
                                    }
                                });
                                tabbar.style.display = 'none';
                            });

                            // Gắn sự kiện cho các nút trong tabbar
                            findImgButton.addEventListener('click', function (event) {
                                open_box_aiautotool();
                                openTab('imagesTab');
                                jQuery('.infodiv').hide();
                                event.stopPropagation();
                                console.log('Find Img clicked');
                                console.log('Selected text:', selectedText);
                                // Gọi API tìm ảnh
                                jQuery('#img_list_find').html('<div id="loading-icon" class="loader" style="display:block;width:100% !important;:100% !important"></div>');
                                openTab('imagesTab');

                                jQuery.ajax({
	                                    url: aiautotoolGetMediaSearchUrl('searchimg'),
                                    type: 'POST',
                                    contentType: 'application/json',
                                    data: JSON.stringify({ question: selectedText }),
                                    success: function (rrr) {
                                        if (rrr.result) {
                                            jQuery('#img_list_find').html('');

                                            rrr.result.forEach(function (url) {
                                                jQuery('#img_list_find').prepend('<div data-src="' + url + '" class="img_search"><img src="' + url + '"></div>');
                                            });
                                        }
                                    }
                                });

                                tabbar.style.display = 'none';
                            });
                            var aiautotool_btnwrite_content = '';
                            writeButton.addEventListener('click', function (event) {
                                if (!check_aipost_premium()) {
                                    if (Swal) {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'AI Post Limit Quota. Please Upgrade Pro.',
                                            icon: 'error',
                                            confirmButtonText: 'Close'
                                        });
                                    } else {
                                        alert('AI Post Limit Quota. Please Upgrade Pro.');
                                    }

                                    return;
                                }
                                open_box_aiautotool();
                                openTab('aiContentTab');
                                var titleValue = selectedText;

                                var post_language = get_lang();

                                if (post_language.length) {
                                    // Nếu tồn tại, lấy giá trị của #aiautotool_title
                                    post_language = post_language;

                                } else {
                                    post_language = langcheck;
                                }


                                if (!titleValue.trim()) {
                                    if (Swal) {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'Please select text in the content.',
                                            icon: 'error',
                                            confirmButtonText: 'Close'
                                        });
                                    } else {
                                        alert('Please select text in the content');
                                    }

                                    return;
                                }
                                var divId = "outbard"; // Thay đổi ID của div tại đây


                                if (languageCodes.hasOwnProperty(post_language)) {
                                    langcheck = languageCodes[post_language];

                                }

                                var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
                                if (sendFn) {
                                    sendFn(titleValue, divId, 'writemore', langcheck)
                                        .catch((error) => {
                                            // Error message is already shown by sendbardToServer (Swal/alert)
                                            console.error('Error generating content:', error);
                                        });
                                }
                            });

                            bardrewrite.addEventListener('click', function (event) {
                            });

                            chatgptButton.addEventListener('click', function (event) {
                                if (!check_aipost_premium()) {
                                    if (Swal) {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'AI Post Limit Quota. Please Upgrade Pro.',
                                            icon: 'error',
                                            confirmButtonText: 'Close'
                                        });
                                    } else {
                                        alert('AI Post Limit Quota. Please Upgrade Pro.');
                                    }

                                    return;
                                }
                                open_box_aiautotool();
                                openTab('aiContentTab');
                                event.stopPropagation();
                                var titleValue = selectedText;
                                var post_language = get_lang();
                                if (languageCodes.hasOwnProperty(post_language)) {
                                    langcheck = languageCodes[post_language];

                                }
                                var divId = "outbard";

                                var sendFn2 = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
                                if (sendFn2) {
                                    sendFn2(titleValue, divId, 'writemore', langcheck, 'chatgpt')
                                        .catch((error) => {
                                            // Error message is already shown by sendbardToServer (Swal/alert)
                                            console.error('Error generating content with ChatGPT:', error);
                                        });
                                }
                            });


                            // Thêm event listener cho button gợi ý hình ảnh
                            suggestImageButton.addEventListener('click', function (event) {
                                if (!check_aipost_premium()) {
                                    if (Swal) {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'AI Post Limit Quota. Please Upgrade Pro.',
                                            icon: 'error',
                                            confirmButtonText: 'Close'
                                        });
                                    } else {
                                        alert('AI Post Limit Quota. Please Upgrade Pro.');
                                    }

                                    return;
                                }

                                // Bắt đầu quá trình gợi ý hình ảnh
                                startImageSuggestionProcess();
                                event.stopPropagation();
                            });

                            // Thêm event listener cho button Write with Agent
                            writeAgentButton.addEventListener('click', function (event) {
                                event.preventDefault();
                                event.stopPropagation();

                                // Get title from post
                                var title = get_title();
                                if (!title || title.trim() === '') {
                                    if (Swal) {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'Please enter a post title first.',
                                            icon: 'error',
                                            confirmButtonText: 'OK'
                                        });
                                    } else {
                                        alert('Please enter a post title first.');
                                    }
                                    return;
                                }

                                // Build prompt with title
                                var prompt = 'Viết bài viết về "' + title + '" với ảnh đại diện, thêm các category và tags phù hợp';

                                // Show loading
                                if (typeof showLoading === 'function') {
                                    showLoading('Starting AI Agent...');
                                }

                                // Call AI Agent with SSE
                                if (typeof executePromptWithAgent === 'function') {
                                    executePromptWithAgent(prompt, 'outbard')
                                        .then(() => {
                                            console.log('AI Agent completed successfully');
                                            if (typeof hideLoading === 'function') {
                                                hideLoading();
                                            }
                                        })
                                        .catch(error => {
                                            console.error('AI Agent error:', error);
                                            if (typeof hideLoading === 'function') {
                                                hideLoading();
                                            }
                                            if (Swal) {
                                                Swal.fire({
                                                    title: 'Error!',
                                                    text: 'AI Agent error: ' + error.message,
                                                    icon: 'error',
                                                    confirmButtonText: 'Close'
                                                });
                                            }
                                        });
                                } else {
                                    console.error('executePromptWithAgent function not found');
                                    if (typeof hideLoading === 'function') {
                                        hideLoading();
                                    }
                                    if (Swal) {
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'AI Agent not available. Please refresh the page.',
                                            icon: 'error',
                                            confirmButtonText: 'OK'
                                        });
                                    }
                                }
                            });

                        } else {
                            tabbar.style.display = 'none';
                        }


                    } else {
                        // Ẩn tabbar nếu không có nội dung nào được chọn
                        tabbar.style.display = 'none';
                        dangviet = false;
                    }
                    event.stopPropagation();
                });
            }
        }

    };
});
function createButton(idbutton = '', icon, text, clickHandler, buttonClass) {
    // Tạo một thẻ button
    var button = document.createElement("span");

    // Gán class cho button nếu được cung cấp
    if (buttonClass) {
        button.className = buttonClass;
    }
    button.id = idbutton;
    // Tạo một thẻ span để chứa icon
    var iconSpan = document.createElement("span");
    iconSpan.className = "icon"; // Thêm class "icon" để tùy chỉnh kiểu dáng icon
    button.type = 'button';
    // Thêm icon vào thẻ span
    iconSpan.innerHTML = icon + " ";

    // Tạo một thẻ span để chứa text
    var textSpan = document.createElement("span");
    textSpan.innerHTML = text;

    // Gắn icon và text vào button
    button.appendChild(iconSpan);
    button.appendChild(textSpan);

    // Gắn hàm xử lý sự kiện khi nút được click
    button.addEventListener("click", clickHandler);

    // Trả về button đã tạo
    return button;
}

function get_title() {
    var titleInput = document.getElementById('title');

    // Kiểm tra xem phần tử có tồn tại hay không
    if (titleInput) {
        console.log('Element with ID "title" exists.');

    } else {
        console.log('Element with ID "title" does not exist.');

        titleInput = document.getElementById('aiautotool_title');

        if (titleInput) {
            console.log('Element with ID "aiautotool_title" exists.');
        } else {
            titleInput = document.querySelector("div.edit-post-header-toolbar__left");
            console.log('Element with ID "h1.wp-block-post-title" does not exist.');
        }
    }
    return titleInput;
}



function get_lang() {
    var post_language = document.getElementById('post_language');

    // Kiểm tra xem phần tử có tồn tại hay không
    if (post_language) {
        console.log('Element with ID "title" exists.');

    } else {
        console.log('Element with ID "title" does not exist.');

        post_language = document.getElementById('post_language');

        if (post_language) {
            console.log('Element with ID "aiautotool_title" exists.');
        } else {
            console.log('Element with ID "aiautotool_title" does not exist.');
        }
    }
    return post_language.value;
}
function scrollToBottom() {
    var outbard = document.getElementById("outbard");
    if (outbard) {
        outbard.scrollTop = outbard.scrollHeight;
    }

}

// Hàm xử lý sự kiện khi nút được click
function handleButtonClick(event) {
    // Xử lý các button khác
    console.log('Button clicked:', event.target.id);
}


if (isEditOrNewPostPage()) {
    // Lấy input title
    var titleInput = get_title();

    // Tạo smart button groups thay vì các button riêng lẻ
    createSmartButtonGroups();

    // Tạo button AI Suggest Tag (giữ lại vì nó ở vị trí khác)
    var suggestTagButton = document.createElement('button');
    suggestTagButton.innerHTML = '<i class="fa-solid fa-tag"></i> AI Suggest Tag';
    suggestTagButton.setAttribute('type', 'button');
    suggestTagButton.setAttribute('id', 'ai-suggest-tag-button');
    suggestTagButton.setAttribute('class', 'button');

    // Lấy phần tử có id 'new-tag-post_tag'
    var newTagInput = document.getElementById('new-tag-post_tag');
    if (newTagInput) {
        // newTagInput.parentNode.insertBefore(suggestTagButton, newTagInput.nextSibling);

        suggestTagButton.addEventListener('click', function () {
            // Lấy giá trị của trường tiêu đề
            var titleInput = document.getElementById('title');
            var titleValue = titleInput.value.trim(); // Xóa khoảng trắng ở đầu và cuối chuỗi

            // Kiểm tra xem tiêu đề có rỗng không
            if (titleValue === '') {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Please enter the title of the post before suggesting tags.',
                        icon: 'error',
                        confirmButtonText: 'Close'
                    });
                } else {
                    alert('Please enter the title of the post before suggesting tags.');
                }
                return;
            } else {
                suggestTags();
            }
        });
    }

    const aiautotoolDiv = document.createElement('div');
    aiautotoolDiv.id = 'aiautotool_bar_right';

    document.body.appendChild(aiautotoolDiv);

    // Kiểm tra xem có phần tử có id là "aiautotool-meta-box" hay không
    var metaBoxElement = document.getElementById("aiautotool-meta-box");

    // Kiểm tra xem phần tử có tồn tại hay không
    if (metaBoxElement) {
        // Nếu tồn tại, thực hiện các thao tác khác ở đây

        metaBoxElement.parentNode.removeChild(metaBoxElement);
        var contentToMove = metaBoxElement.innerHTML;

        // Đặt nội dung vào div có id là "aiautotool_bar_right"

        aiautotoolDiv.innerHTML = contentToMove;
        removeAiautotoolWritingPanel();

        // Di chuyển modal container ra khỏi sidebar và đặt vào body
        const modalContainer = aiautotoolDiv.querySelector(".aiautotool-modal-container");
        if (modalContainer) {
            document.body.appendChild(modalContainer);
        }
    } else {
        // Nếu không tồn tại, thông báo hoặc thực hiện các thao tác khác ở đây
        aiautotoolDiv.innerHTML = '';
        console.log("Không tìm thấy phần tử có id là 'aiautotool-meta-box'");
    }

    // Tạo và thêm button vào trang
    const toggleButton = document.createElement('div');
    toggleButton.id = 'toggleButton';
    toggleButton.className = 'aiautotool_btn_menu';

    toggleButton.innerText = 'Open Aiautotool';
    document.body.appendChild(toggleButton);

    const sidebar = document.getElementById('aiautotool_bar_right');
    const getSidebarClosedRight = () => {
        const sidebarWidth = sidebar ? sidebar.getBoundingClientRect().width : 600;
        return `-${Math.ceil(sidebarWidth)}px`;
    };

    toggleButton.addEventListener('click', () => {
        const sidebar = document.getElementById('aiautotool_bar_right');
        var toggleButton = document.getElementById('toggleButton');
        const isOpen = sidebar.style.right === '0px';

        if (isOpen) {
            sidebar.style.right = getSidebarClosedRight();
            toggleButton.classList.remove('open');
            toggleButton.innerText = 'Open Aiautotool';
        } else {
            sidebar.style.right = '0';
            toggleButton.classList.add('open');
            toggleButton.innerText = 'Close Aiautotool';
        }
    });


    function open_box_aiautotool() {
        const sidebar = document.getElementById('aiautotool_bar_right');
        var toggleButton = document.getElementById('toggleButton');
        const isOpen = sidebar.style.right === '0px';

        if (isOpen) {

        } else {
            sidebar.style.right = '0';
            toggleButton.classList.add('open');
            toggleButton.innerText = 'Close Aiautotool';
        }
    }










    // Khai báo các biến global cho việc xử lý post (sử dụng window để tránh redeclaration)
    // Chỉ khởi tạo một lần để tránh redeclaration error
    if (typeof window.aiautotool_post_vars_initialized === 'undefined') {
        window.aiautotool_post_vars_initialized = true;
        window.post = [];
        window.istrue = true;
        window.indexnow = 0;
    }

    function updatepost(keyToUpdate, data) {
        if (!window.post) window.post = [];
        var stext = '';
        var desc = '';
        if (data?.status == 'writing') {
            if (window.post && window.post[keyToUpdate]) {
                window.post[keyToUpdate].stext += data.sText;
            }
        } else if (data?.status == 'complete') {
            if (window.post && window.post[keyToUpdate] && window.post[keyToUpdate].desc == '') {
                window.post[keyToUpdate].desc = data.text;
            }
        }
    }

    function displayAllPosts(divId) {
        if (!window.post) window.post = [];
        let containerDiv = document.getElementById(divId);

        if (!containerDiv) {
            console.error(`Div with id ${divId} not found.`);
            return;
        }

        if (!window.post || window.post.length === 0) {
            return;
        }

        let stringhtml = '';

        for (let i = 0; i < window.post.length; i++) {
            let postItem = window.post[i];
            if (postItem.desc == '') {
                if (postItem.stext != '') {
                    stringhtml += '<h2>' + postItem.h2 + '</h2>' + markdown(removeMaskData(postItem.stext), false);
                }
            } else {
                stringhtml += '<h2>' + postItem.h2 + '</h2>' + markdown(removeMaskData(postItem.desc), false);
            }
        }
        aiautotool_content = stringhtml;
        jQuery("#" + divId).html(stringhtml);


        scrollToBottom()
    }

    function checkpost() {
        // Sử dụng window scope trực tiếp để tránh redeclaration
        if (!window.post) window.post = [];
        if (typeof window.indexnow === 'undefined') window.indexnow = 0;
        if (typeof window.istrue === 'undefined') window.istrue = true;

        if (window.post && window.post.length > 0) {
            console.log(window.indexnow, window.post.length);
            if (window.indexnow < (window.post.length - 1)) {
                if (window.istrue) {
                    for (let i = 0; i < window.post.length; i++) {
                        let postItem = window.post[i];
                        if (postItem.desc == '') {
                            window.istrue = false;
                            window.indexnow = i;
                            runpost(window.indexnow);
                            break;
                        }
                    }
                }
            } else {
                if (typeof checkpostin !== 'undefined') {
                    clearInterval(checkpostin);
                }
                jQuery('.btnaddpost').show();
                console.log('kết thúc');

            }
        }
    }

    function runpost(index) {
        if (!window.post) window.post = [];
        if (!window.post || !window.post[index]) {
            return;
        }
        idhead = Math.floor(Math.random() * 1000);
        headtitle = window.post[index].h2;


        var post_language = get_lang();
        if (languageCodes.hasOwnProperty(post_language)) {
            langcheck = languageCodes[post_language];

        }
        var divId = "outbard";

    }

    var checkpostin = setInterval(function () {
        checkpost();
    }, 1000);
}




const modalContainer = document.querySelector(".aiautotool-modal-container");
const openModalButton = document.querySelector("#open-modal");
const closeModalButton = document.querySelector(".aiautotool-modal-close");

if (openModalButton) {
    openModalButton.addEventListener("click", () => {
        if (modalContainer) {
            modalContainer.style.display = "block";
        }
    });
}
if (closeModalButton) {
    closeModalButton.addEventListener("click", () => {
        if (modalContainer) {
            modalContainer.style.display = "none";
        }
    });
}

// Thêm event listener cho overlay để đóng modal khi click bên ngoài
document.addEventListener('click', function (event) {
    if (modalContainer && modalContainer.style.display === "block") {
        const overlay = modalContainer.querySelector(".aiautotool-modal-overlay");
        if (event.target === overlay) {
            modalContainer.style.display = "none";
        }
    }
});


document.addEventListener('DOMContentLoaded', function () {
    // Tạo một button mới
    var suggestTagButton = document.createElement('button');
    suggestTagButton.innerHTML = '<i class="fa-solid fa-tag"></i> AI Suggest Tag';
    suggestTagButton.setAttribute('type', 'button');
    suggestTagButton.setAttribute('id', 'ai-suggest-tag-button');
    suggestTagButton.setAttribute('class', 'button');

    // Lấy phần tử có id 'new-tag-post_tag'
    var newTagInput = document.getElementById('new-tag-post_tag');
    if (newTagInput) {

        newTagInput.parentNode.insertBefore(suggestTagButton, newTagInput.nextSibling);

        suggestTagButton.addEventListener('click', function () {
            // Lấy giá trị của trường tiêu đề
            var titleInput = document.getElementById('title');
            var titleValue = titleInput.value.trim(); // Xóa khoảng trắng ở đầu và cuối chuỗi

            // Kiểm tra xem tiêu đề có rỗng không
            if (titleValue === '') {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Please enter the title of the post before suggesting tags.',
                        icon: 'error',
                        confirmButtonText: 'Close'
                    });
                } else {
                    alert('Please enter the title of the post before suggesting tags.');
                }
                return;
            } else {

                suggestTags();
            }
        });
    }

});



function suggestTags() {
    // Lấy giá trị của trường tiêu đề
    var titleInput = document.getElementById('title');
    var lang = get_lang();
    var titleValue = titleInput.value.trim();

    var data = {
        'action': 'aiautotool_suggest_tag',
        'title': titleValue,
        'lang': lang,
        'security': aiautotool_js_setting.security
    };
    showLoading('AI create tag');
    jQuery.ajax({
        url: aiautotool_js_setting.ajax_url,
        type: 'POST',
        data: data,
        beforeSend: function () {

        },
        success: function (response) {
            hideLoading();

            var tags = response.data.map(function (item) {
                return item.tag;
            }).join(', ');

            jQuery('#new-tag-post_tag').val(tags);
            console.log(tags);
        },
        error: function (xhr, status, error) {

            hideLoading();

            alert('Error: ' + error);
        }
    });
}



// Enhanced functionality for All tool for AI Post
function enhanceAllToolFunctionality() {
    // Add loading states to buttons
    function addLoadingState(button) {
        button.classList.add('loading');
        button.disabled = true;
        const originalText = button.textContent;
        button.setAttribute('data-original-text', originalText);
        button.textContent = 'Creating...';
    }

    function removeLoadingState(button) {
        button.classList.remove('loading');
        button.disabled = false;
        const originalText = button.getAttribute('data-original-text');
        if (originalText) {
            button.textContent = originalText;
        }
    }

    function addSuccessState(button) {
        button.classList.add('success');
        button.textContent = 'Created!';
        setTimeout(() => {
            button.classList.remove('success');
            const originalText = button.getAttribute('data-original-text');
            if (originalText) {
                button.textContent = originalText;
            }
        }, 2000);
    }

    function addErrorState(button) {
        button.classList.add('error');
        button.textContent = 'Error!';
        setTimeout(() => {
            button.classList.remove('error');
            const originalText = button.getAttribute('data-original-text');
            if (originalText) {
                button.textContent = originalText;
            }
        }, 3000);
    }

    // Enhanced tool request processing
    window.processToolRequest = function (type, inputId) {
        const inputElement = document.getElementById(inputId);
        const buttonElement = inputElement.nextElementSibling;
        const inputText = inputElement.value.trim();

        if (!inputText) {
            showError('Please enter a topic or keyword.');
            inputElement.focus();
            return;
        }

        if (!check_aipost_premium()) {
            showError('AI Post Limit Quota. Please Upgrade Pro.');
            return;
        }

        // Add loading state
        addLoadingState(buttonElement);

        // Get language settings
        const post_language = get_lang();
        let resolvedLang = '';
        if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
            resolvedLang = languageCodes[post_language];
        } else if (typeof langcheck !== 'undefined') {
            resolvedLang = langcheck;
        } else {
            resolvedLang = post_language;
        }

        // Open the AI tool sidebar
        open_box_aiautotool();

        // Close modal if open
        const modalClose = document.querySelector('.aiautotool-modal-close');
        if (modalClose) {
            modalClose.click();
        }

        const divId = "outbard";
        let text = '';

        // Enhanced prompts for better AI responses
        switch (type) {
            case "Outline":
                text = `Create a comprehensive and well-structured outline for an article about "${inputText}". 
                
Requirements:
- Include main topics and subtopics organized in a hierarchical numbered list format
- Make it SEO-friendly and engaging for readers
- Include 5-8 main sections with relevant subsections
- Focus on user intent and search optimization
- Structure should be logical and flow naturally

Format the response with clear headings and subheadings.`;
                break;

            case "Introduction":
                text = `Write an engaging and compelling introduction for an article titled "${inputText}".
                
Requirements:
- The introduction should be 50-100 words
- Hook the reader's attention with an interesting opening
- Clearly state the topic and its importance
- Provide a preview of what the article will cover
- Make it professional, engaging, and SEO-friendly
- Include a clear thesis statement or main argument`;
                break;

            case "Conclusion":
                text = `Write a strong and compelling conclusion for an article about "${inputText}".
                
Requirements:
- Summarize the key points discussed in the article
- Reinforce the main message and takeaways
- Provide a memorable ending that encourages reader engagement
- Include a call-to-action if appropriate
- Make it professional and impactful
- Tie back to the introduction and main thesis`;
                break;

            case "FAQ":
                text = `Create a comprehensive FAQ section for "${inputText}".
                
Requirements:
- Generate 5-8 frequently asked questions and detailed answers
- Make the questions relevant, specific, and user-focused
- Provide informative and easy-to-understand answers
- Format it clearly with Q&A structure
- Cover common concerns and pain points
- Include both basic and advanced questions
- Make answers actionable and helpful

Format as:
Q: [Question]
A: [Detailed answer]

Q: [Next question]
A: [Next answer]`;
                break;

            case "TitleSuggestion":
                text = `Generate 5-8 engaging and SEO-friendly title suggestions for an article about "${inputText}".
                
Requirements:
- Create titles that are compelling and click-worthy
- Optimize for search engines with relevant keywords
- Include different title formats (question, how-to, listicle, etc.)
- Make titles specific and benefit-focused
- Keep titles between 50-60 characters for optimal SEO
- Use power words that drive engagement
- Ensure titles accurately represent the content

Format the response as a numbered list with each title on a new line.`;
                break;

            case "MetaDescription":
                text = `Create 3-5 compelling meta descriptions for an article about "${inputText}".
                
Requirements:
- Keep each description between 150-160 characters for optimal SEO
- Include primary and secondary keywords naturally
- Make descriptions compelling and click-worthy
- Include a clear call-to-action
- Optimize for search engine snippets
- Use power words that drive engagement
- Ensure descriptions accurately represent the content

Format as a numbered list with each meta description on a new line.`;
                break;

            case "SocialMedia":
                text = `Generate engaging social media posts for "${inputText}" across different platforms.
                
Requirements:
- Create posts for Facebook, Twitter, LinkedIn, and Instagram
- Include relevant hashtags for each platform
- Make content engaging and shareable
- Include call-to-actions appropriate for each platform
- Optimize character count for each platform
- Use emojis and formatting to increase engagement
- Include platform-specific best practices

Format as:
Facebook: [Post content with hashtags]
Twitter: [Post content with hashtags]
LinkedIn: [Professional post content]
Instagram: [Visual-focused post with hashtags]`;
                break;

            case "ContentSummary":
                text = `Create a comprehensive summary of content about "${inputText}".
                
Requirements:
- Summarize the main points in 3-5 bullet points
- Include key takeaways and insights
- Make it easy to understand for different audiences
- Highlight the most important information
- Use clear and concise language
- Include actionable insights if applicable
- Keep summary under 200 words

Format as a structured summary with bullet points.`;
                break;

            case "KeywordResearch":
                text = `Research and suggest relevant keywords for "${inputText}".
                
Requirements:
- Generate 10-15 primary and long-tail keywords
- Include search volume estimates (high/medium/low)
- Suggest related keyword clusters
- Include keyword difficulty assessment
- Provide keyword intent (informational, navigational, transactional)
- Suggest content ideas based on keywords
- Include competitive analysis insights

Format as a structured keyword research report.`;
                break;

            case "ContentRewrite":
                text = `Rewrite content about "${inputText}" in different writing styles.
                
Requirements:
- Create 3 different versions: professional, casual, and creative
- Maintain the same core message and information
- Adapt tone and style for different audiences
- Include SEO optimization for each version
- Make each version engaging and readable
- Vary sentence structure and vocabulary
- Ensure consistency in accuracy and facts

Format as:
Professional Version: [Content]
Casual Version: [Content]
Creative Version: [Content]`;
                break;

            case "BlogPostIdeas":
                text = `Generate 10-15 blog post ideas related to "${inputText}".
                
Requirements:
- Include different content types (how-to, listicle, case study, etc.)
- Make ideas specific and actionable
- Include target audience for each idea
- Suggest content angles and perspectives
- Include potential keywords for each idea
- Make ideas engaging and shareable
- Consider seasonal and trending topics

Format as a numbered list with brief descriptions.`;
                break;

            case "ContentCalendar":
                text = `Create a content calendar strategy for "${inputText}".
                
Requirements:
- Plan content for the next 30 days
- Include different content types and formats
- Suggest posting frequency and timing
- Include content themes and topics
- Plan for different platforms (blog, social media, email)
- Include content goals and KPIs
- Consider seasonal events and trends

Format as a structured content calendar with dates, topics, and platforms.`;
                break;

            default:
                console.error("Unknown type: " + type);
                removeLoadingState(buttonElement);
                return;
        }

        // Send request to AI server
        // Use window.sendbardToServer if available, otherwise use global sendbardToServer
        var sendFunction = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : (typeof sendbardToServer !== 'undefined' ? sendbardToServer : null);

        if (!sendFunction) {
            console.error('sendbardToServer function not found');
            addErrorState(buttonElement);
            showError('AI function not available. Please refresh the page.');
            return;
        }

        sendFunction(text, divId, 'writemore', resolvedLang)
            .then(() => {
                addSuccessState(buttonElement);
                // Auto-scroll to results
                setTimeout(() => {
                    const outbardElement = document.getElementById('outbard');
                    if (outbardElement) {
                        outbardElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                }, 500);
            })
            .catch((error) => {
                // Error message is already shown by sendbardToServer (Swal/alert)
                // Just update button state
                console.error('Error processing tool request:', error);
                addErrorState(buttonElement);
                // Don't show error again as it's already displayed by sendbardToServer
            });
    };

    // Enhanced error display
    function showError(message) {
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Error!',
                text: message,
                icon: 'error',
                confirmButtonText: 'Close',
                customClass: {
                    popup: 'aiautotool-swal-popup',
                    title: 'aiautotool-swal-title',
                    content: 'aiautotool-swal-content'
                }
            });
        } else {
            alert('Error: ' + message);
        }
    }

    // Enhanced success display
    function showSuccess(message) {
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Success!',
                text: message,
                icon: 'success',
                confirmButtonText: 'Close'
            });
        } else {
            alert('Success: ' + message);
        }
    }

    // Add keyboard shortcuts
    document.addEventListener('keydown', function (event) {
        // Ctrl/Cmd + Enter to submit current tool
        if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
            const activeTool = document.querySelector('.tool-content:not([style*="display: none"])');
            if (activeTool) {
                const button = activeTool.querySelector('.aiautotool_input2_button');
                if (button && !button.disabled) {
                    button.click();
                }
            }
        }
    });

    // Add input validation and auto-save
    const toolInputs = document.querySelectorAll('.aiautotool_input2_input');
    toolInputs.forEach(input => {
        // Auto-save to localStorage
        input.addEventListener('input', function () {
            const key = `aiautotool_${input.id}_draft`;
            localStorage.setItem(key, input.value);
        });

        // Load draft on focus
        input.addEventListener('focus', function () {
            const key = `aiautotool_${input.id}_draft`;
            const draft = localStorage.getItem(key);
            if (draft && !input.value) {
                input.value = draft;
            }
        });

        // Clear draft on successful submission
        input.addEventListener('change', function () {
            const key = `aiautotool_${input.id}_draft`;
            localStorage.removeItem(key);
        });
    });

    // Add tool usage analytics
    function trackToolUsage(toolType) {
        if (typeof gtag !== 'undefined') {
            gtag('event', 'tool_usage', {
                'tool_type': toolType,
                'event_category': 'ai_tools',
                'event_label': 'all_tool_for_ai_post'
            });
        }
    }

    // Enhanced tool switching with animations
    window.changeType = function (newType) {
        // Update active button with smooth transition
        document.querySelectorAll('.aiautotool-tool-buttons span').forEach(btn => {
            btn.classList.remove('active');
        });

        const activeButton = document.getElementById('btn_' + newType.toLowerCase().replace(' ', '_'));
        if (activeButton) {
            activeButton.classList.add('active');
        }

        // Update content sections with fade animation
        document.querySelectorAll('.tool-content').forEach(content => {
            content.style.display = 'none';
            content.classList.remove('active');
        });

        // Show appropriate content section
        let targetContent;
        switch (newType) {
            case 'Outline':
                targetContent = document.getElementById('outline');
                document.getElementById('current_type').innerText = 'Suggest Outline By AI Auto Tool';
                break;
            case 'Introduction':
                targetContent = document.getElementById('introduction');
                break;
            case 'Conclusion':
                targetContent = document.getElementById('conclusion');
                break;
            case 'FAQ':
                targetContent = document.getElementById('faq');
                break;
        }

        if (targetContent) {
            targetContent.style.display = 'block';
            setTimeout(() => {
                targetContent.classList.add('active');
            }, 10);
        }

        // Update hidden input
        document.getElementById('type').value = newType;

        // Track usage
        trackToolUsage(newType);
    };

    // Add tool tips and help
    const toolDescriptions = {
        'Outline': 'Create a structured outline with main topics and subtopics for better content organization.',
        'Introduction': 'Generate an engaging opening that hooks readers and introduces your topic.',
        'Conclusion': 'Write a compelling ending that summarizes key points and provides closure.',
        'FAQ': 'Create helpful questions and answers to address common concerns about your topic.'
    };

    // Add help tooltips
    document.querySelectorAll('.tool-content h3').forEach(h3 => {
        const toolType = h3.textContent.replace('Suggest ', '').replace(' By AI Auto Tool', '').replace('Write ', '').replace('Create ', '');
        if (toolDescriptions[toolType]) {
            h3.title = toolDescriptions[toolType];
            h3.style.cursor = 'help';
        }
    });
}

// Initialize enhanced functionality when DOM is ready
document.addEventListener('DOMContentLoaded', function () {
    enhanceAllToolFunctionality();
});

// ===== CÁC FUNCTION XỬ LÝ GỢI Ý CHÈN HÌNH ẢNH TỰ ĐỘNG =====

// Function bắt đầu quá trình gợi ý hình ảnh
async function startImageSuggestionProcess() {
    try {
        // Hiển thị loading dialog
        Swal.fire({
            title: 'Processing...',
            html: `
                <div class="process-status">
                    <div class="step-indicator">
                        <div class="step">1</div>
                        <div class="step">2</div>
                        <div class="step">3</div>
                        <div class="step">4</div>
                        <div class="step">5</div>
                    </div>
                    <p>Starting image suggestion process...</p>
                </div>
            `,
            showConfirmButton: false,
            allowOutsideClick: false
        });

        // Delay để người dùng đọc thông báo
        await new Promise(resolve => setTimeout(resolve, 1500));

        // Step 1: Quét content trong editor
        updateProcessStatus('Step 1: Scanning article content...', 1);
        const content = getEditorContent();
        const title = getPostTitle();

        // Delay để người dùng theo dõi step 1
        await new Promise(resolve => setTimeout(resolve, 2000));

        if (!content || !title) {
            Swal.close();
            showError('Unable to retrieve article content. Please ensure you have entered a title and content.');
            return;
        }

        if (content.length < 100) {
            Swal.close();
            showError('Article content is too short. Please write at least 100 characters to suggest images.');
            return;
        }

        // Hiển thị thông tin về nội dung
        const contentLength = content.replace(/<[^>]*>/g, '').length;
        const estimatedChunks = Math.ceil(contentLength / 1500);

        if (contentLength > 1500) {
            updateProcessStatus(`Step 1: Long content (${contentLength} characters) - will be split into ${estimatedChunks} sections for processing...`, 1);
            await new Promise(resolve => setTimeout(resolve, 2000));
        }

        // Step 2: Xác định vị trí hợp lý để chèn hình ảnh
        updateProcessStatus('Step 2: Analyzing image insertion positions with AI...', 2);
        const imagePositions = await analyzeImagePositions(content);

        // Delay để người dùng theo dõi step 2
        await new Promise(resolve => setTimeout(resolve, 2500));

        if (imagePositions.length === 0) {
            Swal.close();
            showError('AI could not find suitable positions to insert images. Please write more detailed content.');
            return;
        }

        // Hiển thị thông tin về các vị trí được tìm thấy
        const uniqueChunks = [...new Set(imagePositions.map(p => p.aiDetails?.chunkIndex).filter(c => c !== null))];
        if (uniqueChunks.length > 1) {
            updateProcessStatus(`Step 2: Analyzed ${uniqueChunks.length} content sections and found ${imagePositions.length} suitable positions...`, 2);
            await new Promise(resolve => setTimeout(resolve, 2000));
        }

        // Step 3: Tạo prompt hình ảnh cho bài viết
        updateProcessStatus('Step 3: Generating intelligent image prompts with AI...', 3);
        const imagePrompts = await generateImagePrompts(title, content, imagePositions);

        // Delay để người dùng theo dõi step 3
        await new Promise(resolve => setTimeout(resolve, 2000));

        if (!imagePrompts || imagePrompts.length === 0) {
            Swal.close();
            showError('Unable to generate image prompts.');
            return;
        }

        // Hiển thị thông tin về prompt được tạo
        const aiGeneratedPrompts = imagePrompts.filter(p => p.prompt && p.prompt.length > 0).length;
        if (aiGeneratedPrompts > 0) {
            updateProcessStatus(`Step 3: Generated ${aiGeneratedPrompts} enhanced English prompts with AI...`, 3);
            await new Promise(resolve => setTimeout(resolve, 2000));

            // Hiển thị thông tin chi tiết về các prompt
            displayEnhancedPromptDetails(imagePrompts);
        }

        // Step 4: Tạo hình ảnh và chèn vào bài viết
        updateProcessStatus(`Step 4: Creating and inserting ${imagePrompts.length} images...`, 4);
        let successCount = 0;
        const imageErrors = [];

        for (let i = 0; i < imagePrompts.length; i++) {
            try {
                const prompt = imagePrompts[i];
                const chunkInfo = prompt.chunkIndex !== null ? ` (section ${prompt.chunkIndex + 1})` : '';
                const styleInfo = prompt.suggestedStyle ? ` - ${prompt.suggestedStyle} style` : '';
                const contentTypeInfo = prompt.contentType ? ` - ${prompt.contentType} content` : '';

                updateProcessStatus(`Creating image ${i + 1}/${imagePrompts.length}${chunkInfo}${styleInfo}${contentTypeInfo}...`, 4);
                const imageUrl = await generateImageFromAPI(prompt.prompt);

                if (imageUrl) {
                    let savedImageUrl = imageUrl;
                    try {
                        // Tải hình ảnh về và thêm vào media library
                        savedImageUrl = await uploadImageToMediaLibrary(imageUrl, prompt.prompt);
                    } catch (uploadError) {
                        console.warn(`Image ${i + 1} generated but upload failed. Inserting remote image URL.`, uploadError);
                        imageErrors.push(`Image ${i + 1}: upload failed, inserted remote URL (${uploadError.message || uploadError})`);
                    }

                    if (savedImageUrl) {
                        // Chèn hình ảnh vào editor
                        await insertImageIntoEditor(savedImageUrl, prompt.position);
                        successCount++;

                        console.log(`Successfully inserted image ${i + 1} at position ${prompt.position.index} with style: ${prompt.suggestedStyle}, content type: ${prompt.contentType}`);
                    }
                }

                // Delay giữa các lần tạo hình ảnh
                if (i < imagePrompts.length - 1) {
                    await new Promise(resolve => setTimeout(resolve, 3000));
                }

            } catch (error) {
                console.error(`Error generating image ${i + 1}:`, error);
                imageErrors.push(`Image ${i + 1}: ${error.message || error}`);
                // Tiếp tục với hình ảnh tiếp theo
            }
        }

        // Delay để người dùng theo dõi step 4
        await new Promise(resolve => setTimeout(resolve, 2000));

        updateProcessStatus('Completed! Enhanced images have been inserted into the article.', 5);

        // Delay để người dùng thấy step 5 hoàn thành
        await new Promise(resolve => setTimeout(resolve, 2000));

        // Đóng loading và hiển thị thành công
        setTimeout(() => {
            Swal.close();
            if (successCount > 0) {
                const chunkInfo = uniqueChunks.length > 1 ? ` from ${uniqueChunks.length} content sections` : '';
                const aiInfo = aiGeneratedPrompts > 0 ? ` with ${aiGeneratedPrompts} enhanced English prompts generated by AI` : '';
                const styleInfo = getUniqueStyles(imagePrompts);
                const contentTypeInfo = getUniqueContentTypes(imagePrompts);

                let successMessage = `Successfully inserted ${successCount}/${imagePrompts.length} enhanced images into the article${chunkInfo}${aiInfo}!`;

                if (styleInfo) {
                    successMessage += `\n\nStyles used: ${styleInfo}`;
                }

                if (contentTypeInfo) {
                    successMessage += `\nContent types: ${contentTypeInfo}`;
                }

                showSuccess(successMessage);
            } else {
                const details = imageErrors.length ? '\n\n' + imageErrors.slice(0, 3).join('\n') : '';
                showError('Unable to create any images. Please try again later.' + details);
            }
        }, 1000);

    } catch (error) {
        console.error('Error in image suggestion process:', error);
        Swal.close();
        showError('An error occurred: ' + error.message);
    }
}

// Function hiển thị thông tin chi tiết về các prompt được tạo
function displayEnhancedPromptDetails(imagePrompts) {
    console.log('Enhanced Image Prompt Details:');

    imagePrompts.forEach((prompt, index) => {
        console.log(`Prompt ${index + 1}:`, {
            style: prompt.suggestedStyle,
            contentType: prompt.contentType,
            visualElements: prompt.visualElements,
            aiScore: prompt.aiScore,
            aiReason: prompt.aiReason,
            enhanced: prompt.enhanced,
            fallback: prompt.fallback,
            promptPreview: prompt.prompt.substring(0, 100) + '...',
            paragraphPreview: prompt.originalParagraph.substring(0, 100) + '...'
        });
    });
}

// Function lấy danh sách các style duy nhất được sử dụng
function getUniqueStyles(imagePrompts) {
    const styles = [...new Set(imagePrompts.map(p => p.suggestedStyle).filter(s => s))];
    return styles.join(', ');
}

// Function lấy danh sách các content type duy nhất được sử dụng
function getUniqueContentTypes(imagePrompts) {
    const contentTypes = [...new Set(imagePrompts.map(p => p.contentType).filter(c => c))];
    return contentTypes.join(', ');
}

// Function lấy nội dung từ editor
function getEditorContent() {
    console.log('Getting editor content...');

    if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
        const editor = tinymce.activeEditor;
        const content = editor.getContent();
        console.log('TinyMCE editor found, content length:', content.length);
        console.log('Content preview:', content.substring(0, 200) + '...');
        return content;
    } else if (document.getElementById('content')) {
        const content = document.getElementById('content').value;
        console.log('Textarea content found, content length:', content.length);
        console.log('Content preview:', content.substring(0, 200) + '...');
        return content;
    } else if (document.getElementById('post_content')) {
        const content = document.getElementById('post_content').value;
        console.log('Post content textarea found, content length:', content.length);
        console.log('Content preview:', content.substring(0, 200) + '...');
        return content;
    } else if (document.querySelector('.wp-block-post-content')) {
        const content = document.querySelector('.wp-block-post-content').innerHTML;
        console.log('Block editor content found, content length:', content.length);
        console.log('Content preview:', content.substring(0, 200) + '...');
        return content;
    } else {
        console.warn('No editor content found');
        return null;
    }
}

// Function lấy tiêu đề bài viết
function getPostTitle() {
    const titleInput = document.getElementById('title');
    if (titleInput) {
        return titleInput.value;
    }
    return '';
}

function extractArticleParagraphs(content) {
    const rawContent = String(content || '');
    const paragraphs = [];

    if (rawContent.includes('<')) {
        try {
            const doc = new DOMParser().parseFromString(rawContent, 'text/html');
            let nodes = Array.from(doc.body.querySelectorAll('p')).filter(node => {
                const text = (node.textContent || '').replace(/\s+/g, ' ').trim();
                return text.length >= 40;
            });
            if (!nodes.length) {
                nodes = Array.from(doc.body.querySelectorAll('h2, h3, h4, li')).filter(node => {
                    const text = (node.textContent || '').replace(/\s+/g, ' ').trim();
                    return text.length >= 40;
                });
            }

            nodes.forEach((node, index) => {
                const text = (node.textContent || '').replace(/\s+/g, ' ').trim();
                paragraphs.push({
                    id: 'p' + index,
                    index,
                    text,
                    html: node.outerHTML || text
                });
            });
        } catch (error) {
            console.warn('DOMParser failed, falling back to text paragraph extraction.', error);
        }
    }

    if (!paragraphs.length) {
        rawContent
            .replace(/<[^>]*>/g, '\n')
            .split(/\n{2,}|\r\n{2,}/)
            .map(text => text.replace(/\s+/g, ' ').trim())
            .filter(text => text.length >= 40)
            .forEach((text, index) => {
                paragraphs.push({
                    id: 'p' + index,
                    index,
                    text,
                    html: text
                });
            });
    }

    return paragraphs;
}

function parseAIJsonObject(rawValue) {
    if (!rawValue) return null;

    if (typeof rawValue === 'object') {
        return rawValue;
    }

    let text = String(rawValue).trim();
    text = text.replace(/```json\s*/gi, '').replace(/```\s*/g, '').trim();
    text = text.replace(/<[^>]*>/g, '').trim();

    try {
        return JSON.parse(text);
    } catch (_) {
        const match = text.match(/\{[\s\S]*\}/);
        if (match) {
            try {
                return JSON.parse(match[0]);
            } catch (error) {
                console.warn('Failed to parse extracted JSON object.', error);
            }
        }
    }

    return null;
}

function normalizeAISuggestedImagePositions(aiData, articleParagraphs) {
    const positions = [];
    const paragraphMap = new Map(articleParagraphs.map(paragraph => [paragraph.id, paragraph]));
    const rawPositions = aiData && Array.isArray(aiData.positions) ? aiData.positions : [];

    rawPositions.forEach((item, fallbackIndex) => {
        const paragraphId = String(item.paragraph_id || item.id || ('p' + (Number.isFinite(Number(item.index)) ? Number(item.index) : fallbackIndex)));
        const paragraph = paragraphMap.get(paragraphId) || articleParagraphs[Number(item.index)] || articleParagraphs[fallbackIndex];
        if (!paragraph) return;

        const score = Number(item.score || 70);
        positions.push({
            paragraphId: paragraph.id,
            index: paragraph.index,
            paragraph: paragraph.text,
            position: 'after',
            score: Number.isFinite(score) ? score : 70,
            reason: item.reason || '',
            suggestedStyle: item.suggested_style || item.suggestedStyle || 'illustration',
            contentType: item.content_type || item.contentType || 'concept',
            visualElements: item.visual_elements || item.visualElements || '',
            imagePrompt: item.image_prompt || item.prompt || '',
            altText: item.alt_text || '',
            caption: item.caption || '',
            aiDetails: {
                aiScore: Number.isFinite(score) ? score : 70,
                aiReason: item.reason || '',
                aiStyle: item.suggested_style || item.suggestedStyle || 'illustration',
                contentType: item.content_type || item.contentType || 'concept',
                visualElements: item.visual_elements || item.visualElements || '',
                chunkIndex: null
            }
        });
    });

    const seen = new Set();
    return positions
        .filter(position => {
            if (seen.has(position.index)) return false;
            seen.add(position.index);
            return true;
        })
        .sort((a, b) => b.score - a.score)
        .slice(0, 3)
        .sort((a, b) => a.index - b.index);
}

// Function phân tích vị trí chèn hình ảnh bằng AI Provider
async function analyzeImagePositions(content) {
    try {
        console.log('Analyzing image positions for content length:', content.length);

        const articleParagraphs = extractArticleParagraphs(content);
        if (!articleParagraphs.length) {
            return analyzeImagePositionsFallback(content);
        }

        const compactParagraphs = articleParagraphs.slice(0, 40).map(paragraph => ({
            paragraph_id: paragraph.id,
            index: paragraph.index,
            text: paragraph.text.slice(0, 700)
        }));

        const aiPrompt = `You are an editorial image planner for WordPress articles.

Analyze the article paragraphs and choose the best 1-3 image insertion points. Prefer useful editorial images, clean infographics, charts, diagrams, or realistic web illustrations. Avoid decorative images and avoid text-heavy generated images.

Return ONLY valid JSON. No markdown, no explanations.

ARTICLE PARAGRAPHS:
${JSON.stringify(compactParagraphs, null, 2)}

Return this exact JSON shape:
{
  "positions": [
    {
      "paragraph_id": "p0",
      "score": 1-100,
      "reason": "why an image helps here",
      "suggested_style": "infographic|chart|comparison|product|illustration|editorial",
      "content_type": "process|data|comparison|product|concept|news",
      "visual_elements": "specific visual elements",
      "image_prompt": "English image prompt under 80 words, editorial style, no visible text, no watermark",
      "alt_text": "short SEO-friendly alt text",
      "caption": "optional short caption"
    }
  ]
}

Rules:
- Use paragraph_id exactly from ARTICLE PARAGRAPHS.
- Do not choose the first paragraph unless it is clearly the best image anchor.
- If article is short, return 1 image.
- If article is medium, return 2 images.
- If article is long, return up to 3 images.`;

        const response = await fetch(aiautotool_js_setting.ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aiautotool_analyze_image_positions',
                security: aiautotool_js_setting.security,
                content: JSON.stringify(compactParagraphs),
                prompt: aiPrompt
            })
        });

        const result = await response.json();
        if (!result.success || !result.data) {
            console.warn('AI image position analysis failed:', result);
            return analyzeImagePositionsFallback(content);
        }

        const parsed = parseAIJsonObject(result.data);
        const selectedPositions = normalizeAISuggestedImagePositions(parsed, articleParagraphs);

        if (!selectedPositions.length) {
            console.warn('AI returned no usable image positions, using fallback algorithm');
            return analyzeImagePositionsFallback(content);
        }

        return selectedPositions;

    } catch (error) {
        console.error('Error calling AI API:', error);
        // Fallback: sử dụng thuật toán cũ
        return analyzeImagePositionsFallback(content);
    }
}

// Function cắt nội dung thành các đoạn phù hợp cho AI xử lý
function splitContentForAI(content) {
    const maxChunkSize = 1500; // Kích thước tối đa cho mỗi đoạn
    const minChunkSize = 500;  // Kích thước tối thiểu cho mỗi đoạn
    const chunks = [];

    // Loại bỏ HTML tags để đếm ký tự thực
    const cleanContent = content.replace(/<[^>]*>/g, '');

    if (cleanContent.length <= maxChunkSize) {
        // Nội dung ngắn, không cần cắt
        chunks.push(content);
        return chunks;
    }

    // Tách nội dung theo đoạn văn
    const paragraphs = content.split('</p>').filter(p => p.trim().length > 0);
    let currentChunk = '';
    let currentChunkCleanLength = 0;

    for (let i = 0; i < paragraphs.length; i++) {
        const paragraph = paragraphs[i];
        const cleanParagraph = paragraph.replace(/<[^>]*>/g, '');

        // Kiểm tra xem có thể thêm đoạn này vào chunk hiện tại không
        if (currentChunkCleanLength + cleanParagraph.length <= maxChunkSize) {
            currentChunk += paragraph + '</p>';
            currentChunkCleanLength += cleanParagraph.length;
        } else {
            // Chunk hiện tại đã đủ lớn, lưu lại và bắt đầu chunk mới
            if (currentChunk.length > 0) {
                chunks.push(currentChunk);
            }

            // Bắt đầu chunk mới
            currentChunk = paragraph + '</p>';
            currentChunkCleanLength = cleanParagraph.length;
        }

        // Kiểm tra nếu chunk hiện tại đã đủ lớn và có ít nhất minChunkSize ký tự
        if (currentChunkCleanLength >= minChunkSize && currentChunkCleanLength >= maxChunkSize * 0.8) {
            chunks.push(currentChunk);
            currentChunk = '';
            currentChunkCleanLength = 0;
        }
    }

    // Thêm chunk cuối cùng nếu còn
    if (currentChunk.length > 0) {
        chunks.push(currentChunk);
    }

    // Đảm bảo không có chunk nào quá lớn
    const finalChunks = [];
    for (const chunk of chunks) {
        const cleanChunk = chunk.replace(/<[^>]*>/g, '');
        if (cleanChunk.length > maxChunkSize) {
            // Cắt chunk quá lớn thành các phần nhỏ hơn
            const subChunks = splitLargeChunk(chunk, maxChunkSize);
            finalChunks.push(...subChunks);
        } else {
            finalChunks.push(chunk);
        }
    }

    console.log(`Split content into ${finalChunks.length} chunks:`,
        finalChunks.map((chunk, index) => ({
            chunk: index + 1,
            length: chunk.replace(/<[^>]*>/g, '').length,
            paragraphs: chunk.split('</p>').filter(p => p.trim().length > 0).length
        }))
    );

    return finalChunks;
}

// Function cắt chunk quá lớn
function splitLargeChunk(chunk, maxSize) {
    const subChunks = [];
    const sentences = chunk.split(/[.!?]+/).filter(s => s.trim().length > 0);
    let currentSubChunk = '';
    let currentLength = 0;

    for (const sentence of sentences) {
        const cleanSentence = sentence.replace(/<[^>]*>/g, '');

        if (currentLength + cleanSentence.length <= maxSize) {
            currentSubChunk += sentence + '. ';
            currentLength += cleanSentence.length;
        } else {
            if (currentSubChunk.length > 0) {
                subChunks.push(currentSubChunk.trim());
            }
            currentSubChunk = sentence + '. ';
            currentLength = cleanSentence.length;
        }
    }

    if (currentSubChunk.length > 0) {
        subChunks.push(currentSubChunk.trim());
    }

    return subChunks;
}

// Function fallback sử dụng thuật toán cũ
function analyzeImagePositionsFallback(content) {
    const positions = [];

    // Cải thiện cách phân tích nội dung - xử lý cả HTML và text thuần
    let paragraphs = [];

    if (content.includes('<p>') || content.includes('</p>')) {
        // Nội dung HTML - tách theo thẻ p
        const htmlParagraphs = content.split('</p>').filter(p => p.trim().length > 0);
        paragraphs = htmlParagraphs.map(p => {
            // Loại bỏ thẻ mở <p> và các thẻ HTML khác
            return p.replace(/<p[^>]*>/, '').replace(/<[^>]*>/g, '').trim();
        }).filter(p => p.length > 0);
    } else {
        // Nội dung text thuần - tách theo dòng trống
        paragraphs = content.split('\n\n').filter(p => p.trim().length > 0);
    }

    console.log('Analyzing content with', paragraphs.length, 'paragraphs');
    console.log('Content preview:', content.substring(0, 200) + '...');

    // AI Scoring System - Intelligent scoring system
    const aiScoreParagraph = (paragraph, index, totalParagraphs) => {
        let score = 0;
        const cleanParagraph = paragraph.replace(/<[^>]*>/g, '').trim();
        const lowerParagraph = cleanParagraph.toLowerCase();

        // 1. Paragraph length (20% weight)
        const lengthScore = Math.min(cleanParagraph.length / 100, 1) * 20;
        score += lengthScore;

        // 2. Position in article (15% weight) - prioritize middle sections
        const positionRatio = index / totalParagraphs;
        let positionScore = 0;
        if (positionRatio >= 0.2 && positionRatio <= 0.8) {
            // Middle sections are prioritized
            positionScore = 15;
        } else if (positionRatio >= 0.1 && positionRatio <= 0.9) {
            // Near middle sections
            positionScore = 10;
        } else {
            // Beginning or end sections
            positionScore = 5;
        }
        score += positionScore;

        // 3. Image description keywords (25% weight)
        const imageKeywords = {
            'describe': 5, 'image': 5, 'chart': 8, 'graph': 8, 'diagram': 8,
            'process': 7, 'step': 6, 'method': 6, 'approach': 7,
            'compare': 8, 'difference': 7, 'contrast': 7, 'versus': 7,
            'data': 8, 'statistics': 8, 'information': 7, 'result': 6,
            'product': 7, 'service': 6, 'feature': 7, 'characteristic': 6,
            'example': 6, 'illustration': 7, 'demonstrate': 6, 'show': 6,
            'include': 5, 'contain': 5, 'have': 4, 'is': 3, 'especially': 6,
            'important': 7, 'main': 6, 'primary': 6, 'core': 7
        };

        let keywordScore = 0;
        for (const [keyword, weight] of Object.entries(imageKeywords)) {
            if (lowerParagraph.includes(keyword)) {
                keywordScore += weight;
            }
        }
        score += Math.min(keywordScore, 25);

        // 4. Content type (20% weight)
        let contentTypeScore = 0;

        // Process description content
        if (lowerParagraph.includes('process') || lowerParagraph.includes('step') ||
            lowerParagraph.includes('method') || lowerParagraph.includes('approach')) {
            contentTypeScore = 20;
        }
        // Comparison content
        else if (lowerParagraph.includes('compare') || lowerParagraph.includes('difference') ||
            lowerParagraph.includes('contrast') || lowerParagraph.includes('versus')) {
            contentTypeScore = 18;
        }
        // Data content
        else if (lowerParagraph.includes('data') || lowerParagraph.includes('statistics') ||
            lowerParagraph.includes('information') || lowerParagraph.includes('result') ||
            /\d+%|\d+ percent|\d+ billion|\d+ million/.test(lowerParagraph)) {
            contentTypeScore = 19;
        }
        // Product/service content
        else if (lowerParagraph.includes('product') || lowerParagraph.includes('service') ||
            lowerParagraph.includes('feature') || lowerParagraph.includes('characteristic')) {
            contentTypeScore = 16;
        }
        // General description content
        else if (lowerParagraph.includes('describe') || lowerParagraph.includes('example') ||
            lowerParagraph.includes('illustration') || lowerParagraph.includes('show')) {
            contentTypeScore = 15;
        }

        score += contentTypeScore;

        // 5. Sentence structure (10% weight)
        const sentences = cleanParagraph.split(/[.!?]+/).filter(s => s.trim().length > 0);
        const avgSentenceLength = sentences.reduce((sum, s) => sum + s.length, 0) / sentences.length;
        const structureScore = Math.min(avgSentenceLength / 50, 1) * 10;
        score += structureScore;

        // 6. Important keywords (10% weight)
        const importantWords = ['especially', 'important', 'main', 'primary', 'core',
            'key', 'crucial', 'essential', 'significant', 'critical'];
        const importantScore = importantWords.filter(word => lowerParagraph.includes(word)).length * 2;
        score += Math.min(importantScore, 10);

        return {
            score: Math.round(score),
            details: {
                lengthScore: Math.round(lengthScore),
                positionScore: Math.round(positionScore),
                keywordScore: Math.round(keywordScore),
                contentTypeScore: Math.round(contentTypeScore),
                structureScore: Math.round(structureScore),
                importantScore: Math.round(importantScore)
            }
        };
    };

    // Analyze each paragraph
    for (let i = 0; i < paragraphs.length; i++) {
        const paragraph = paragraphs[i].trim();

        // Skip paragraphs that are too short or too long
        if (paragraph.length < 30 || paragraph.length > 800) {
            continue;
        }

        // Calculate AI score for paragraph
        const aiResult = aiScoreParagraph(paragraph, i, paragraphs.length);

        // Only select paragraphs with high scores (>= 40 points)
        if (aiResult.score >= 40) {
            positions.push({
                index: i,
                paragraph: paragraph,
                position: 'after', // Insert after paragraph
                score: aiResult.score,
                aiDetails: aiResult.details
            });

            console.log(`Paragraph ${i} scored ${aiResult.score} points:`, paragraph.substring(0, 100) + '...');
        }
    }

    // Sort by score from high to low
    positions.sort((a, b) => b.score - a.score);

    // Limit number of images (maximum 3)
    const selectedPositions = positions.slice(0, 3);

    // Ensure positions are evenly distributed in the article
    if (selectedPositions.length > 1) {
        // Sort by index to ensure order in article
        selectedPositions.sort((a, b) => a.index - b.index);

        // Check distance between positions
        const minDistance = Math.floor(paragraphs.length / selectedPositions.length);
        const finalPositions = [];

        for (let i = 0; i < selectedPositions.length; i++) {
            const current = selectedPositions[i];

            // Check if this position is too close to the previous one
            if (i === 0 || (current.index - finalPositions[finalPositions.length - 1].index) >= minDistance) {
                finalPositions.push(current);
            }
        }

        console.log('Final selected positions:', finalPositions.map(p => ({
            index: p.index,
            score: p.score,
            preview: p.paragraph.substring(0, 50) + '...'
        })));

        return finalPositions;
    }

    // Log AI information for debugging (can be removed in production)
    if (selectedPositions.length > 0) {
        console.log('Fallback Image Position Analysis:', selectedPositions.map(p => ({
            index: p.index,
            score: p.score,
            preview: p.paragraph.substring(0, 100) + '...',
            details: p.aiDetails
        })));
    }

    return selectedPositions;
}

// Function tạo prompt hình ảnh thông minh
async function generateImagePrompts(title, content, positions) {
    console.log('Generating image prompts for', positions.length, 'positions');
    console.log('Title:', title);
    console.log('Content length:', content.length);

    const prompts = [];

    for (let i = 0; i < positions.length; i++) {
        const position = positions[i];

        console.log(`Processing position ${i + 1}/${positions.length}:`, {
            index: position.index,
            score: position.score,
            style: position.suggestedStyle,
            contentType: position.contentType,
            visualElements: position.visualElements,
            chunkIndex: position.aiDetails?.chunkIndex || 'N/A',
            paragraphPreview: position.paragraph.substring(0, 100) + '...'
        });

        try {
            // Prefer the prompt returned by the one-shot AI image planner.
            const englishPrompt = position.imagePrompt && position.imagePrompt.trim()
                ? position.imagePrompt.trim()
                : await generateEnglishImagePrompt(title, position);

            console.log(`Position ${i + 1} AI-generated English prompt:`, englishPrompt);

            prompts.push({
                prompt: englishPrompt,
                position: position,
                aiScore: position.score,
                aiReason: position.reason || '',
                suggestedStyle: position.suggestedStyle || 'illustration',
                contentType: position.contentType || 'concept',
                visualElements: position.visualElements || '',
                chunkIndex: position.aiDetails?.chunkIndex || null,
                originalParagraph: position.paragraph,
                altText: position.altText || '',
                caption: position.caption || '',
                enhanced: true
            });

        } catch (error) {
            console.error(`Error generating AI prompt for position ${i + 1}:`, error);

            // Fallback: sử dụng logic cải tiến nếu AI không hoạt động
            const fallbackPrompt = generateEnhancedFallbackPrompt(title, position);
            console.log(`Position ${i + 1} using enhanced fallback prompt:`, fallbackPrompt);

            prompts.push({
                prompt: fallbackPrompt,
                position: position,
                aiScore: position.score,
                aiReason: position.reason || '',
                suggestedStyle: position.suggestedStyle || 'illustration',
                contentType: position.contentType || 'concept',
                visualElements: position.visualElements || '',
                chunkIndex: position.aiDetails?.chunkIndex || null,
                originalParagraph: position.paragraph,
                altText: position.altText || '',
                caption: position.caption || '',
                enhanced: true,
                fallback: true
            });
        }
    }

    console.log('Generated', prompts.length, 'enhanced image prompts');
    return prompts;
}

// Function sử dụng AI để tạo prompt tiếng Anh
async function generateEnglishImagePrompt(title, position) {
    const cleanParagraph = position.paragraph.replace(/<[^>]*>/g, '').trim();

    // Tạo prompt cho AI bằng tiếng Anh với cải tiến từ hệ thống create image AI
    const aiPrompt = `You are an expert AI image prompt generator. Create a professional, detailed prompt for AI image generation based on the following content:

TITLE: ${title}
PARAGRAPH: ${cleanParagraph}
AI ANALYSIS:
- Score: ${position.score}/100
- Suggested Style: ${position.suggestedStyle || 'illustration'}
- Content Type: ${position.contentType || 'concept'}
- Visual Elements: ${position.visualElements || 'N/A'}
- Reason: ${position.reason || 'Content analysis'}

REQUIREMENTS:
1. Create a detailed English prompt for AI image generation
2. Focus on the main concept and visual elements from the paragraph
3. Include appropriate style keywords based on the suggested style
4. Make it professional, clear, and descriptive
5. Follow this professional structure: [Main Scene] | [Key Elements] | [Text Integration if needed] | [Lighting & Atmosphere] | [Technical Parameters]
6. Include quality keywords like "8k resolution", "hyperrealistic", "photorealistic quality", "cinematic composition"
7. Keep it concise but descriptive (max 150 words)
8. Use English only, no Vietnamese

STYLE GUIDELINES:
- infographic: "infographic, process diagram, step by step, workflow, modern design, professional visualization"
- chart: "data visualization, chart, graph, statistics, modern dashboard, professional analytics"
- comparison: "comparison chart, side by side, visual comparison, before after, split screen, professional layout"
- product: "product showcase, feature highlight, modern design, professional photography, clean layout, commercial quality"
- illustration: "illustration, concept art, modern style, clean design, professional, artistic composition"

CONTENT TYPE GUIDELINES:
- process: focus on workflow, steps, procedures, sequential actions
- data: emphasize statistics, numbers, charts, graphs, information visualization
- comparison: highlight contrasts, side-by-side elements, before/after scenarios
- product: showcase features, benefits, design, functionality
- concept: illustrate ideas, concepts, explanations, general content

TECHNICAL PARAMETERS TO INCLUDE:
- 8k resolution, hyperrealistic, photorealistic quality
- octane render, cinematic composition, sharp focus, high detail
- professional photography, modern design, clean aesthetic

Generate only the enhanced prompt, no explanations or additional text.`;

    try {
        // Gọi AI API để tạo prompt tiếng Anh
        const response = await fetch(aiautotool_js_setting.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'aiautotool_generate_english_prompt',
                security: aiautotool_js_setting.security,
                title: title,
                paragraph: cleanParagraph,
                ai_analysis: JSON.stringify({
                    score: position.score,
                    suggestedStyle: position.suggestedStyle,
                    contentType: position.contentType,
                    visualElements: position.visualElements,
                    reason: position.reason,
                    contentTypeScore: position.aiDetails?.contentTypeScore
                }),
                prompt: aiPrompt
            })
        });

        const result = await response.json();

        if (result.success && result.data) {
            // Làm sạch prompt từ AI
            let englishPrompt = result.data.trim();
            console.log('englishPrompt', englishPrompt);
            // Loại bỏ các từ khóa không cần thiết
            englishPrompt = englishPrompt.replace(/^(prompt|image|create|generate):\s*/i, '');
            return englishPrompt;
            // Đảm bảo prompt có độ dài phù hợp
            // if (englishPrompt.length > 200) {
            //     englishPrompt = englishPrompt.substring(0, 200) + '...';
            // }

            // // Áp dụng hệ thống tạo prompt chuyên nghiệp nếu AI response chưa đủ chất lượng
            // if (!englishPrompt.includes('8k resolution') || !englishPrompt.includes('hyperrealistic')) {
            //     // Sử dụng hệ thống enhancePromptToProfessional để cải thiện
            //     const enhancedPrompt = enhancePromptToProfessional(englishPrompt);
            //     return enhancedPrompt;
            // }

            // return englishPrompt;

        } else {
            throw new Error('AI response not successful');
        }

    } catch (error) {
        console.error('Error calling AI for English prompt:', error);
        // Fallback: sử dụng hệ thống tạo prompt chuyên nghiệp
        return generateEnhancedFallbackPrompt(title, position);
    }
}

// Function fallback cải tiến để tạo prompt khi AI không hoạt động
function generateEnhancedFallbackPrompt(title, position) {
    const cleanParagraph = position.paragraph.replace(/<[^>]*>/g, '').trim();

    // Lấy từ khóa chính từ đoạn văn
    const words = cleanParagraph
        .split(/\s+/)
        .filter(word => word.length > 2 && !['and', 'of', 'for', 'with', 'from', 'to', 'in', 'out', 'on', 'under', 'has', 'is', 'been', 'of', 'for', 'with', 'from', 'to', 'in', 'out', 'on', 'under', 'this', 'that', 'these', 'those', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'].includes(word.toLowerCase()))
        .slice(0, 6);

    const keywords = words.join(' ');

    // Tạo prompt cơ bản bằng tiếng Anh
    let basePrompt = '';
    if (keywords.length > 10) {
        basePrompt = `${title} - ${keywords}`;
    } else {
        basePrompt = title;
    }

    // Thêm style keywords dựa trên suggestedStyle
    const style = position.suggestedStyle || 'illustration';
    let styleKeywords = '';

    switch (style) {
        case 'infographic':
            styleKeywords = 'infographic, process diagram, step by step, workflow, modern design, professional visualization';
            break;
        case 'chart':
            styleKeywords = 'data visualization, chart, graph, statistics, modern dashboard, professional analytics';
            break;
        case 'comparison':
            styleKeywords = 'comparison chart, side by side, visual comparison, before after, split screen, professional layout';
            break;
        case 'product':
            styleKeywords = 'product showcase, feature highlight, modern design, professional photography, clean layout, commercial quality';
            break;
        case 'illustration':
        default:
            styleKeywords = 'illustration, concept art, modern style, clean design, professional, artistic composition';
            break;
    }

    // Thêm content type keywords dựa trên contentType
    const contentType = position.contentType || 'concept';
    let contentTypeKeywords = '';

    switch (contentType) {
        case 'process':
            contentTypeKeywords = 'workflow, sequential process, step by step, procedure, methodology';
            break;
        case 'data':
            contentTypeKeywords = 'statistics, numerical data, information visualization, analytics, metrics';
            break;
        case 'comparison':
            contentTypeKeywords = 'contrast, comparison, side by side, before after, difference';
            break;
        case 'product':
            contentTypeKeywords = 'product features, benefits, functionality, design, showcase';
            break;
        case 'concept':
        default:
            contentTypeKeywords = 'concept, idea, explanation, general content, illustration';
            break;
    }

    // Thêm visual elements nếu có
    let visualElementsKeywords = '';
    if (position.visualElements && position.visualElements.trim()) {
        visualElementsKeywords = position.visualElements.trim();
    }

    // Áp dụng hệ thống tạo prompt chuyên nghiệp
    const enhancedPrompt = enhancePromptToProfessional(basePrompt);

    // Tạo prompt cuối cùng với tất cả thông tin
    let finalPrompt = enhancedPrompt;

    if (visualElementsKeywords) {
        finalPrompt += ` | ${visualElementsKeywords}`;
    }

    if (contentTypeKeywords) {
        finalPrompt += ` | ${contentTypeKeywords}`;
    }

    finalPrompt += ` | ${styleKeywords}`;

    return finalPrompt;
}

// Function dịch từ khóa cơ bản sang tiếng Anh
function translateKeywordsToEnglish(keywords) {
    const translations = {
        'process': 'process',
        'step': 'step',
        'method': 'method',
        'approach': 'approach',
        'compare': 'comparison',
        'difference': 'difference',
        'contrast': 'compare',
        'data': 'data',
        'statistics': 'statistics',
        'information': 'data',
        'result': 'result',
        'product': 'product',
        'service': 'service',
        'feature': 'feature',
        'characteristic': 'characteristic',
        'description': 'description',
        'example': 'example',
        'illustration': 'illustration',
        'chart': 'chart',
        'graph': 'graph',
        'diagram': 'diagram',
        'important': 'important',
        'main': 'main',
        'primary': 'primary',
        'core': 'core',
        'success': 'success',
        'effective': 'effective',
        'optimize': 'optimize',
        'improve': 'improve',
        'develop': 'develop',
        'growth': 'growth',
        'research': 'research',
        'analysis': 'analysis',
        'evaluation': 'evaluation',
        'check': 'check',
        'confirm': 'confirm',
        'prove': 'prove',
        'show': 'show',
        'include': 'include',
        'contain': 'include',
        'have': 'have',
        'is': 'is',
        'been': 'be',
        'especially': 'special',
        'key': 'key',
        'decision': 'decision',
        'impact': 'impact',
        'effect': 'effect'
    };

    let translatedKeywords = keywords;

    // Thay thế các từ khóa đã biết
    for (const [english, translation] of Object.entries(translations)) {
        const regex = new RegExp(english, 'gi');
        translatedKeywords = translatedKeywords.replace(regex, translation);
    }

    return translatedKeywords;
}

function getAIImageProviders() {
    const aipostSettings = window.aipost || {};
    const globalSettings = window.aiautotool_js_setting || {};
    return aipostSettings.ai_image_providers || globalSettings.ai_image_providers || {};
}

function getDefaultAIImageSelection() {
    const providers = getAIImageProviders();
    const providerIds = Object.keys(providers || {});

    for (const providerId of providerIds) {
        const provider = providers[providerId] || {};
        const models = provider.models || {};
        const modelIds = Object.keys(models);
        if (!provider.configured || modelIds.length === 0) continue;

        return {
            provider: providerId,
            model: provider.default_model || modelIds[0],
            label: (provider.name || providerId) + ' - ' + (models[provider.default_model || modelIds[0]] || provider.default_model || modelIds[0])
        };
    }

    return { provider: '', model: '', label: 'No image provider configured' };
}

function populateAIImageModelSelect(selectEl, selectedValue = '') {
    if (!selectEl) return;

    const providers = getAIImageProviders();
    const options = [];

    Object.keys(providers || {}).forEach(providerId => {
        const provider = providers[providerId] || {};
        const models = provider.models || {};
        if (!provider.configured) return;

        Object.keys(models).forEach(modelId => {
            options.push({
                value: providerId + '::' + modelId,
                label: (provider.name || providerId) + ' - ' + (models[modelId] || modelId)
            });
        });
    });

    if (!options.length) {
        selectEl.innerHTML = '<option value="">No image provider configured</option>';
        selectEl.disabled = true;
        return;
    }

    selectEl.disabled = false;
    selectEl.innerHTML = options.map(option => {
        const selected = selectedValue && selectedValue === option.value ? ' selected' : '';
        return `<option value="${aiautotoolEscapeHtml(option.value)}"${selected}>${aiautotoolEscapeHtml(option.label)}</option>`;
    }).join('');
}

function parseAIImageModelValue(value, fallbackModel = '', explicitProvider = '') {
    const raw = String(value || '');
    if (raw.includes('::')) {
        const parts = raw.split('::');
        return { provider: parts[0] || '', model: parts.slice(1).join('::') || fallbackModel || '' };
    }

    const fallback = getDefaultAIImageSelection();
    return {
        provider: explicitProvider || fallback.provider,
        model: raw || fallbackModel || fallback.model
    };
}

// Function gọi AI Provider tạo hình ảnh
async function generateImageFromAPI(prompt, options = {}) {
    try {
        const {
            width = 1024,
            height = 1024,
            seed = 42,
            model = '',
            provider = '',
            negative_prompt = 'worst quality, blurry',
        } = options || {};

        const parsedSelection = (provider || model)
            ? parseAIImageModelValue(model, '', provider)
            : getDefaultAIImageSelection();

        const response = await fetch((window.aipost && aipost.ajax_url) || aiautotool_js_setting.ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aiautotool_generate_ai_image',
                security: (window.aipost && aipost.security) || '',
                prompt: prompt,
                provider: parsedSelection.provider || '',
                model: parsedSelection.model || '',
                width: String(width || 1024),
                height: String(height || 1024),
                seed: seed !== undefined && seed !== null ? String(seed) : '',
                negative_prompt: negative_prompt || '',
                post_id: String((window.aiautotool_js_setting && aiautotool_js_setting.postID) || (window.aipost && aipost.postID) || 0)
            })
        });

        const result = await response.json();
        if (!response.ok || !result || !result.success) {
            const message = result && result.data && result.data.message ? result.data.message : 'Không thể tạo hình ảnh từ AI Provider';
            throw new Error(message);
        }

        const imageUrl = result.data && result.data.url ? result.data.url : '';
        if (!imageUrl) {
            throw new Error('AI Provider không trả về URL hình ảnh');
        }

        return imageUrl;
    } catch (error) {
        console.error('Error generating image:', error);
        throw error;
    }
}

// Function tải hình ảnh về và thêm vào media library
async function uploadImageToMediaLibrary(imageUrl, prompt) {
    try {
        try {
            const url = new URL(imageUrl, window.location.href);
            if (url.origin === window.location.origin && url.pathname.indexOf('/wp-content/uploads/') !== -1) {
                return url.href;
            }
        } catch (_) { }

        const response = await fetch(aiautotool_js_setting.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'aiautotool_save_image',
                security: aiautotool_js_setting.security,
                link_img: imageUrl,
                postTitle: prompt.substring(0, 50) + '...',
                postId: '0',
                i: '0'
            })
        });

        const result = await response.json();

        if (result.stt === 'ok' && result.linkedit) {
            // Trả về URL của hình ảnh đã được lưu
            return result.linkedit;
        } else {
            throw new Error(result.linkedit || 'Không thể tải hình ảnh');
        }
    } catch (error) {
        console.error('Error uploading image:', error);
        throw error;
    }
}

// Function chèn hình ảnh vào editor tại vị trí được AI gợi ý
async function insertImageIntoEditor(imageUrl, position) {
    try {
        console.log('Inserting image at position:', position);
        const altText = aiautotoolEscapeHtml(position.altText || position.paragraph.substring(0, 80) || 'AI suggested image');
        const captionText = position.caption ? `<figcaption>${aiautotoolEscapeHtml(position.caption)}</figcaption>` : '';
        const imageHtml = captionText
            ? `<figure class="wp-caption aligncenter"><img src="${aiautotoolEscapeHtml(imageUrl)}" alt="${altText}" class="aligncenter size-medium" style="max-width: 100%; height: auto;" />${captionText}</figure>`
            : `<p><img src="${aiautotoolEscapeHtml(imageUrl)}" alt="${altText}" class="aligncenter size-medium" style="max-width: 100%; height: auto;" /></p>`;

        if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
            const editor = tinymce.activeEditor;
            const content = editor.getContent();

            // Phân tích nội dung editor để tìm vị trí chèn chính xác
            const paragraphs = content.split('</p>').filter(p => p.trim().length > 0);
            let insertPosition = -1;

            console.log('Total paragraphs in editor:', paragraphs.length);
            console.log('Target paragraph index:', position.index);
            console.log('Target paragraph content:', position.paragraph.substring(0, 100) + '...');

            // Phương pháp 1: Tìm theo index (ưu tiên)
            if (position.index >= 0 && position.index < paragraphs.length) {
                console.log('Using index-based insertion at paragraph:', position.index);

                // Tính vị trí chèn sau đoạn văn tại index
                let currentPos = 0;
                for (let i = 0; i <= position.index; i++) {
                    currentPos += paragraphs[i].length + 4; // +4 cho '</p>'
                }
                insertPosition = currentPos;

                console.log('Calculated insert position:', insertPosition);
            }

            // Phương pháp 2: Tìm theo nội dung nếu index không khớp
            if (insertPosition === -1) {
                console.log('Index method failed, trying content-based matching...');

                const targetContent = position.paragraph.replace(/<[^>]*>/g, '').trim();

                for (let i = 0; i < paragraphs.length; i++) {
                    const paragraph = paragraphs[i].trim();
                    const cleanParagraph = paragraph.replace(/<[^>]*>/g, '').trim();

                    // So sánh nội dung với độ chính xác cao hơn
                    const similarity = calculateTextSimilarity(cleanParagraph, targetContent);

                    console.log(`Paragraph ${i} similarity: ${similarity}%`);
                    console.log(`Paragraph ${i} content: ${cleanParagraph.substring(0, 100)}...`);

                    if (similarity > 70) { // Độ tương đồng > 70%
                        console.log(`Found matching paragraph at index ${i} with ${similarity}% similarity`);

                        // Tính vị trí chèn sau đoạn văn này
                        let currentPos = 0;
                        for (let j = 0; j <= i; j++) {
                            currentPos += paragraphs[j].length + 4;
                        }
                        insertPosition = currentPos;
                        break;
                    }
                }
            }

            // Phương pháp 3: Fallback - chèn vào vị trí tương đối
            if (insertPosition === -1) {
                console.log('Content matching failed, using relative positioning...');

                const totalParagraphs = paragraphs.length;
                const targetIndex = Math.min(position.index, totalParagraphs - 1);

                // Chèn vào giữa bài viết thay vì đầu
                const relativeIndex = Math.max(1, Math.floor(targetIndex / 2));

                let currentPos = 0;
                for (let i = 0; i <= relativeIndex; i++) {
                    currentPos += paragraphs[i].length + 4;
                }
                insertPosition = currentPos;

                console.log(`Using relative positioning at paragraph ${relativeIndex}/${totalParagraphs}`);
            }

            // Chèn hình ảnh vào vị trí đã tìm
            if (insertPosition >= 0) {
                const newContent = content.slice(0, insertPosition) + imageHtml + content.slice(insertPosition);
                editor.setContent(newContent);
                console.log(`Successfully inserted image at position ${insertPosition}`);
            } else {
                // Fallback cuối cùng: chèn vào cuối
                editor.insertContent(imageHtml);
                console.log('Fallback: inserted image at end of content');
            }

        } else if (document.getElementById('content')) {
            // Fallback cho textarea thông thường
            const textarea = document.getElementById('content');
            const content = textarea.value;

            // Phân tích nội dung textarea
            const paragraphs = content.split('\n\n').filter(p => p.trim().length > 0);
            let insertPosition = -1;

            console.log('Textarea - Total paragraphs:', paragraphs.length);
            console.log('Textarea - Target paragraph index:', position.index);

            // Phương pháp 1: Tìm theo index
            if (position.index >= 0 && position.index < paragraphs.length) {
                console.log('Textarea - Using index-based insertion at paragraph:', position.index);

                let currentPos = 0;
                for (let i = 0; i <= position.index; i++) {
                    currentPos += paragraphs[i].length + 2; // +2 cho '\n\n'
                }
                insertPosition = currentPos;
            }

            // Phương pháp 2: Tìm theo nội dung
            if (insertPosition === -1) {
                const targetContent = position.paragraph.replace(/<[^>]*>/g, '').trim();

                for (let i = 0; i < paragraphs.length; i++) {
                    const paragraph = paragraphs[i].trim();
                    const cleanParagraph = paragraph.replace(/<[^>]*>/g, '').trim();

                    const similarity = calculateTextSimilarity(cleanParagraph, targetContent);

                    if (similarity > 70) {
                        let currentPos = 0;
                        for (let j = 0; j <= i; j++) {
                            currentPos += paragraphs[j].length + 2;
                        }
                        insertPosition = currentPos;
                        break;
                    }
                }
            }

            // Phương pháp 3: Fallback
            if (insertPosition === -1) {
                const totalParagraphs = paragraphs.length;
                const relativeIndex = Math.max(1, Math.floor(Math.min(position.index, totalParagraphs - 1) / 2));

                let currentPos = 0;
                for (let i = 0; i <= relativeIndex; i++) {
                    currentPos += paragraphs[i].length + 2;
                }
                insertPosition = currentPos;
            }

            // Chèn hình ảnh
            if (insertPosition >= 0) {
                const newContent = content.slice(0, insertPosition) + '\n\n' + imageHtml + content.slice(insertPosition);
                textarea.value = newContent;
                console.log(`Textarea - Successfully inserted image at position ${insertPosition}`);
            } else {
                textarea.value += '\n\n' + imageHtml;
                console.log('Textarea - Fallback: inserted image at end');
            }
        }

        console.log(`Đã chèn hình ảnh vào vị trí sau đoạn văn index: ${position.index}`);

    } catch (error) {
        console.error('Error inserting image:', error);
        // Fallback: chèn vào cuối nếu có lỗi
        try {
            if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
                const imageHtml = `<p><img src="${imageUrl}" alt="${position.paragraph.substring(0, 50)}..." class="aligncenter size-medium" style="max-width: 100%; height: auto;" /></p>`;
                tinymce.activeEditor.insertContent(imageHtml);
            } else if (document.getElementById('content')) {
                const textarea = document.getElementById('content');
                const imageHtml = `<p><img src="${imageUrl}" alt="${position.paragraph.substring(0, 50)}..." class="aligncenter size-medium" style="max-width: 100%; height: auto;" /></p>`;
                textarea.value += '\n\n' + imageHtml;
            }
        } catch (fallbackError) {
            console.error('Fallback error:', fallbackError);
        }
    }
}

// Function tính độ tương đồng giữa hai đoạn văn
function calculateTextSimilarity(text1, text2) {
    if (!text1 || !text2) return 0;

    // Chuẩn hóa text
    const normalize = (text) => text.toLowerCase().replace(/[^\w\s]/g, '').trim();
    const normalized1 = normalize(text1);
    const normalized2 = normalize(text2);

    if (normalized1 === normalized2) return 100;

    // Tính độ tương đồng dựa trên từ khóa chung
    const words1 = normalized1.split(/\s+/).filter(w => w.length > 2);
    const words2 = normalized2.split(/\s+/).filter(w => w.length > 2);

    if (words1.length === 0 || words2.length === 0) return 0;

    const commonWords = words1.filter(word => words2.includes(word));
    const similarity = (commonWords.length / Math.max(words1.length, words2.length)) * 100;

    return Math.round(similarity);
}

// Function cập nhật trạng thái quá trình
function updateProcessStatus(message, step) {
    if (typeof Swal !== 'undefined') {
        // Tạo HTML cho các step với trạng thái phù hợp
        let stepHtml = '';
        for (let i = 1; i <= 5; i++) {
            let stepClass = '';
            if (i < step) {
                stepClass = 'completed';
            } else if (i === step) {
                stepClass = 'active';
            }
            stepHtml += `<div class="step ${stepClass}">${i}</div>`;
        }

        Swal.update({
            title: 'Processing...',
            html: `
                <div class="process-status">
                    <div class="step-indicator">
                        ${stepHtml}
                    </div>
                    <p>${message}</p>
                </div>
            `
        });
    } else {
        console.log(`Step ${step}: ${message}`);
    }
}

// Function hiển thị lỗi
function showError(message) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Error!',
            text: message,
            icon: 'error',
            confirmButtonText: 'Close'
        });
    } else {
        alert('Error: ' + message);
    }
}

// Function hiển thị thành công
function showSuccess(message) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Success!',
            text: message,
            icon: 'success',
            confirmButtonText: 'Close'
        });
    } else {
        alert('Success: ' + message);
    }
}

// Function debug để kiểm tra quá trình chèn hình ảnh
function debugImageInsertion() {
    console.log('=== DEBUG IMAGE INSERTION ===');

    // Kiểm tra editor
    if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
        const editor = tinymce.activeEditor;
        const content = editor.getContent();
        const paragraphs = content.split('</p>').filter(p => p.trim().length > 0);

        console.log('Editor type: TinyMCE');
        console.log('Total paragraphs:', paragraphs.length);
        console.log('Content length:', content.length);

        // Hiển thị các đoạn văn
        paragraphs.forEach((p, index) => {
            const cleanP = p.replace(/<[^>]*>/g, '').trim();
            if (cleanP.length > 0) {
                console.log(`Paragraph ${index}:`, cleanP.substring(0, 100) + '...');
            }
        });

    } else if (document.getElementById('content')) {
        const content = document.getElementById('content').value;
        const paragraphs = content.split('\n\n').filter(p => p.trim().length > 0);

        console.log('Editor type: Textarea');
        console.log('Total paragraphs:', paragraphs.length);
        console.log('Content length:', content.length);

        // Hiển thị các đoạn văn
        paragraphs.forEach((p, index) => {
            console.log(`Paragraph ${index}:`, p.substring(0, 100) + '...');
        });
    } else {
        console.log('No editor found');
    }

    console.log('=== END DEBUG ===');
}

// Thêm function debug vào global scope để có thể gọi từ console
window.debugImageInsertion = debugImageInsertion;






function insertArticleToEditor() {
    // Get content from global variable
    const contentToInsert = (typeof window !== 'undefined' && window.aiautotool_content)
        ? window.aiautotool_content
        : (typeof aiautotool_content !== 'undefined' ? aiautotool_content : '');

    if (!contentToInsert) {
        console.warn('No content to insert');
        if (typeof Swal !== 'undefined' && Swal) {
            Swal.fire({
                title: 'Error!',
                text: 'No content available to insert.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
        return;
    }

    // Chèn vào editor
    let inserted = false;

    // Try TinyMCE first
    if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
        tinymce.activeEditor.insertContent(contentToInsert);
        inserted = true;
    }
    // Try Gutenberg editor
    else if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch) {
        try {
            const currentContent = wp.data.select('core/editor').getEditedPostContent();
            wp.data.dispatch('core/editor').editPost({
                content: currentContent + contentToInsert
            });
            inserted = true;
        } catch (e) {
            console.error('Error inserting into Gutenberg:', e);
        }
    }
    // Fallback to textarea
    else {
        const textarea = document.getElementById('content');
        if (textarea) {
            const start = textarea.selectionStart || 0;
            const end = textarea.selectionEnd || 0;
            textarea.value = textarea.value.substring(0, start) + contentToInsert + textarea.value.substring(end);
            textarea.selectionStart = textarea.selectionEnd = start + contentToInsert.length;
            textarea.focus();
            inserted = true;
        }
    }

    if (inserted) {
        // Clear outbard and hide button
        const outbard = document.getElementById('outbard');
        if (outbard) {
            outbard.innerHTML = '';
        }

        const btnAddPost = document.querySelector('.btnaddpost');
        if (btnAddPost) {
            btnAddPost.style.display = 'none';
        }

        if (typeof Swal !== 'undefined' && Swal) {
            Swal.fire({
                title: 'Success!',
                text: 'Article has been inserted into the editor.',
                icon: 'success',
                confirmButtonText: 'OK',
                timer: 2000
            });
        }
    } else {
        if (typeof Swal !== 'undefined' && Swal) {
            Swal.fire({
                title: 'Error!',
                text: 'Could not insert content. Please copy manually.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
    }
}

// Add event listener for btnaddpost button if not already added
if (typeof jQuery !== 'undefined') {
    jQuery(document).off('click', '.btnaddpost').on('click', '.btnaddpost', function (e) {
        e.preventDefault();
        insertArticleToEditor();
        return false;
    });
} else {
    // Vanilla JS fallback
    document.addEventListener('click', function (e) {
        if (e.target && e.target.classList.contains('btnaddpost')) {
            e.preventDefault();
            insertArticleToEditor();
        }
    });
}

// Progress Tracking Functions




// Enhanced Button Grouping System
function createSmartButtonGroups() {
    if (!isEditOrNewPostPage()) return;

    const titleInput = get_title();
    if (!titleInput) return;

    // Create main button group container
    const buttonGroupContainer = document.createElement('div');
    buttonGroupContainer.className = 'aiautotool-button-groups';
    buttonGroupContainer.id = 'aiautotool-button-groups';

    // Define button categories
    const buttonCategories = {
        'writing': {
            name: 'Draft',
            icon: 'fa-solid fa-pen-nib',
            color: '#00875c',
            buttons: [
                {
                    id: 'write-with-agent',
                    icon: 'fa-solid fa-robot',
                    text: 'Full Article',
                    handler: null,
                    premium: true,
                    description: 'Draft a complete article from the current title'
                },
                {
                    id: 'write-with-google-search',
                    icon: 'fa-solid fa-magnifying-glass',
                    text: 'Research Draft',
                    handler: null,
                    premium: true,
                    description: 'Search first, then write'
                },
                {
                    id: 'your-prompt',
                    icon: 'fa-solid fa-comments',
                    text: 'Ask AI',
                    handler: null,
                    premium: false,
                    description: 'Ask the assistant'
                },
                {
                    id: 'custom-prompt-write',
                    icon: 'fa-solid fa-keyboard',
                    text: 'Custom Prompt',
                    handler: null,
                    premium: true,
                    description: 'Write with your own prompt'
                }
            ]
        },
        'content': {
            name: 'Blocks',
            icon: 'fa-solid fa-lightbulb',
            color: '#10b981',
            buttons: [
                {
                    id: 'outline-tool',
                    icon: 'fa-solid fa-list-ol',
                    text: 'Outline',
                    handler: null,
                    premium: true,
                    description: 'Create article outline with AI',
                    action: 'Outline'
                },
                {
                    id: 'introduction-tool',
                    icon: 'fa-solid fa-arrow-right-to-bracket',
                    text: 'Introduction',
                    handler: null,
                    premium: true,
                    description: 'Generate article introduction',
                    action: 'Introduction'
                },
                {
                    id: 'conclusion-tool',
                    icon: 'fa-solid fa-arrow-right-from-bracket',
                    text: 'Conclusion',
                    handler: null,
                    premium: true,
                    description: 'Create article conclusion',
                    action: 'Conclusion'
                },
                {
                    id: 'faq-tool',
                    icon: 'fa-solid fa-question-circle',
                    text: 'Create FAQ',
                    handler: null,
                    premium: true,
                    description: 'Generate FAQ section',
                    action: 'FAQ'
                }
            ]
        },
        'seo': {
            name: 'SEO',
            icon: 'fa-solid fa-chart-line',
            color: '#2563eb',
            buttons: [
                {
                    id: 'btn_suggettitle',
                    icon: 'fa-solid fa-heading',
                    text: 'SEO Titles',
                    handler: null,
                    premium: true,
                    description: 'Suggest optimized titles'
                },
                {
                    id: 'meta-description-tool',
                    icon: 'fa-solid fa-tags',
                    text: 'Meta Description',
                    handler: null,
                    premium: true,
                    description: 'Create SEO meta descriptions',
                    action: 'MetaDescription'
                },
                {
                    id: 'keyword-research-tool',
                    icon: 'fa-solid fa-magnifying-glass',
                    text: 'Keywords',
                    handler: null,
                    premium: true,
                    description: 'Research relevant keywords',
                    action: 'KeywordResearch'
                },
                {
                    id: 'blog-post-ideas-tool',
                    icon: 'fa-solid fa-lightbulb',
                    text: 'Ideas',
                    handler: null,
                    premium: true,
                    description: 'Generate blog post ideas',
                    action: 'BlogPostIdeas'
                }
            ]
        },
        'improve': {
            name: 'Improve',
            icon: 'fa-solid fa-wand-magic-sparkles',
            color: '#7c3aed',
            buttons: [
                {
                    id: 'content-rewrite-tool',
                    icon: 'fa-solid fa-rotate',
                    text: 'Rewrite',
                    handler: null,
                    premium: true,
                    description: 'Rewrite existing content',
                    action: 'ContentRewrite'
                },
                {
                    id: 'content-summary-tool',
                    icon: 'fa-solid fa-compress',
                    text: 'Summarize',
                    handler: null,
                    premium: true,
                    description: 'Summarize long content',
                    action: 'ContentSummary'
                },
                {
                    id: 'remote-rewrite-tool',
                    icon: 'fa-solid fa-globe',
                    text: 'Remote Rewrite',
                    handler: null,
                    premium: true,
                    description: 'Fetch a URL and rewrite content'
                }
            ]
        },
        'advanced': {
            name: 'More',
            icon: 'fa-solid fa-sliders',
            color: '#64748b',
            buttons: [
                {
                    id: 'social-media-tool',
                    icon: 'fa-solid fa-share-nodes',
                    text: 'Social Posts',
                    handler: null,
                    premium: true,
                    description: 'Generate social media content',
                    action: 'SocialMedia'
                },
                {
                    id: 'content-calendar-tool',
                    icon: 'fa-solid fa-calendar-days',
                    text: 'Calendar',
                    handler: null,
                    premium: true,
                    description: 'Plan content strategy',
                    action: 'ContentCalendar'
                }
            ]
        },
        'media': {
            name: 'Media',
            icon: 'fa-solid fa-image',
            color: '#f59e0b',
            buttons: [
                {
                    id: 'suggest-images',
                    icon: 'fa-solid fa-magic',
                    text: 'Suggest Images',
                    handler: startImageSuggestionProcess,
                    premium: true,
                    description: 'AI-powered image suggestions'
                },
                {
                    id: 'create-image-ai',
                    icon: 'fa-solid fa-wand-magic-sparkles',
                    text: 'Create Image AI',
                    handler: null,
                    premium: false,
                    description: 'Open AI image generator to create images from prompt'
                },
                {
                    id: 'find-img-button',
                    icon: 'fa-solid fa-search',
                    text: 'Find Images',
                    handler: null,
                    premium: false,
                    description: 'Search for relevant images'
                },
                {
                    id: 'youtube-button',
                    icon: 'fa-solid fa-video',
                    text: 'Find Videos',
                    handler: null,
                    premium: false,
                    description: 'Search for YouTube videos'
                },
                {
                    id: 'tts-post-button',
                    icon: 'fa-solid fa-volume-high',
                    text: 'TTS MP3',
                    handler: null,
                    premium: false,
                    description: 'Create MP3 narration for this post'
                }
            ]
        }
    };

    // Create category buttons
    Object.entries(buttonCategories).forEach(([categoryKey, category]) => {
        const categoryButton = createCategoryButton(category, categoryKey);
        buttonGroupContainer.appendChild(categoryButton);
    });

    // Add language selector
    const languageSelector = createLanguageSelector();
    buttonGroupContainer.appendChild(languageSelector);

    // Insert after title
    titleInput.parentNode.insertBefore(buttonGroupContainer, titleInput.nextSibling);

    // Add scroll detection for sticky behavior
    let scrollTimeout;
    let isSticky = false;

    const handleScroll = () => {
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(() => {
            const rect = buttonGroupContainer.getBoundingClientRect();
            const shouldBeSticky = rect.top <= 0;

            if (shouldBeSticky !== isSticky) {
                isSticky = shouldBeSticky;
                if (shouldBeSticky) {
                    buttonGroupContainer.classList.add('sticky');
                } else {
                    buttonGroupContainer.classList.remove('sticky');
                }
            }
        }, 10);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });

    // Initial check
    handleScroll();

    // Add styles
    addButtonGroupStyles();
}

function aiautotoolGetEditorPlainText() {
    if (typeof tinymce !== 'undefined' && tinymce.activeEditor && !tinymce.activeEditor.isHidden()) {
        return tinymce.activeEditor.getContent({ format: 'text' }).trim();
    }

    const contentField = document.getElementById('content');
    if (contentField) {
        const tmp = document.createElement('div');
        tmp.innerHTML = contentField.value || '';
        return (tmp.textContent || tmp.innerText || contentField.value || '').trim();
    }

    return '';
}

function aiautotoolRenderTtsResult(result, title) {
    const audioUrl = result.local_audio_url || result.audio_url || result.url || '';
    if (!audioUrl) {
        throw new Error('TTS server did not return an audio URL');
    }

    const safeUrl = aiautotoolEscapeHtml(audioUrl);
    const safeTitle = aiautotoolEscapeHtml(title || 'Article narration');
    const safeVoice = aiautotoolEscapeHtml(result.voice || '');
    const safeSource = result.local_audio_url ? 'Saved to this site' : 'Remote audio';
    const sizeText = result.bytes ? `${Math.round(Number(result.bytes) / 1024)} KB` : '';

    jQuery('#outbard').html(`
        <div class="aiautotool-tts-result" style="padding:16px;border:1px solid #d8e4dc;border-radius:8px;background:#fff;">
            <h3 style="margin:0 0 10px;color:#173b2f;font-size:16px;">
                <i class="fa-solid fa-volume-high"></i> MP3 narration ready
            </h3>
            <p style="margin:0 0 12px;color:#5d6f68;">${safeTitle}${safeVoice ? ' · ' + safeVoice : ''}${sizeText ? ' · ' + sizeText : ''} · ${safeSource}</p>
            <audio controls src="${safeUrl}" style="width:100%;display:block;margin-bottom:12px;"></audio>
            <a class="button button-primary" href="${safeUrl}" download>
                <i class="fa-solid fa-download"></i> Download MP3
            </a>
            <button type="button" class="button aiautotool-insert-tts-audio" data-audio-url="${safeUrl}" style="margin-left:8px;">
                <i class="fa-solid fa-plus"></i> Insert Player
            </button>
        </div>
    `);
}

function aiautotoolSaveTtsAudioToMediaLibrary(ttsResult, title) {
    const audioUrl = ttsResult.audio_url || ttsResult.url || '';
    if (!audioUrl || !window.aipost || !aipost.ajax_url || !aipost.security) {
        return Promise.resolve(ttsResult);
    }

    const postId = (window.aiautotool_js_setting && window.aiautotool_js_setting.postID) || 0;
    const formData = new FormData();
    formData.append('action', 'aiautotool_save_tts_audio');
    formData.append('security', aipost.security);
    formData.append('audio_url', audioUrl);
    formData.append('post_id', postId);
    formData.append('title', title || 'Article narration');

    return fetch(aipost.ajax_url, {
        method: 'POST',
        body: formData
    })
        .then(function (response) {
            return response.json();
        })
        .then(function (saved) {
            if (saved && saved.success && saved.data && saved.data.url) {
                return Object.assign({}, ttsResult, {
                    local_audio_url: saved.data.url,
                    attachment_id: saved.data.attachment_id
                });
            }
            const message = saved && saved.data && (saved.data.message || saved.data);
            throw new Error(message || 'Could not save MP3 to this WordPress site');
        });
}

function aiautotoolGeneratePostTts() {
    const titleInput = get_title();
    const title = titleInput ? titleInput.value.trim() : (document.title || 'Article');
    const contentText = aiautotoolGetEditorPlainText();
    const text = [title, contentText].filter(Boolean).join('\n\n').trim();
    const voiceConfig = (window.aipost && aipost.ai_voice) || (window.aiautotool_js_setting && aiautotool_js_setting.ai_voice) || {};

    if (!text) {
        if (typeof Swal !== 'undefined') {
            Swal.fire({ title: 'Error', text: 'Please enter a title or article content before creating MP3.', icon: 'error' });
        } else {
            alert('Please enter a title or article content before creating MP3.');
        }
        return;
    }

    open_box_aiautotool();
    openTab('aiContentTab');
    jQuery('#outbard').html('<div style="padding:20px;text-align:center;"><div id="loading-icon" class="loader" style="display:block"></div><p>Creating MP3 narration...</p></div>');

    const postId = (window.aiautotool_js_setting && window.aiautotool_js_setting.postID) || 0;
    const formData = new FormData();
    formData.append('action', 'aiautotool_generate_tts_audio');
    formData.append('security', (window.aipost && aipost.security) || '');
    formData.append('post_id', postId);
    formData.append('title', title || 'Article narration');
    formData.append('text', text);
    formData.append('provider', voiceConfig.provider || 'openai');
    formData.append('model', voiceConfig.model || '');
    formData.append('voice', voiceConfig.voice || '');

    fetch((window.aipost && aipost.ajax_url) || aiautotool_js_setting.ajax_url, {
        method: 'POST',
        body: formData
    })
        .then(function (response) {
            return response.json().then(function (data) {
                if (!response.ok || !data || data.success === false) {
                    const message = data && data.data && (data.data.message || data.data.error || data.data);
                    throw new Error(message || 'Failed to create MP3 narration');
                }
                return data.data || data;
            });
        })
        .then(function (data) {
            aiautotoolRenderTtsResult(data, title || 'Article narration');
        })
        .catch(function (error) {
            jQuery('#outbard').html('<div style="padding:16px;border:1px solid #fecaca;border-radius:8px;background:#fef2f2;color:#991b1b;">' + aiautotoolEscapeHtml(error.message || error) + '</div>');
        });
}

document.addEventListener('click', function (event) {
    const button = event.target.closest('.aiautotool-insert-tts-audio');
    if (!button) {
        return;
    }

    event.preventDefault();
    const audioUrl = button.getAttribute('data-audio-url');
    if (!audioUrl) {
        return;
    }

    const audioHtml = `<p><audio controls src="${aiautotoolEscapeHtml(audioUrl)}"></audio></p>`;
    if (typeof tinymce !== 'undefined' && tinymce.activeEditor && !tinymce.activeEditor.isHidden()) {
        tinymce.activeEditor.insertContent(audioHtml);
    } else {
        const contentField = document.getElementById('content');
        if (contentField) {
            contentField.value += '\n' + audioHtml;
        }
    }
});

function createCategoryButton(category, categoryKey) {
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'aiautotool-category-container';

    const mainButton = document.createElement('button');
    mainButton.type = 'button';
    mainButton.className = 'aiautotool-category-btn';
    mainButton.style.setProperty('--category-color', category.color);
    mainButton.innerHTML = `
        <i class="${category.icon}"></i>
        <span>${category.name}</span>
        <i class="fa-solid fa-chevron-down dropdown-arrow"></i>
    `;

    const dropdown = document.createElement('div');
    dropdown.className = 'aiautotool-category-dropdown';
    dropdown.style.display = 'none';

    // Add buttons to dropdown
    category.buttons.forEach(buttonConfig => {
        const button = createDropdownButton(buttonConfig, categoryKey);
        dropdown.appendChild(button);
    });

    // Toggle dropdown
    mainButton.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        const isOpen = dropdown.style.display === 'block';

        // Close all other dropdowns
        document.querySelectorAll('.aiautotool-category-dropdown').forEach(dd => {
            dd.style.display = 'none';
        });

        // Toggle current dropdown
        dropdown.style.display = isOpen ? 'none' : 'block';

        // Update arrow
        const arrow = mainButton.querySelector('.dropdown-arrow');
        arrow.style.transform = isOpen ? 'rotate(0deg)' : 'rotate(180deg)';
    });

    buttonContainer.appendChild(mainButton);
    buttonContainer.appendChild(dropdown);

    return buttonContainer;
}

function createDropdownButton(buttonConfig, categoryKey) {
    const button = document.createElement('button');
    button.type = 'button';
    button.className = 'aiautotool-dropdown-btn';
    button.id = buttonConfig.id;

    if (buttonConfig.premium) {
        button.classList.add('premium');
    }

    if (buttonConfig.description) {
        button.title = buttonConfig.description;
    }

    button.innerHTML = `
        <div class="button-content">
            <i class="${buttonConfig.icon}"></i>
            <span>${buttonConfig.text}</span>
            ${buttonConfig.premium ? '<span class="premium-badge">PRO</span>' : ''}
        </div>
    `;

    // Add click handler
    if (buttonConfig.handler) {
        button.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (buttonConfig.premium && !check_aipost_premium()) {
                showPremiumError();
                return;
            }
            buttonConfig.handler(e);
            closeAllDropdowns();
        });
    } else {
        // Handle special cases
        button.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            handleSpecialButton(buttonConfig, e);
            closeAllDropdowns();
        });
    }

    // Add submenu if needed
    if (buttonConfig.hasSubmenu && buttonConfig.submenuItems) {
        const submenu = createSubmenu(buttonConfig.submenuItems);
        button.appendChild(submenu);

        let submenuTimeout;

        const showSubmenu = () => {
            clearTimeout(submenuTimeout);
            submenu.style.display = 'block';
        };

        const hideSubmenu = () => {
            submenuTimeout = setTimeout(() => {
                submenu.style.display = 'none';
            }, 100);
        };

        button.addEventListener('mouseenter', showSubmenu);
        button.addEventListener('mouseleave', hideSubmenu);

        submenu.addEventListener('mouseenter', showSubmenu);
        submenu.addEventListener('mouseleave', hideSubmenu);
    }

    return button;
}

function createSubmenu(submenuItems) {
    const submenu = document.createElement('div');
    submenu.className = 'aiautotool-submenu';
    submenu.style.display = 'none';

    submenuItems.forEach(item => {
        const submenuItem = document.createElement('div');
        submenuItem.className = 'aiautotool-submenu-item';
        submenuItem.id = item.id;
        submenuItem.textContent = item.text;

        submenuItem.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeAllDropdowns();
            handleSubmenuAction(item.action);
        });

        // Add hover effect
        submenuItem.addEventListener('mouseenter', function () {
            this.style.backgroundColor = 'rgba(139, 92, 246, 0.1)';
        });

        submenuItem.addEventListener('mouseleave', function () {
            this.style.backgroundColor = '';
        });

        submenu.appendChild(submenuItem);
    });

    return submenu;
}

function createLanguageSelector() {
    const container = document.createElement('div');
    container.className = 'aiautotool-language-container';
    container.style.display = 'flex';
    container.style.alignItems = 'center';
    container.style.gap = '8px';

    const selectBox = document.createElement('select');
    selectBox.name = 'post_language';
    selectBox.id = 'post_language';
    selectBox.className = 'aiautotool-language-select';

    for (var code in aiautotool_js_setting.languageCodes) {
        if (aiautotool_js_setting.languageCodes.hasOwnProperty(code)) {
            var option = document.createElement('option');
            option.value = code;
            if (langcheck === code) {
                option.selected = true;
            }
            option.text = aiautotool_js_setting.languageCodes[code];
            selectBox.appendChild(option);
        }
    }

    // Create settings button
    const settingsButton = document.createElement('button');
    settingsButton.type = 'button';
    settingsButton.className = 'aiautotool-settings-button';
    settingsButton.innerHTML = '<i class="fa-solid fa-gear"></i>';
    settingsButton.title = 'Article Settings';
    settingsButton.style.cssText = 'background: none; border: 1px solid #d1d5db; border-radius: 6px; padding: 8px 10px; cursor: pointer; color: #6b7280; transition: all 0.2s;';
    settingsButton.addEventListener('mouseenter', function () {
        this.style.borderColor = '#3b82f6';
        this.style.color = '#3b82f6';
        this.style.backgroundColor = '#eff6ff';
    });
    settingsButton.addEventListener('mouseleave', function () {
        this.style.borderColor = '#d1d5db';
        this.style.color = '#6b7280';
        this.style.backgroundColor = 'transparent';
    });
    settingsButton.addEventListener('click', function () {
        openArticleSettingsModal();
    });

    container.appendChild(selectBox);
    container.appendChild(settingsButton);

    // Initialize modal if not exists
    if (!document.getElementById('aiautotool-article-settings-modal')) {
        createArticleSettingsModal();
    }

    return container;
}

// Article Settings Modal Functions
function getEditorProviderConfig() {
    const settings = window.aiautotool_js_setting || {};
    return {
        providers: settings.ai_providers || {},
        activeProvider: settings.active_ai_provider || '',
        activeModel: settings.active_ai_model || '',
        routingMode: settings.ai_provider_routing_mode || 'single'
    };
}

function escapeArticleSettingHtml(value) {
    return String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function buildArticleProviderOptions(selectedProvider) {
    const config = getEditorProviderConfig();
    let html = '<option value="">Default AI Provider settings</option>';

    Object.keys(config.providers).forEach(function (providerId) {
        const provider = config.providers[providerId] || {};
        const configuredText = provider.configured ? '' : ' (not configured)';
        html += '<option value="' + escapeArticleSettingHtml(providerId) + '" ' +
            (selectedProvider === providerId ? 'selected' : '') +
            (provider.configured ? '' : ' disabled') + '>' +
            escapeArticleSettingHtml(provider.name || providerId) +
            configuredText +
            '</option>';
    });

    return html;
}

function buildArticleModelOptions(providerId, selectedModel) {
    const config = getEditorProviderConfig();
    const provider = providerId && config.providers[providerId] ? config.providers[providerId] : null;
    let html = '<option value="">Default model</option>';

    if (!provider || !provider.models) {
        return html;
    }

    Object.keys(provider.models).forEach(function (modelId) {
        html += '<option value="' + escapeArticleSettingHtml(modelId) + '" ' +
            (selectedModel === modelId ? 'selected' : '') + '>' +
            escapeArticleSettingHtml(provider.models[modelId] || modelId) +
            '</option>';
    });

    return html;
}

function updateArticleModelSelect() {
    const providerSelect = document.getElementById('articleAiProvider');
    const modelSelect = document.getElementById('articleAiModel');
    if (!providerSelect || !modelSelect) return;

    const savedSettings = getArticleSettings();
    const providerId = providerSelect.value || '';
    const savedModel = savedSettings.aiModel || '';
    modelSelect.innerHTML = buildArticleModelOptions(providerId, savedModel);
    modelSelect.disabled = !providerId;
}

function createArticleSettingsModal() {
    // Check if modal already exists
    if (document.getElementById('aiautotool-article-settings-modal')) {
        return;
    }

    const modal = document.createElement('div');
    modal.id = 'aiautotool-article-settings-modal';
    modal.className = 'aiautotool-article-settings-modal';
    modal.style.display = 'none';

    modal.innerHTML = `
        <div class="aiautotool-modal-overlay"></div>
        <div class="aiautotool-modal-content">
            <div class="aiautotool-modal-header">
                <h2><i class="fa-solid fa-gear"></i> Article Settings</h2>
                <button class="aiautotool-modal-close" onclick="closeArticleSettingsModal()">
                    <i class="fa-solid fa-times"></i>
                </button>
            </div>
            <div class="aiautotool-modal-body">
                <form id="article-settings-form">
                    <div class="aiautotool-form-field">
                        <label for="articleAiProvider">AI Provider</label>
                        <select id="articleAiProvider" name="aiProvider">
                            ${buildArticleProviderOptions('')}
                        </select>
                        <small>Để trống để dùng cấu hình AI Provider chung hoặc chế độ xoay provider.</small>
                    </div>

                    <div class="aiautotool-form-field">
                        <label for="articleAiModel">AI Model</label>
                        <select id="articleAiModel" name="aiModel" disabled>
                            <option value="">Default model</option>
                        </select>
                        <small>Chỉ áp dụng khi chọn AI Provider riêng cho bài viết này.</small>
                    </div>

                    <div class="aiautotool-form-field">
                        <label for="targetAudience">
                            Target Audience
                        </label>
                        <input type="text" id="targetAudience" name="targetAudience" 
                               placeholder="e.g., Marketing professionals, Small business owners, Tech enthusiasts">
                        <small>Đối tượng người đọc mục tiêu của bài viết</small>
                    </div>
                    
                    <div class="aiautotool-form-field">
                        <label for="tone">Tone (Giọng văn)</label>
                        <select id="tone" name="tone">
                            <option value="">-- Select Tone --</option>
                            <option value="professional">Professional (Chuyên nghiệp)</option>
                            <option value="friendly">Friendly (Thân thiện)</option>
                            <option value="humorous">Humorous (Hài hước)</option>
                            <option value="formal">Formal (Trang trọng)</option>
                            <option value="casual">Casual (Thân mật)</option>
                            <option value="authoritative">Authoritative (Có thẩm quyền)</option>
                            <option value="conversational">Conversational (Trò chuyện)</option>
                        </select>
                        <small>Giọng văn của bài viết</small>
                    </div>
                    
                    <div class="aiautotool-form-field">
                        <label for="lengthType">Length Type</label>
                        <select id="lengthType" name="lengthType">
                            <option value="">-- Select Length --</option>
                            <option value="short-form">Short-form (Ngắn gọn)</option>
                            <option value="long-form">Long-form (Dài, chi tiết)</option>
                            <option value="comparison">Comparison (So sánh)</option>
                        </select>
                        <small>Độ dài và loại bài viết</small>
                    </div>
                    
                    <div class="aiautotool-form-field">
                        <label for="competitors">Competitors URLs</label>
                        <textarea id="competitors" name="competitors" rows="3" 
                                  placeholder="Enter competitor URLs (one per line)&#10;e.g.,&#10;https://example.com/article1&#10;https://example.com/article2"></textarea>
                        <small>URL các bài viết của đối thủ để phân tích (mỗi URL một dòng)</small>
                    </div>
                    
                    <div class="aiautotool-form-field">
                        <label for="brandVoiceRules">Brand Voice Rules</label>
                        <textarea id="brandVoiceRules" name="brandVoiceRules" rows="4" 
                                  placeholder="Enter brand voice rules and guidelines&#10;e.g.,&#10;- Always use active voice&#10;- Avoid technical jargon&#10;- Include real-world examples&#10;- Focus on benefits, not features"></textarea>
                        <small>Quy tắc thương hiệu và hướng dẫn viết bài</small>
                    </div>
                    
                    <div class="aiautotool-form-field">
                        <div class="aiautotool-checkbox-field">
                            <input type="checkbox" id="autoInternalLinks" name="autoInternalLinks" checked>
                            <label for="autoInternalLinks" class="checkbox-label">
                                <strong>Auto Find Internal Links</strong>
                                <span class="checkbox-description">Tự động tìm và chèn internal links vào bài viết khi viết</span>
                            </label>
                        </div>
                        <small>Hệ thống sẽ tự động tìm các bài viết liên quan và chèn internal links một cách tự nhiên vào bài viết</small>
                    </div>
                </form>
            </div>
            <div class="aiautotool-modal-footer">
                <button type="button" class="aiautotool-btn-secondary" onclick="closeArticleSettingsModal()">
                    Cancel
                </button>
                <button type="button" class="aiautotool-btn-primary" onclick="saveArticleSettings()">
                    <i class="fa-solid fa-save"></i> Save Settings
                </button>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    const providerSelect = document.getElementById('articleAiProvider');
    if (providerSelect) {
        providerSelect.addEventListener('change', function () {
            const modelSelect = document.getElementById('articleAiModel');
            if (modelSelect) {
                modelSelect.innerHTML = buildArticleModelOptions(providerSelect.value, '');
                modelSelect.disabled = !providerSelect.value;
            }
        });
    }

    // Load saved settings
    loadArticleSettings();
}

function openArticleSettingsModal() {
    const modal = document.getElementById('aiautotool-article-settings-modal');
    if (modal) {
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
        loadArticleSettings();
    }
}

function closeArticleSettingsModal() {
    const modal = document.getElementById('aiautotool-article-settings-modal');
    if (modal) {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    }
}

function saveArticleSettings() {
    const form = document.getElementById('article-settings-form');
    if (!form) return;

    const formData = new FormData(form);
    const settings = {
        aiProvider: formData.get('aiProvider') || '',
        aiModel: formData.get('aiModel') || '',
        targetAudience: formData.get('targetAudience') || '',
        tone: formData.get('tone') || '',
        lengthType: formData.get('lengthType') || '',
        competitors: formData.get('competitors') ? formData.get('competitors').split('\n').filter(url => url.trim()) : [],
        brandVoiceRules: formData.get('brandVoiceRules') || '',
        autoInternalLinks: formData.get('autoInternalLinks') === 'on' || formData.get('autoInternalLinks') === true
    };

    // Save to localStorage
    localStorage.setItem('aiautotool_article_settings', JSON.stringify(settings));

    // Show success message
    const successMsg = document.createElement('div');
    successMsg.className = 'aiautotool-settings-saved';
    successMsg.textContent = 'Settings saved successfully!';
    successMsg.style.cssText = 'position: fixed; top: 20px; right: 20px; background: #10b981; color: white; padding: 12px 20px; border-radius: 6px; z-index: 10000; box-shadow: 0 4px 6px rgba(0,0,0,0.1);';
    document.body.appendChild(successMsg);

    setTimeout(() => {
        successMsg.remove();
    }, 3000);

    closeArticleSettingsModal();
}

function loadArticleSettings() {
    const saved = localStorage.getItem('aiautotool_article_settings');
    if (!saved) return;

    try {
        const settings = JSON.parse(saved);

        if (document.getElementById('articleAiProvider')) {
            document.getElementById('articleAiProvider').innerHTML = buildArticleProviderOptions(settings.aiProvider || '');
            document.getElementById('articleAiProvider').value = settings.aiProvider || '';
        }
        if (document.getElementById('articleAiModel')) {
            document.getElementById('articleAiModel').innerHTML = buildArticleModelOptions(settings.aiProvider || '', settings.aiModel || '');
            document.getElementById('articleAiModel').value = settings.aiModel || '';
            document.getElementById('articleAiModel').disabled = !settings.aiProvider;
        }
        if (document.getElementById('targetAudience')) {
            document.getElementById('targetAudience').value = settings.targetAudience || '';
        }
        if (document.getElementById('tone')) {
            document.getElementById('tone').value = settings.tone || '';
        }
        if (document.getElementById('lengthType')) {
            document.getElementById('lengthType').value = settings.lengthType || '';
        }
        if (document.getElementById('competitors')) {
            document.getElementById('competitors').value = Array.isArray(settings.competitors)
                ? settings.competitors.join('\n')
                : (settings.competitors || '');
        }
        if (document.getElementById('brandVoiceRules')) {
            document.getElementById('brandVoiceRules').value = settings.brandVoiceRules || '';
        }
        if (document.getElementById('autoInternalLinks')) {
            // Default to true if not set
            document.getElementById('autoInternalLinks').checked = settings.hasOwnProperty('autoInternalLinks')
                ? settings.autoInternalLinks
                : true;
        }
    } catch (e) {
        console.error('Error loading article settings:', e);
    }
}

function getArticleSettings() {
    const saved = localStorage.getItem('aiautotool_article_settings');

    // Default settings if not saved
    const defaultSettings = {
        aiProvider: '',
        aiModel: '',
        autoInternalLinks: true
    };

    if (!saved) return defaultSettings;

    try {
        const settings = JSON.parse(saved);
        // Ensure competitors is array
        if (typeof settings.competitors === 'string') {
            settings.competitors = settings.competitors.split('\n').filter(url => url.trim());
        }
        // Ensure autoInternalLinks defaults to true if not set
        if (!settings.hasOwnProperty('autoInternalLinks')) {
            settings.autoInternalLinks = true;
        }
        return settings;
    } catch (e) {
        console.error('Error parsing article settings:', e);
        return defaultSettings;
    }
}

function handleSpecialButton(buttonConfig, event) {
    switch (buttonConfig.id) {
        case 'write-with-agent':
            // Get title from post
            var titleValue = get_title().value;
            if (!titleValue || titleValue.trim() === '') {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Please enter a post title first.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                } else {
                    showError('Please enter a post title first.');
                }
                return;
            }

            // Open AI box and switch to aiContentTab
            open_box_aiautotool();
            openTab('aiContentTab');

            // Get language
            var post_language = jQuery('#post_language').val();
            var lang = 'vi';
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                lang = languageCodes[post_language];
            } else if (post_language) {
                lang = post_language === 'Vietnamese' ? 'vi' : 'en';
            }

            // Hide info_content div when streaming starts
            const infoContentDiv = document.getElementById('info_content');
            if (infoContentDiv) {
                infoContentDiv.style.display = 'none';
            }

            // Call AI Auto Writer with SSE streaming - output to aiContentTab
            if (typeof window.writeArticleWithAutoWriter === 'function') {
                window.writeArticleWithAutoWriter(titleValue, 'outbard', lang)
                    .then((content) => {
                        console.log('AI Auto Writer completed successfully');
                        if (typeof hideLoading === 'function') {
                            hideLoading();
                        }
                    })
                    .catch(error => {
                        console.error('AI Auto Writer error:', error);
                        if (typeof hideLoading === 'function') {
                            hideLoading();
                        }
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                title: 'Error!',
                                text: 'AI Auto Writer error: ' + error.message,
                                icon: 'error',
                                confirmButtonText: 'Close'
                            });
                        } else {
                            showError('AI Auto Writer error: ' + error.message);
                        }
                    });
            } else {
                console.error('writeArticleWithAutoWriter function not found');
                if (typeof hideLoading === 'function') {
                    hideLoading();
                }
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Error!',
                        text: 'AI Auto Writer not available. Please refresh the page.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                } else {
                    showError('AI Auto Writer not available. Please refresh the page.');
                }
            }
            break;

        case 'bard-write':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            var titleValue = get_title().value;
            if (!titleValue.trim()) {
                showError('Please fill in the title.');
                return;
            }
            open_box_aiautotool();
            openTab('aiContentTab');
            var divId = "outbard";
            var post_language = jQuery('#post_language').val();
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                window.langcheck = languageCodes[post_language];
            }

            // Use new function with analysis and SSE streaming
            var sendFnWithAnalysis = (typeof window.sendbardToServerWithAnalysis !== 'undefined')
                ? window.sendbardToServerWithAnalysis
                : null;

            // Ensure langcheck is set
            if (typeof window.langcheck === 'undefined' || !window.langcheck) {
                window.langcheck = post_language || 'Vietnamese';
            }

            console.log('Attempting to use sendbardToServerWithAnalysis:', typeof sendFnWithAnalysis);
            console.log('Title:', titleValue);
            console.log('Language:', window.langcheck);

            if (sendFnWithAnalysis) {
                // Get original prompt template if available
                var prompt_article = '';
                if (typeof aiautotool_js_setting !== 'undefined' &&
                    aiautotool_js_setting.prompt &&
                    aiautotool_js_setting.prompt.aiautotool_prompt_artcile) {
                    prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
                    if (typeof aiautotool_fix_question === 'function') {
                        prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
                    }
                }

                console.log('Calling sendbardToServerWithAnalysis with:', {
                    title: titleValue,
                    divId: divId,
                    lang: window.langcheck,
                    model: '',
                    prompt: prompt_article
                });

                sendFnWithAnalysis(titleValue, divId, window.langcheck, '', prompt_article)
                    .then((content) => {
                        console.log('Article generated successfully, length:', content ? content.length : 0);
                    })
                    .catch((error) => {
                        // Error message is already shown by sendbardToServerWithAnalysis
                        console.error('Error generating content with analysis:', error);
                    });
            } else {
                console.warn('sendbardToServerWithAnalysis not available, using fallback');
                // Fallback to old method if new function not available
                var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
                prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
                var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
                if (sendFn) {
                    sendFn(prompt_article, divId, 'writefull', window.langcheck, '')
                        .catch((error) => {
                            // Error message is already shown by sendbardToServer (Swal/alert)
                            console.error('Error generating content with Gemini:', error);
                        });
                }
            }
            break;

        case 'chatgpt-write':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            var titleValue = get_title().value;
            if (!titleValue.trim()) {
                showError('Please fill in the title.');
                return;
            }
            open_box_aiautotool();
            openTab('aiContentTab');
            var divId = "outbard";
            var post_language = jQuery('#post_language').val();
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                window.langcheck = languageCodes[post_language];
            }
            var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
            prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
            var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
            if (sendFn) {
                sendFn(prompt_article, divId, 'writefull', window.langcheck, '')
                    .catch((error) => {
                        // Error message is already shown by sendbardToServer (Swal/alert)
                        console.error('Error generating content with ChatGPT:', error);
                    });
            }
            break;

        case 'gpt4o-write':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            var titleValue = get_title().value;
            if (!titleValue.trim()) {
                showError('Please fill in the title.');
                return;
            }
            open_box_aiautotool();
            openTab('aiContentTab');
            var divId = "outbard";
            var post_language = jQuery('#post_language').val();
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                window.langcheck = languageCodes[post_language];
            }
            var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
            prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
            var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
            if (sendFn) {
                sendFn(prompt_article, divId, 'writefull', window.langcheck, 'gpt-5-mini')
                    .catch((error) => {
                        console.error('Error generating content with GPT-4o:', error);
                    });
            }
            break;

        case 'claude-opus-write':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            var titleValue = get_title().value;
            if (!titleValue.trim()) {
                showError('Please fill in the title.');
                return;
            }
            open_box_aiautotool();
            openTab('aiContentTab');
            var divId = "outbard";
            var post_language = jQuery('#post_language').val();
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                window.langcheck = languageCodes[post_language];
            }
            var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
            prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
            var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
            if (sendFn) {
                sendFn(prompt_article, divId, 'writefull', window.langcheck, 'claude-3-7-sonnet')
                    .catch((error) => {
                        console.error('Error generating content with Claude 3 Opus:', error);
                    });
            }
            break;

        case 'gemini-2.5-flash-write':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            var titleValue = get_title().value;
            if (!titleValue.trim()) {
                showError('Please fill in the title.');
                return;
            }
            open_box_aiautotool();
            openTab('aiContentTab');
            var divId = "outbard";
            var post_language = jQuery('#post_language').val();
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                window.langcheck = languageCodes[post_language];
            }

            // Ensure langcheck is set
            if (typeof window.langcheck === 'undefined' || !window.langcheck) {
                window.langcheck = post_language || 'Vietnamese';
            }

            // Use new function with analysis and SSE streaming
            var sendFnWithAnalysis = (typeof window.sendbardToServerWithAnalysis !== 'undefined')
                ? window.sendbardToServerWithAnalysis
                : null;

            console.log('=== Gemini 2.5 Flash Write Button Clicked ===');
            console.log('Title:', titleValue);
            console.log('Language:', window.langcheck);
            console.log('sendbardToServerWithAnalysis available:', typeof sendFnWithAnalysis === 'function');

            if (sendFnWithAnalysis) {
                // Get original prompt template if available
                var prompt_article = '';
                if (typeof aiautotool_js_setting !== 'undefined' &&
                    aiautotool_js_setting.prompt &&
                    aiautotool_js_setting.prompt.aiautotool_prompt_artcile) {
                    prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
                    if (typeof aiautotool_fix_question === 'function') {
                        prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
                    }
                }

                console.log('Calling sendbardToServerWithAnalysis with:', {
                    title: titleValue,
                    divId: divId,
                    lang: window.langcheck,
                    model: '',
                    prompt: prompt_article
                });

                sendFnWithAnalysis(titleValue, divId, window.langcheck, '', prompt_article)
                    .then((content) => {
                        console.log('Article generated successfully with Gemini 2.5 Flash, length:', content ? content.length : 0);
                    })
                    .catch((error) => {
                        // Error message is already shown by sendbardToServerWithAnalysis
                        console.error('Error generating content with Gemini 2.5 Flash:', error);
                    });
            } else {
                console.warn('sendbardToServerWithAnalysis not available, using fallback');
                // Fallback to old method if new function not available
                var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
                prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
                var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
                if (sendFn) {
                    sendFn(prompt_article, divId, 'writefull', window.langcheck, '')
                        .catch((error) => {
                            // Error message is already shown by sendbardToServer (Swal/alert)
                            console.error('Error generating content with Gemini 2.5 Flash:', error);
                        });
                }
            }
            break;

        case 'write-with-google-search':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            var titleValue = get_title().value;
            if (!titleValue.trim()) {
                showError('Please fill in the title.');
                return;
            }
            open_box_aiautotool();
            openTab('aiContentTab');
            var divId = "outbard";
            var post_language = jQuery('#post_language').val();
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                window.langcheck = languageCodes[post_language];
            }

            // Ensure langcheck is set
            if (typeof window.langcheck === 'undefined' || !window.langcheck) {
                window.langcheck = post_language || 'Vietnamese';
            }

            console.log('=== Write with Google Search Button Clicked ===');
            console.log('Title:', titleValue);
            console.log('Language:', window.langcheck);

            // Use new function with Google search and SSE streaming
            var sendFnWithGoogleSearch = (typeof window.sendbardToServerWithGoogleSearch !== 'undefined')
                ? window.sendbardToServerWithGoogleSearch
                : null;

            // Get original prompt template if available
            var prompt_article = '';
            if (typeof aiautotool_js_setting !== 'undefined' &&
                aiautotool_js_setting.prompt &&
                aiautotool_js_setting.prompt.aiautotool_prompt_artcile) {
                prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
                if (typeof aiautotool_fix_question === 'function') {
                    prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
                }
            }

            if (sendFnWithGoogleSearch) {
                console.log('Calling sendbardToServerWithGoogleSearch with:', {
                    title: titleValue,
                    divId: divId,
                    lang: window.langcheck,
                    model: '',
                    prompt: prompt_article
                });

                sendFnWithGoogleSearch(titleValue, divId, window.langcheck, '', prompt_article)
                    .then((content) => {
                        console.log('Article generated successfully with Google search, length:', content ? content.length : 0);
                    })
                    .catch((error) => {
                        console.error('Error generating content with Google search:', error);
                    });
            } else {
                // Fallback: create function on the fly or use standard function
                console.warn('sendbardToServerWithGoogleSearch not available, using fallback');

                // Create function similar to sendbardToServerWithAnalysis but with different action
                if (typeof window.sendbardToServerWithAnalysis !== 'undefined') {
                    // Temporarily override action in sendbardToServerWithAnalysis
                    var originalFunction = window.sendbardToServerWithAnalysis;
                    window.sendbardToServerWithGoogleSearch = function (title, divId, lang, model, originalPrompt) {
                        return new Promise((resolve, reject) => {
                            if (!title || !title.trim()) {
                                const errorMsg = 'Please provide a title for the article.';
                                if (typeof showError === 'function') {
                                    showError(errorMsg);
                                }
                                reject(new Error(errorMsg));
                                return;
                            }

                            // Hide info_content div when streaming starts
                            const infoContentDiv = document.getElementById('info_content');
                            if (infoContentDiv) {
                                infoContentDiv.style.display = 'none';
                            }

                            if (typeof showLoading === 'function') {
                                showLoading('Starting article generation with Google search...');
                            }

                            if (divId) {
                                const targetDiv = document.getElementById(divId);
                                if (targetDiv) {
                                    targetDiv.innerHTML = '<div id="article-analysis-container" style="padding: 0px; font-family: Arial, sans-serif; border-bottom: 2px solid #e0e0e0; margin-bottom: 20px;"></div>' +
                                        '<div id="article-content-container" style="padding: 20px; font-family: Arial, sans-serif;"></div>';
                                }
                            }

                            const messageId = 'article_google_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
                            const articleSettings = getArticleSettings();
                            const aiRoute = aiautotoolResolveAiRoute(model);

                            const dataToSend = {
                                title: title,
                                lang: lang,
                                provider_id: aiRoute.provider_id,
                                model: aiRoute.model,
                                message_id: messageId,
                                original_prompt: originalPrompt,
                                domain: (window.aiautotool_js_setting && window.aiautotool_js_setting.fsdata && window.aiautotool_js_setting.fsdata.domain) || '',
                                info: (window.aiautotool_js_setting && window.aiautotool_js_setting.fsdata) || {},
                                targetAudience: articleSettings ? articleSettings.targetAudience : '',
                                tone: articleSettings ? articleSettings.tone : '',
                                lengthType: articleSettings ? articleSettings.lengthType : '',
                                competitors: articleSettings ? articleSettings.competitors : [],
                                brandVoiceRules: articleSettings ? articleSettings.brandVoiceRules : '',
                                autoInternalLinks: articleSettings ? (articleSettings.autoInternalLinks !== false) : true
                            };

                            const formData = new FormData();
                            formData.append('action', 'aiautotool_write_article_with_google_search');
                            formData.append('data', JSON.stringify(dataToSend));
                            formData.append('security', (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) ? aiautotool_js_setting.security : '');

                            let currentStepElement = null;
                            let currentStepNumber = 0;
                            let articleContent = '';
                            let stepOutputs = {};

                            fetch(aiautotool_js_setting.ajax_url, {
                                method: 'POST',
                                body: formData
                            }).then(response => {
                                if (!response.ok) {
                                    return response.text().then(text => {
                                        throw new Error('Network response was not ok: ' + response.status + ' - ' + text.substring(0, 200));
                                    });
                                }

                                const contentType = response.headers.get('content-type');
                                if (!contentType || !contentType.includes('text/event-stream')) {
                                    return response.text().then(text => {
                                        try {
                                            const jsonData = JSON.parse(text);
                                            if (jsonData.success === false) {
                                                throw new Error(jsonData.data || 'Unknown error');
                                            }
                                        } catch (e) {
                                            throw new Error('Unexpected response format: ' + text.substring(0, 200));
                                        }
                                    });
                                }

                                const reader = response.body.getReader();
                                const decoder = new TextDecoder();
                                let buffer = '';
                                let currentEvent = null;

                                function readChunk() {
                                    return reader.read().then(({ done, value }) => {
                                        if (done) {
                                            if (typeof hideLoading === 'function') {
                                                hideLoading();
                                            }

                                            // Finalize article display
                                            const finalContent = articleContent;

                                            // Store in global variable for btnaddpost button
                                            if (typeof window !== 'undefined' && finalContent) {
                                                window.aiautotool_content = finalContent;
                                            }

                                            if (divId && finalContent) {
                                                // Update only the content container, keep analysis container intact
                                                const contentContainer = document.getElementById('article-content-container');
                                                if (contentContainer) {
                                                    contentContainer.innerHTML = finalContent;

                                                    // Show Add Post button
                                                    const btnAddPost = document.querySelector('.btnaddpost');
                                                    if (btnAddPost) {
                                                        btnAddPost.style.display = 'block';
                                                        btnAddPost.style.marginTop = '15px';
                                                        btnAddPost.style.marginBottom = '15px';
                                                    }

                                                    if (typeof scrollToBottom === 'function') {
                                                        scrollToBottom();
                                                    }
                                                }
                                            }

                                            // Resolve even if content is empty (let the UI handle it)
                                            resolve(finalContent || '');
                                            return;
                                        }

                                        buffer += decoder.decode(value, { stream: true });
                                        const lines = buffer.split('\n');

                                        // Keep the last incomplete line in buffer
                                        buffer = lines.pop() || '';

                                        lines.forEach(line => {
                                            line = line.trim();

                                            if (!line) {
                                                // Empty line signals end of event
                                                currentEvent = null;
                                                return;
                                            }

                                            if (line.startsWith('event:')) {
                                                currentEvent = line.substring(6).trim();
                                                console.log('SSE Event:', currentEvent);
                                            } else if (line.startsWith('data:')) {
                                                try {
                                                    const jsonData = line.substring(5).trim();
                                                    if (!jsonData) {
                                                        return; // Skip empty data
                                                    }

                                                    const data = JSON.parse(jsonData);
                                                    console.log('SSE Data received:', currentEvent, data);

                                                    // Use handleArticleSSEEvent if available, otherwise handle manually
                                                    if (typeof handleArticleSSEEvent === 'function') {
                                                        handleArticleSSEEvent(data, currentEvent, divId, {
                                                            currentStepElement: () => currentStepElement,
                                                            setCurrentStepElement: (el) => { currentStepElement = el; },
                                                            currentStepNumber: () => currentStepNumber,
                                                            setCurrentStepNumber: (num) => { currentStepNumber = num; },
                                                            articleContent: () => articleContent,
                                                            appendArticleContent: (text) => { articleContent += text; },
                                                            setArticleContent: (content) => { articleContent = content; },
                                                            stepOutputs: () => stepOutputs,
                                                            setStepOutput: (step, output) => { stepOutputs[step] = output; }
                                                        });

                                                        // Update articleContent from complete event
                                                        if (currentEvent === 'complete' && data.content) {
                                                            articleContent = data.content;
                                                            console.log('Article content received, length:', articleContent.length);
                                                        }
                                                    } else {
                                                        // Fallback manual handling
                                                        const eventType = currentEvent || data.type || 'unknown';

                                                        // Helper function to escape HTML
                                                        const escapeHtml = (text) => {
                                                            const div = document.createElement('div');
                                                            div.textContent = text;
                                                            return div.innerHTML;
                                                        };

                                                        if (eventType === 'step_start' || data.type === 'step_start') {
                                                            currentStepNumber = data.step || 0;
                                                            const stepName = data.step_name || 'unknown';

                                                            const analysisContainer = document.getElementById('article-analysis-container');
                                                            if (analysisContainer) {
                                                                const stepDiv = document.createElement('div');
                                                                stepDiv.className = 'analysis-step';
                                                                stepDiv.id = 'step-' + currentStepNumber;
                                                                stepDiv.innerHTML = '<div class="step-header"><span class="step-number">' + currentStepNumber + '</span> <span class="step-name">' + stepName + '</span> <span class="step-status">Processing...</span></div><div class="step-content"></div>';
                                                                analysisContainer.appendChild(stepDiv);
                                                                currentStepElement = stepDiv;
                                                            }
                                                        } else if (eventType === 'step_output' || data.type === 'step_output') {
                                                            const stepNum = data.step || currentStepNumber;
                                                            const output = data.output || '';

                                                            if (currentStepElement && currentStepElement.id === 'step-' + stepNum) {
                                                                const contentDiv = currentStepElement.querySelector('.step-content');
                                                                if (contentDiv) {
                                                                    contentDiv.innerHTML = output;
                                                                }
                                                            }
                                                            stepOutputs[stepNum] = output;
                                                        } else if (eventType === 'step_complete' || data.type === 'step_complete') {
                                                            const stepNum = data.step || currentStepNumber;
                                                            if (currentStepElement && currentStepElement.id === 'step-' + stepNum) {
                                                                const statusSpan = currentStepElement.querySelector('.step-status');
                                                                if (statusSpan) {
                                                                    statusSpan.textContent = 'Completed';
                                                                    statusSpan.className = 'step-status completed';
                                                                }
                                                            }
                                                        } else if (eventType === 'complete' || data.type === 'complete') {
                                                            articleContent = data.content || '';
                                                            const contentContainer = document.getElementById('article-content-container');
                                                            if (contentContainer) {
                                                                contentContainer.innerHTML = articleContent;
                                                            }
                                                            if (typeof hideLoading === 'function') {
                                                                hideLoading();
                                                            }
                                                            resolve(articleContent);
                                                        } else if (eventType === 'error' || data.type === 'error') {
                                                            const errorMsg = data.message || 'Unknown error';

                                                            // Display error in container
                                                            const analysisContainer = document.getElementById('article-analysis-container');
                                                            if (analysisContainer) {
                                                                const errorDiv = document.createElement('div');
                                                                errorDiv.className = 'sse-error-message';
                                                                errorDiv.style.cssText = 'padding: 20px; background: #f8d7da; border-left: 5px solid #dc3545; border-radius: 5px; margin: 15px 0; color: #721c24;';
                                                                errorDiv.innerHTML = '<div style="display: flex; align-items: center; margin-bottom: 10px;">' +
                                                                    '<span style="font-size: 24px; margin-right: 10px;">❌</span>' +
                                                                    '<strong style="font-size: 16px;">Error</strong>' +
                                                                    '</div>' +
                                                                    '<div style="line-height: 1.6; font-size: 14px; white-space: pre-wrap; word-wrap: break-word;">' +
                                                                    escapeHtml(errorMsg) +
                                                                    '</div>';
                                                                analysisContainer.appendChild(errorDiv);

                                                                setTimeout(() => {
                                                                    errorDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                                                                }, 100);
                                                            }

                                                            // Show modal/alert
                                                            if (typeof Swal !== 'undefined' && Swal && typeof Swal.fire === 'function') {
                                                                try {
                                                                    Swal.fire({
                                                                        title: 'Error!',
                                                                        html: '<div style="text-align: left; padding: 10px 0;">' +
                                                                            '<p style="margin-bottom: 10px; color: #333; font-size: 15px; white-space: pre-wrap;">' +
                                                                            escapeHtml(errorMsg) +
                                                                            '</p>' +
                                                                            '</div>',
                                                                        icon: 'error',
                                                                        confirmButtonText: 'Close',
                                                                        confirmButtonColor: '#dc3545'
                                                                    });
                                                                } catch (e) {
                                                                    alert('Error: ' + errorMsg);
                                                                }
                                                            } else if (typeof showError === 'function') {
                                                                showError(errorMsg);
                                                            } else {
                                                                alert('Error: ' + errorMsg);
                                                            }

                                                            if (typeof hideLoading === 'function') {
                                                                hideLoading();
                                                            }
                                                            reject(new Error(errorMsg));
                                                        }
                                                    }
                                                } catch (e) {
                                                    console.error('Failed to parse SSE data:', e);
                                                    console.error('Line that failed:', line);
                                                    console.error('Current event:', currentEvent);
                                                }
                                            }
                                        });

                                        return readChunk();
                                    });
                                }

                                return readChunk();
                            }).catch(error => {
                                console.error('Fetch error:', error);
                                if (typeof hideLoading === 'function') {
                                    hideLoading();
                                }
                                if (typeof showError === 'function') {
                                    showError('Error: ' + error.message);
                                }
                                reject(error);
                            });
                        });
                    };

                    // Now call it - use the function we just created on window
                    window.sendbardToServerWithGoogleSearch(titleValue, divId, window.langcheck, 'gemini-2.5-flash-lite', prompt_article)
                        .then((content) => {
                            console.log('Article generated successfully with Google search, length:', content ? content.length : 0);
                        })
                        .catch((error) => {
                            console.error('Error generating content with Google search:', error);
                        });
                } else {
                    showError('Google search writing function not available. Please refresh the page and try again.');
                }
            }
            break;

        case 'mistral-large-write':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            var titleValue = get_title().value;
            if (!titleValue.trim()) {
                showError('Please fill in the title.');
                return;
            }
            open_box_aiautotool();
            openTab('aiContentTab');
            var divId = "outbard";
            var post_language = jQuery('#post_language').val();
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                window.langcheck = languageCodes[post_language];
            }
            var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
            prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
            var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
            if (sendFn) {
                sendFn(prompt_article, divId, 'writefull', window.langcheck, '')
                    .catch((error) => {
                        console.error('Error generating content with Mistral Large:', error);
                    });
            }
            break;

        case 'llama3-write':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            var titleValue = get_title().value;
            if (!titleValue.trim()) {
                showError('Please fill in the title.');
                return;
            }
            open_box_aiautotool();
            openTab('aiContentTab');
            var divId = "outbard";
            var post_language = jQuery('#post_language').val();
            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
                window.langcheck = languageCodes[post_language];
            }
            var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
            prompt_article = aiautotool_fix_question(prompt_article, titleValue, window.langcheck);
            var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
            if (sendFn) {
                sendFn(prompt_article, divId, 'writefull', window.langcheck, '')
                    .catch((error) => {
                        console.error('Error generating content with Llama 3:', error);
                    });
            }
            break;

        case 'your-prompt':
            // Open Ask Assistant functionality
            open_box_aiautotool();
            openTab('aiContentTab');
            break;

        case 'custom-prompt-write':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            // Show custom prompt modal
            showCustomPromptModal();
            break;

        case 'btn_suggettitle':
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }
            // Create input modal for title suggestion
            showTitleSuggestionModal();
            break;

        case 'open-modal':
            // Open modal
            const modalContainer = document.querySelector(".aiautotool-modal-container");
            if (modalContainer) {
                modalContainer.style.display = "block";
            }
            break;

        case 'create-image-ai':
            // Open image generation popup modal
            showImageGenerationModal();
            break;

        case 'find-img-button':
            // Trigger find image functionality
            if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
                const selectedText = tinymce.activeEditor.selection.getContent({ format: 'text' });
                if (selectedText.trim()) {
                    open_box_aiautotool();
                    openTab('imagesTab');
                    jQuery('#img_list_find').html('<div id="loading-icon" class="loader" style="display:block;width:100% !important;:100% !important"></div>');
                    openTab('imagesTab');

                    jQuery.ajax({
	                        url: aiautotoolGetMediaSearchUrl('searchimg'),
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({ question: selectedText }),
                        success: function (rrr) {
                            if (rrr.result) {
                                jQuery('#img_list_find').html('');
                                rrr.result.forEach(function (url) {
                                    jQuery('#img_list_find').prepend('<div data-src="' + url + '" class="img_search"><img src="' + url + '"></div>');
                                });
                            }
                        }
                    });
                }
            }
            break;

        case 'youtube-button':
            // Trigger find video functionality
            if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
                const selectedText = tinymce.activeEditor.selection.getContent({ format: 'text' });
                if (selectedText.trim()) {
                    open_box_aiautotool();
                    openTab('videoTab');
                    jQuery('.infodiv').hide();
                    showLoading();
                    openTab('videoTab');

                    jQuery.ajax({
	                        url: aiautotoolGetMediaSearchUrl('youtubesearch'),
                        type: 'GET',
                        contentType: 'application/json',
                        data: { q: selectedText },
                        success: function (r) {
                            if (r.result) {
                                hideLoading();
                                jQuery('#video_list_find').html('');
                                r.result.forEach(function (video) {
                                    jQuery('#video_list_find').prepend('<div data-id="' + video.id + '" class="Youtube_thumb "><img src="' + video.thumbnails[0].url + '" /></div>');
                                });
                            }
                        }
                    });
                }
            }
            break;

        case 'tts-post-button':
            aiautotoolGeneratePostTts();
            break;

        case 'outline-tool':
        case 'introduction-tool':
        case 'conclusion-tool':
        case 'faq-tool':
        case 'meta-description-tool':
        case 'social-media-tool':
        case 'content-summary-tool':
        case 'keyword-research-tool':
        case 'content-rewrite-tool':
        case 'blog-post-ideas-tool':
        case 'content-calendar-tool':
            // Handle AI Post Tools
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }

            // Create input modal for topic/keyword
            showAIPostToolModal(buttonConfig.action, buttonConfig.text);
            break;

        case 'content-rewrite-tool':
            // Handle Content Rewrite Tool with special modal
            if (!check_aipost_premium()) {
                showPremiumError();
                return;
            }

            // Create special modal for content rewrite
            showContentRewriteModal();
            break;
        case 'remote-rewrite-tool':
            if (!check_aipost_premium()) { showPremiumError(); return; }
            if (typeof showRemoteRewriteModal === 'function') { showRemoteRewriteModal(); } else { alert('Remote Rewrite module not loaded.'); }
            break;
    }
}

function handleSubmenuAction(action) {
    // Check if TinyMCE editor exists
    if (typeof tinymce === 'undefined' || !tinymce.activeEditor) {
        if (typeof showError === 'function') {
            showError('Editor not found. Please make sure you are on the post edit page.');
        } else if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Error!',
                text: 'Editor not found. Please make sure you are on the post edit page.',
                icon: 'error',
                confirmButtonText: 'Close'
            });
        } else {
            alert('Editor not found. Please make sure you are on the post edit page.');
        }
        return;
    }

    const editor = tinymce.activeEditor;

    // Check if selection exists
    if (!editor.selection) {
        if (typeof showError === 'function') {
            showError('Please select text in the content.');
        } else if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Error!',
                text: 'Please select text in the content.',
                icon: 'error',
                confirmButtonText: 'Close'
            });
        } else {
            alert('Please select text in the content.');
        }
        return;
    }

    const selectedText = editor.selection.getContent({ format: 'text' });

    if (!selectedText.trim()) {
        if (typeof showError === 'function') {
            showError('Please select text in the content.');
        } else if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Error!',
                text: 'Please select text in the content.',
                icon: 'error',
                confirmButtonText: 'Close'
            });
        } else {
            alert('Please select text in the content.');
        }
        return;
    }

    open_box_aiautotool();
    openTab('aiContentTab');

    const post_language = get_lang();
    const resolvedLang = (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language))
        ? languageCodes[post_language]
        : (typeof langcheck !== 'undefined' ? langcheck : post_language);
    const divId = "outbard";

    let instruction = '';
    switch (action) {
        case 'shorter':
            instruction = 'Make text shorten.';
            break;
        case 'longer':
            instruction = 'Make text longer tone of voice.';
            break;
        case 'professional':
            instruction = 'Make text use professional tone of voice.';
            break;
        case 'remote_rewrite':
            if (typeof showRemoteRewriteModal === 'function') {
                showRemoteRewriteModal();
            } else {
                alert('Remote Rewrite module not loaded.');
            }
            return;
        default:
            console.error('Unknown submenu action:', action);
            return;
    }

    var sendRewriteFn = (typeof window.sendbardToServerrewrite !== 'undefined') ? window.sendbardToServerrewrite : sendbardToServerrewrite;
    if (sendRewriteFn) {
        sendRewriteFn(selectedText, divId, 'bardrewrite', resolvedLang, instruction)
            .catch((error) => {
                // Error message is already shown by sendbardToServerrewrite (Swal/alert)
                console.error('Error rewriting content:', error);
            });
    } else {
        console.error('sendbardToServerrewrite function not found');
        if (typeof showError === 'function') {
            showError('Rewrite function not found. Please refresh the page.');
        } else {
            alert('Rewrite function not found. Please refresh the page.');
        }
    }
}

function closeAllDropdowns() {
    document.querySelectorAll('.aiautotool-category-dropdown').forEach(dropdown => {
        dropdown.style.display = 'none';
    });

    document.querySelectorAll('.dropdown-arrow').forEach(arrow => {
        arrow.style.transform = 'rotate(0deg)';
    });
}

function showPremiumError() {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Error!',
            text: 'AI Post Limit Quota. Please Upgrade Pro.',
            icon: 'error',
            confirmButtonText: 'Close'
        });
    } else {
        alert('AI Post Limit Quota. Please Upgrade Pro.');
    }
}

function showError(message) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Error!',
            text: message,
            icon: 'error',
            confirmButtonText: 'Close'
        });
    } else {
        alert(message);
    }
}

function addButtonGroupStyles() {
    const style = document.createElement('style');
    style.textContent = `
        .aiautotool-button-groups {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            margin: 10px 0;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 2000;
            background: #ffffff;
            padding: 8px;
            border-radius: 8px;
            border: 1px solid #d8e4dc;
            box-shadow: 0 2px 8px rgba(15, 23, 42, 0.08);
            transition: all 0.3s ease;
        }
        
        /* WordPress admin bar support */
        .admin-bar .aiautotool-button-groups {
            top: 32px;
        }
        
        @media (max-width: 782px) {
            .admin-bar .aiautotool-button-groups {
                top: 46px;
            }
        }
        
        /* Add sticky behavior when scrolling */
        .aiautotool-button-groups.sticky {
            background: rgba(248, 250, 252, 0.95);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border-bottom: 1px solid #e5e7eb;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            animation: stickySlideIn 0.3s ease-out;
        }
        
        @keyframes stickySlideIn {
            from {
                transform: translateY(-100%);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        /* Mobile responsive sticky behavior */
        @media (max-width: 768px) {
            .aiautotool-button-groups {
                top: 0;
                z-index: 1001;
            }
            
            .aiautotool-button-groups.sticky {
                background: rgba(248, 250, 252, 0.98);
                backdrop-filter: blur(15px);
                -webkit-backdrop-filter: blur(15px);
            }
        }
        
        .aiautotool-category-container {
            position: relative;
        }
        
        .aiautotool-category-btn {
            display: flex;
            align-items: center;
            gap: 7px;
            padding: 7px 12px;
            border: 1px solid #d8e4dc;
            border-radius: 8px;
            background: white;
            color: #173b2f;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.18s ease;
            font-size: 13px;
        }
        
        .aiautotool-category-btn:hover {
            border-color: var(--category-color);
            color: var(--category-color);
            background: #f7faf8;
        }
        
        .dropdown-arrow {
            transition: transform 0.3s ease;
        }
        
        .aiautotool-category-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            min-width: 190px;
            background: white;
            border: 1px solid #d8e4dc;
            border-radius: 8px;
            box-shadow: 0 12px 24px rgba(15, 23, 42, 0.12);
            z-index: 111000;
            margin-top: 4px;
            padding: 6px;
        }
        
        .aiautotool-dropdown-btn {
            width: 100%;
            padding: 9px 10px;
            border: none;
            background: transparent;
            text-align: left;
            cursor: pointer;
            border-radius: 6px;
            transition: all 0.2s ease;
            position: relative;
        }
        
        .aiautotool-dropdown-btn:hover {
            background: #f0faf5;
        }
        
        .aiautotool-dropdown-btn.premium {
            border-left: 0;
        }
        
        .button-content {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #173b2f;
            font-size: 13px;
            font-weight: 650;
        }
        
        .premium-badge {
            background: #fff7ed;
            color: #c2410c;
            padding: 1px 5px;
            border-radius: 999px;
            font-size: 9px;
            font-weight: bold;
            margin-left: auto;
            border: 1px solid #fed7aa;
        }
        
        .aiautotool-submenu {
            position: absolute;
            left: 100%;
            top: 0;
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            display: none;
            min-width: 120px;
            z-index: 1001;
        }
        
        .aiautotool-submenu-item {
            padding: 8px 12px;
            cursor: pointer;
            transition: background 0.2s ease;
        }
        
        .aiautotool-submenu-item:hover {
            background: #f3f4f6;
        }
        
        .aiautotool-language-container {
            margin-left: auto;
        }
        
        .aiautotool-language-select {
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background: white;
            font-size: 14px;
            cursor: pointer;
        }
        
        .aiautotool-language-select:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        /* Article Settings Modal Styles */
        .aiautotool-article-settings-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 10000;
            display: none;
        }
        
        .aiautotool-modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(2px);
        }
        
        .aiautotool-modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            display: flex;
            flex-direction: column;
            z-index: 10001;
        }
        
        .aiautotool-modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .aiautotool-modal-header h2 {
            margin: 0;
            font-size: 20px;
            font-weight: 600;
            color: #111827;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .aiautotool-modal-close {
            background: none;
            border: none;
            font-size: 20px;
            color: #6b7280;
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.2s;
        }
        
        .aiautotool-modal-close:hover {
            background: #f3f4f6;
            color: #111827;
        }
        
        .aiautotool-modal-body {
            padding: 24px;
            overflow-y: auto;
            flex: 1;
        }
        
        .aiautotool-form-field {
            margin-bottom: 20px;
        }
        
        .aiautotool-form-field label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: #374151;
            font-size: 14px;
        }
        
        .aiautotool-form-field .required {
            color: #ef4444;
        }
        
        .aiautotool-form-field input[type="text"],
        .aiautotool-form-field select,
        .aiautotool-form-field textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
            transition: border-color 0.2s;
        }
        
        .aiautotool-form-field input[type="text"]:focus,
        .aiautotool-form-field select:focus,
        .aiautotool-form-field textarea:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .aiautotool-form-field textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .aiautotool-form-field small {
            display: block;
            margin-top: 4px;
            color: #6b7280;
            font-size: 12px;
        }
        
        .aiautotool-checkbox-field {
            display: flex;
            align-items: flex-start;
            gap: 12px;
            padding: 12px;
            background: #f9fafb;
            border-radius: 6px;
            border: 1px solid #e5e7eb;
        }
        
        .aiautotool-checkbox-field input[type="checkbox"] {
            width: 20px;
            height: 20px;
            margin-top: 2px;
            cursor: pointer;
            flex-shrink: 0;
        }
        
        .aiautotool-checkbox-field .checkbox-label {
            flex: 1;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        
        .aiautotool-checkbox-field .checkbox-label strong {
            color: #111827;
            font-size: 14px;
        }
        
        .aiautotool-checkbox-field .checkbox-description {
            color: #6b7280;
            font-size: 13px;
            font-weight: normal;
        }
        
        .aiautotool-modal-footer {
            padding: 16px 24px;
            border-top: 1px solid #e5e7eb;
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }
        
        .aiautotool-btn-primary,
        .aiautotool-btn-secondary {
            padding: 10px 20px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .aiautotool-btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .aiautotool-btn-primary:hover {
            background: #2563eb;
        }
        
        .aiautotool-btn-secondary {
            background: #f3f4f6;
            color: #374151;
        }
        
        .aiautotool-btn-secondary:hover {
            background: #e5e7eb;
        }
        
        @media (max-width: 768px) {
            .aiautotool-button-groups {
                flex-direction: column;
                align-items: stretch;
            }
            
            .aiautotool-category-dropdown {
                min-width: 100%;
            }
            
            .aiautotool-language-container {
                margin-left: 0;
                margin-top: 8px;
            }
            
            .aiautotool-modal-content {
                width: 95%;
                max-height: 95vh;
            }
            
            .aiautotool-modal-header,
            .aiautotool-modal-body,
            .aiautotool-modal-footer {
                padding: 16px;
            }
        }
    `;
    document.head.appendChild(style);
}

// Add global click listener to close dropdowns
document.addEventListener('click', function (event) {
    // Close dropdowns when clicking outside
    if (!event.target.closest('.aiautotool-category-container')) {
        closeAllDropdowns();
    }

    // Close modal when clicking overlay
    if (modalContainer && modalContainer.style.display === "block") {
        const overlay = modalContainer.querySelector(".aiautotool-modal-overlay");
        if (event.target === overlay) {
            modalContainer.style.display = "none";
        }
    }
});

// Add keyboard shortcuts for better UX
document.addEventListener('keydown', function (event) {
    // Escape key to close dropdowns
    if (event.key === 'Escape') {
        closeAllDropdowns();
    }

    // Ctrl/Cmd + Enter to submit current tool
    if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
        const activeTool = document.querySelector('.tool-content:not([style*="display: none"])');
        if (activeTool) {
            const button = activeTool.querySelector('.aiautotool_input2_button');
            if (button && !button.disabled) {
                button.click();
            }
        }
    }
});

// Add missing functions for button functionality
function openTab(tabName) {
    // Hide all tab content
    var tabcontent = document.getElementsByClassName("tabcontent");
    for (var i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // Remove active class from all tab buttons - add null check
    var tabContainer = document.getElementsByClassName("aiautotool_tab")[0];
    if (tabContainer) {
        var tabbuttons = tabContainer.getElementsByTagName("button");
        for (var i = 0; i < tabbuttons.length; i++) {
            tabbuttons[i].classList.remove("active");
        }
    }

    // Show the selected tab content
    var selectedTab = document.getElementById(tabName);
    if (selectedTab) {
        selectedTab.style.display = "block";
    }

    // Add active class to the clicked button
    var activeButton = document.querySelector('[data-tab="' + tabName + '"]');
    if (activeButton) {
        activeButton.classList.add("active");
    }
}

// Prefer WP AJAX version if requested or if no existing implementation
if (typeof window.sendbardToServer === 'undefined' || (window.aiautotool_js_setting && window.aiautotool_js_setting.use_wp_api === true)) {
    window.sendbardToServer = function (text, divId, option, lang, model = '') {
        return new Promise((resolve, reject) => {
            if (typeof showLoading === 'function') {
                showLoading('Generating content...');
            }

            // Map option to WordPress AJAX action
            var ajaxAction = 'aiautotool_bard_content';
            switch (option) {
                case 'writefull':
                case 'writemore':
                    ajaxAction = 'aiautotool_bard_contentmore';
                    break;
                case 'writebard':
                    ajaxAction = 'aiautotool_bard_content';
                    break;
                case 'bardrewrite':
                    ajaxAction = 'aiautotool_bard_rewrite';
                    break;
                default:
                    ajaxAction = 'aiautotool_bard_content';
                    break;
            }

            var aiRoute = aiautotoolResolveAiRoute(model);
            var dataToSend = {
                question: text,
                lang: lang,
                domain: (window.aiautotool_js_setting && window.aiautotool_js_setting.fsdata && window.aiautotool_js_setting.fsdata.domain) || '',
                provider_id: aiRoute.provider_id,
                model: aiRoute.model,
                info: (window.aiautotool_js_setting && window.aiautotool_js_setting.fsdata) || {}
            };
            var jsonData = JSON.stringify(dataToSend);

            jQuery.ajax({
                url: aiautotool_js_setting.ajax_url,
                type: 'POST',
                data: {
                    action: ajaxAction,
                    data: jsonData,
                    security: (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) ? aiautotool_js_setting.security : ''
                },
                success: function (response) {
                    if (typeof hideLoading === 'function') hideLoading();

                    // Debug log
                    console.log('=== API Response Debug (aipost.js) ===');
                    console.log('Full Response:', response);
                    console.log('Response Code:', response.code);
                    console.log('Response Message:', response.msg);

                    // Check if API returned error code
                    var code = response.code;
                    var isSuccess = (code == '200' || code == 200) && response.result && response.result !== false;

                    if (isSuccess) {
                        // Success - get content from result
                        var processedResult = response.result || '';

                        // Decode HTML entities using virtual DOM (most concise method)
                        if (typeof processedResult === 'string' && processedResult.length > 0 &&
                            (processedResult.indexOf('&lt;') !== -1 || processedResult.indexOf('&gt;') !== -1 ||
                                processedResult.indexOf('&amp;') !== -1 || processedResult.indexOf('&#') !== -1)) {
                            var div = document.createElement('div');
                            div.innerHTML = processedResult;
                            processedResult = div.innerHTML;
                        }

                        const content = processedResult;
                        if (divId) {
                            jQuery('#' + divId).html(content);
                            if (typeof scrollToBottom === 'function') scrollToBottom();
                        }
                        resolve(content);
                    } else {
                        // Error - display message from API
                        const errorMsg = response.msg || 'Failed to generate content';
                        const errorCode = response.code || 'Unknown';

                        console.error('API Error Code:', errorCode);
                        console.error('API Error Message:', errorMsg);

                        // Show error message from API
                        if (typeof Swal !== 'undefined' && Swal) {
                            Swal.fire({
                                title: 'Error!',
                                text: errorMsg,
                                icon: 'error',
                                confirmButtonText: 'Close'
                            }).then(function () {
                                reject(new Error(errorMsg));
                            });
                        } else if (typeof showError === 'function') {
                            showError(errorMsg);
                            reject(new Error(errorMsg));
                        } else {
                            alert(errorMsg);
                            reject(new Error(errorMsg));
                        }
                    }
                },
                error: function (xhr, status, error) {
                    if (typeof hideLoading === 'function') hideLoading();

                    console.error('=== AJAX Error Debug (aipost.js) ===');
                    console.error('Status:', status);
                    console.error('Error:', error);
                    console.error('Response:', xhr.responseText);

                    var errorMsg = error || status || 'Network error occurred';

                    if (typeof Swal !== 'undefined' && Swal) {
                        Swal.fire({
                            title: 'Error!',
                            text: errorMsg,
                            icon: 'error',
                            confirmButtonText: 'Close'
                        });
                    } else if (typeof showError === 'function') {
                        showError(errorMsg);
                    } else {
                        alert(errorMsg);
                    }

                    reject(new Error(errorMsg));
                }
            });
        });
    };
}

if (typeof window.sendbardToServerrewrite === 'undefined' || (window.aiautotool_js_setting && window.aiautotool_js_setting.use_wp_api === true)) {
    window.sendbardToServerrewrite = function (text, divId, option, lang, tone = '') {
        return new Promise((resolve, reject) => {
            if (typeof showLoading === 'function') showLoading('Rewriting...');

            // Map option to WordPress AJAX action
            var ajaxAction = 'aiautotool_bard_content';
            switch (option) {
                case 'writefull':
                case 'writemore':
                    ajaxAction = 'aiautotool_bard_contentmore';
                    break;
                case 'writebard':
                    ajaxAction = 'aiautotool_bard_content';
                    break;
                case 'bardrewrite':
                    ajaxAction = 'aiautotool_bard_rewrite';
                    break;
                default:
                    ajaxAction = 'aiautotool_bard_content';
                    break;
            }

            var dataToSend = {
                question: text,
                lang: lang,
                toneOfVoice: tone,
                domain: (window.aiautotool_js_setting && window.aiautotool_js_setting.fsdata && window.aiautotool_js_setting.fsdata.domain) || '',
                info: (window.aiautotool_js_setting && window.aiautotool_js_setting.fsdata) || {}
            };
            var jsonData = JSON.stringify(dataToSend);

            jQuery.ajax({
                url: aiautotool_js_setting.ajax_url,
                type: 'POST',
                data: {
                    action: ajaxAction,
                    data: jsonData,
                    security: (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) ? aiautotool_js_setting.security : ''
                },
                success: function (response) {
                    if (typeof hideLoading === 'function') hideLoading();

                    // Debug log
                    console.log('=== API Response Debug (aipost.js - Rewrite) ===');
                    console.log('Full Response:', response);
                    console.log('Response Code:', response.code);
                    console.log('Response Message:', response.msg);

                    // Check if API returned error code
                    var code = response.code;
                    var isSuccess = (code == '200' || code == 200) && response.result && response.result !== false;

                    if (isSuccess) {
                        // Success - get content from result
                        var processedResult = response.result || '';

                        // Decode HTML entities using virtual DOM (most concise method)
                        if (typeof processedResult === 'string' && processedResult.length > 0 &&
                            (processedResult.indexOf('&lt;') !== -1 || processedResult.indexOf('&gt;') !== -1 ||
                                processedResult.indexOf('&amp;') !== -1 || processedResult.indexOf('&#') !== -1)) {
                            var div = document.createElement('div');
                            div.innerHTML = processedResult;
                            processedResult = div.innerHTML;
                        }

                        const content = processedResult;
                        if (divId) {
                            jQuery('#' + divId).html(content);
                            if (typeof scrollToBottom === 'function') scrollToBottom();
                        }
                        resolve(content);
                    } else {
                        // Error - display message from API
                        const errorMsg = response.msg || 'Failed to rewrite content';
                        const errorCode = response.code || 'Unknown';

                        console.error('API Error Code (Rewrite):', errorCode);
                        console.error('API Error Message (Rewrite):', errorMsg);

                        // Show error message from API
                        if (typeof Swal !== 'undefined' && Swal) {
                            Swal.fire({
                                title: 'Error!',
                                text: errorMsg,
                                icon: 'error',
                                confirmButtonText: 'Close'
                            }).then(function () {
                                reject(new Error(errorMsg));
                            });
                        } else if (typeof showError === 'function') {
                            showError(errorMsg);
                            reject(new Error(errorMsg));
                        } else {
                            alert(errorMsg);
                            reject(new Error(errorMsg));
                        }
                    }
                },
                error: function (xhr, status, error) {
                    if (typeof hideLoading === 'function') hideLoading();

                    console.error('=== AJAX Error Debug (aipost.js - Rewrite) ===');
                    console.error('Status:', status);
                    console.error('Error:', error);
                    console.error('Response:', xhr.responseText);

                    var errorMsg = error || status || 'Network error occurred';

                    if (typeof Swal !== 'undefined' && Swal) {
                        Swal.fire({
                            title: 'Error!',
                            text: errorMsg,
                            icon: 'error',
                            confirmButtonText: 'Close'
                        });
                    } else if (typeof showError === 'function') {
                        showError(errorMsg);
                    } else {
                        alert(errorMsg);
                    }

                    reject(new Error(errorMsg));
                }
            });
        });
    };
}

// ===== Image parameter inference utilities =====
function pickModelFromPrompt(promptText) {
    const p = (promptText || '').toLowerCase();
    if (/(anime|manga|chibi|cartoon|cel shading)/i.test(p)) return 'flux-anime';
    if (/(realistic|photograph|photo|dslr|bokeh|portrait|cinematic lighting)/i.test(p)) return 'flux-realism';
    if (/(3d|pixar|render|octane|unreal|blender|toy|sculpt|isometric)/i.test(p)) return 'flux-3d';
    if (/(dark|noir|moody|gothic|low key|cyberpunk dark)/i.test(p)) return 'any-dark';
    if (/(fast|quick draft|concept sketch|rough)/i.test(p)) return 'turbo';
    return 'flux';
}

function pickDimensionsFromPrompt(promptText) {
    const p = (promptText || '').toLowerCase();
    // Explicit aspect tokens
    if (/16\s*:\s*9|cinematic|landscape|wide|panorama|ultrawide/.test(p)) return { width: 1280, height: 720 };
    if (/9\s*:\s*16|portrait|vertical|phone|story/.test(p)) return { width: 720, height: 1280 };
    if (/4\s*:\s*3/.test(p)) return { width: 1024, height: 768 };
    if (/3\s*:\s*4/.test(p)) return { width: 768, height: 1024 };
    if (/21\s*:\s*9/.test(p)) return { width: 1920, height: 822 };
    // Default square
    return { width: 1024, height: 1024 };
}

function enrichShortPromptIfNeeded(promptText) {
    const words = (promptText || '').trim().split(/\s+/).filter(Boolean);
    if (words.length >= 50) return promptText.trim();
    if (words.length >= 10) return promptText.trim();

    // Lightweight enrichment to ~50 words without AI
    const base = promptText.trim();
    const extras = [
        'highly detailed',
        'professional composition',
        'dramatic lighting',
        'rich textures',
        'depth of field',
        'cinematic atmosphere',
        'color graded',
        '8k resolution',
        'sharp focus',
        'artistic style',
    ];
    const enriched = `${base}, ${extras.join(', ')}`;
    return enriched;
}

function parseSeedFromPrompt(promptText) {
    let prompt = promptText;
    let seed = null;
    const match = /(?:seed\s*[:=]\s*)(\d{1,10})/i.exec(promptText);
    if (match) {
        seed = parseInt(match[1], 10);
        // remove seed token from prompt
        prompt = promptText.replace(match[0], '').replace(/\s{2,}/g, ' ').trim();
    }
    if (seed === null || Number.isNaN(seed)) {
        seed = Math.floor(Math.random() * 1e6);
    }
    return { seed, prompt };
}

function extractImagineCommand(promptText) {
    const trimmed = (promptText || '').trim();
    if (/^\/imagine\b/i.test(trimmed)) {
        return trimmed.replace(/^\/imagine\s*/i, '').trim();
    }
    return null;
}

function buildMarkdownEmbed({ prompt, width, height }) {
    const encoded = encodeURIComponent(prompt);
    const url = `https://image.pollinations.ai/prompt/${encoded}?width=${width}&height=${height}`;
    return `![${prompt}](${url})\n*${prompt}*`;
}

function inferImageParamsFromPrompt(rawPrompt) {
    // Handle /imagine command extraction first
    const imagine = extractImagineCommand(rawPrompt);
    let prompt = imagine !== null ? imagine : rawPrompt;

    // Seed extraction
    const { seed, prompt: promptWithoutSeed } = parseSeedFromPrompt(prompt);
    prompt = promptWithoutSeed;

    // Enrich if short
    prompt = enrichShortPromptIfNeeded(prompt);

    // Dimensions & model
    const { width, height } = pickDimensionsFromPrompt(prompt);
    const model = pickModelFromPrompt(prompt);

    return { prompt, seed, width, height, model, imagineMode: imagine !== null };
}
// ===== End image parameter inference utilities =====

window.generateImage = async function generateImage() {
    try {
        const promptInput = document.getElementById('promptInput');
        const generateBtn = document.getElementById('generateButton');
        const buttonText = document.getElementById('buttonText');
        const loader = document.getElementById('loader');
        const imageEl = document.getElementById('generatedImage');
        const downloadBtn = document.getElementById('downloadButton');
        const statusEl = document.getElementById('status');

        if (!promptInput) {
            if (typeof showError === 'function') showError('Prompt input not found.'); else alert('Prompt input not found.');
            return;
        }

        const userPrompt = (promptInput.value || '').trim();
        if (!userPrompt) {
            if (typeof showError === 'function') showError('Please enter your prompt.'); else alert('Please enter your prompt.');
            promptInput.focus();
            return;
        }

        const setLoading = (isLoading) => {
            if (generateBtn) generateBtn.disabled = isLoading;
            if (buttonText) buttonText.textContent = isLoading ? 'Generating...' : 'Generate Image';
            if (loader) loader.style.display = isLoading ? 'inline-block' : 'none';
        };

        setLoading(true);

        // Infer parameters from prompt per spec
        const inferred = inferImageParamsFromPrompt(userPrompt);

        // If /imagine mode, also provide markdown embed and copy to clipboard
        if (inferred.imagineMode) {
            const md = buildMarkdownEmbed({ prompt: inferred.prompt, width: inferred.width, height: inferred.height });
            try { await navigator.clipboard.writeText(md); } catch (_) { }
            if (statusEl) statusEl.textContent = 'Markdown image copied to clipboard.';
        }

        // Override by optional controls if present
        const modelSelect = document.getElementById('modelSelect');
        populateAIImageModelSelect(modelSelect, modelSelect ? modelSelect.value : '');
        const seedInput = document.getElementById('seedInput');
        const widthInput = document.getElementById('widthInput');
        const heightInput = document.getElementById('heightInput');

        const model = modelSelect ? (modelSelect.value || inferred.model) : inferred.model;
        const seed = seedInput ? (seedInput.value || inferred.seed) : inferred.seed;
        const width = widthInput ? parseInt(widthInput.value || String(inferred.width), 10) : inferred.width;
        const height = heightInput ? parseInt(heightInput.value || String(inferred.height), 10) : inferred.height;

        // Generate image via Pollinations
        const url = await generateImageFromAPI(inferred.prompt, {
            model,
            seed,
            width,
            height,
            nologo: true,
            negative_prompt: 'worst quality, blurry'
        });

        // Display image
        if (imageEl) {
            const finalUrl = url + (url.includes('?') ? '&' : '?') + 'ts=' + Date.now();
            imageEl.src = finalUrl;
            imageEl.classList.remove('hidden');
        }

        // Prepare download (try to save to media library first)
        let downloadableUrl = url;
        try {
            if (typeof uploadImageToMediaLibrary === 'function') {
                const saved = await uploadImageToMediaLibrary(url, inferred.prompt);
                if (saved) downloadableUrl = saved;
            }
        } catch (e) {
            console.warn('Save to media library failed, fallback to direct URL.', e);
        }

        if (downloadBtn) {
            downloadBtn.href = downloadableUrl;
            downloadBtn.setAttribute('download', 'ai-image-' + Date.now() + '.png');
            downloadBtn.classList.remove('hidden');
        }

        if (statusEl) {
            statusEl.textContent = `Model: ${model} • Seed: ${seed} • ${width}x${height}`;
        }

    } catch (err) {
        console.error('Generate Image Error:', err);
        if (typeof showError === 'function') showError(err && err.message ? err.message : 'Failed to generate image.');
    } finally {
        const generateBtn = document.getElementById('generateButton');
        const buttonText = document.getElementById('buttonText');
        const loader = document.getElementById('loader');
        if (generateBtn) generateBtn.disabled = false;
        if (buttonText) buttonText.textContent = 'Generate Image';
        if (loader) loader.style.display = 'none';
    }
};

// Provide an advanced handler that mirrors the same inference but reads advanced inputs
window.generateAdvancedImage = async function generateAdvancedImage() {
    try {
        const promptInput = document.getElementById('advancedPromptInput') || document.getElementById('promptInput');
        const generateBtn = document.getElementById('generateAdvancedButton') || document.getElementById('generateButton');
        const buttonText = document.getElementById('advancedButtonText') || document.getElementById('buttonText');
        const loader = document.getElementById('advancedLoader') || document.getElementById('loader');
        const imageEl = document.getElementById('generatedAdvancedImage') || document.getElementById('generatedImage');
        const downloadBtn = document.getElementById('downloadAdvancedButton') || document.getElementById('downloadButton');
        const statusEl = document.getElementById('status');
        const imagePromptText = document.getElementById('imagePrompt');

        if (!promptInput) {
            if (typeof showError === 'function') showError('Prompt input not found.'); else alert('Prompt input not found.');
            return;
        }

        const userPrompt = (promptInput.value || '').trim();
        if (!userPrompt) {
            if (typeof showError === 'function') showError('Please enter your prompt.'); else alert('Please enter your prompt.');
            promptInput.focus();
            return;
        }

        const setLoading = (isLoading) => {
            if (generateBtn) generateBtn.disabled = isLoading;
            if (buttonText) buttonText.textContent = isLoading ? 'Generating...' : 'Generate Image';
            if (loader) loader.style.display = isLoading ? 'inline-block' : 'none';
        };

        setLoading(true);

        // Inference
        const inferred = inferImageParamsFromPrompt(userPrompt);

        // Read explicit advanced fields if present to override
        const modelSelect = document.getElementById('modelSelect');
        populateAIImageModelSelect(modelSelect, modelSelect ? modelSelect.value : '');
        const seedInput = document.getElementById('seedInput');
        const widthInput = document.getElementById('widthInput');
        const heightInput = document.getElementById('heightInput');

        const model = modelSelect ? (modelSelect.value || inferred.model) : inferred.model;
        const seed = seedInput ? (seedInput.value || inferred.seed) : inferred.seed;
        const width = widthInput ? parseInt(widthInput.value || String(inferred.width), 10) : inferred.width;
        const height = heightInput ? parseInt(heightInput.value || String(inferred.height), 10) : inferred.height;

        const url = await generateImageFromAPI(inferred.prompt, {
            model,
            seed,
            width,
            height,
            nologo: true,
            negative_prompt: 'worst quality, blurry'
        });

        if (imageEl) {
            const finalUrl = url + (url.includes('?') ? '&' : '?') + 'ts=' + Date.now();
            imageEl.src = finalUrl;
            imageEl.classList.remove('hidden');
        }
        if (imagePromptText) {
            imagePromptText.textContent = inferred.prompt;
            imagePromptText.classList.remove('hidden');
        }

        let downloadableUrl = url;
        try {
            if (typeof uploadImageToMediaLibrary === 'function') {
                const saved = await uploadImageToMediaLibrary(url, inferred.prompt);
                if (saved) downloadableUrl = saved;
            }
        } catch (e) { console.warn(e); }

        if (downloadBtn) {
            downloadBtn.href = downloadableUrl;
            downloadBtn.setAttribute('download', 'ai-image-' + Date.now() + '.png');
            downloadBtn.classList.remove('hidden');
        }
        if (statusEl) statusEl.textContent = `Model: ${model} • Seed: ${seed} • ${width}x${height}`;

    } catch (err) {
        console.error('Generate Advanced Image Error:', err);
        if (typeof showError === 'function') showError(err && err.message ? err.message : 'Failed to generate image.');
    } finally {
        const generateBtn = document.getElementById('generateAdvancedButton') || document.getElementById('generateButton');
        const buttonText = document.getElementById('advancedButtonText') || document.getElementById('buttonText');
        const loader = document.getElementById('advancedLoader') || document.getElementById('loader');
        if (generateBtn) generateBtn.disabled = false;
        if (buttonText) buttonText.textContent = 'Generate Image';
        if (loader) loader.style.display = 'none';
    }
};

// ===== Image Generation Modal Popup =====
function showImageGenerationModal() {
    // Remove existing modal if any
    const existingModal = document.getElementById('imageGenerationModal');
    if (existingModal) {
        existingModal.remove();
    }

    // Create modal HTML
    const modalHTML = `
        <div id="imageGenerationModal" class="aiautotool-modal" style="
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 999999;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: Arial, sans-serif;
        ">
            <div class="modal-content" style="
                background: #2a2a2a;
                border-radius: 1rem;
                box-shadow: 0 10px 20px rgba(0, 0, 0, 0.5);
                padding: 2rem;
                max-width: 800px;
                width: 90%;
                max-height: 90vh;
                overflow-y: auto;
                border: 1px solid #3a3a3a;
                position: relative;
            ">
                <button onclick="closeImageGenerationModal()" style="
                    position: absolute;
                    top: 1rem;
                    right: 1rem;
                    background: #4a4a4a;
                    color: #e0e0e0;
                    border: none;
                    border-radius: 50%;
                    width: 2rem;
                    height: 2rem;
                    cursor: pointer;
                    font-size: 1.2rem;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                ">&times;</button>
                
                <h1 style="
                    color: #e0e0e0;
                    text-shadow: 0 0 10px rgba(107, 33, 168, 0.5);
                    text-align: center;
                    margin-bottom: 1.5rem;
                    font-size: 2rem;
                ">AI Image Generator</h1>
                
                <div style="margin-bottom: 1.5rem;">
                    <label style="display: block; color: #e0e0e0; margin-bottom: 0.5rem; font-weight: bold;">Prompt</label>
                    <textarea id="modalPromptInput" rows="4" style="
                        width: 100%;
                        padding: 1rem;
                        border-radius: 0.5rem;
                        background: #3a3a3a;
                        color: #e0e0e0;
                        border: 1px solid #4a4a4a;
                        resize: none;
                        font-size: 1rem;
                    " placeholder="Enter your prompt (e.g., 'A haunted forest at midnight')"></textarea>
                    
                    <div id="enhancedPromptPreview" style="
                        margin-top: 1rem;
                        padding: 1rem;
                        background: #1a1a1a;
                        border-radius: 0.5rem;
                        border: 1px solid #4a4a4a;
                        display: none;
                    ">
                        <div style="color: #e0e0e0; font-weight: bold; margin-bottom: 0.5rem;">Enhanced Professional Prompt:</div>
                        <div id="enhancedPromptText" style="
                            color: #a0a0a0;
                            font-size: 0.9rem;
                            line-height: 1.4;
                            font-family: monospace;
                            word-break: break-word;
                        "></div>
                        <div style="margin-top: 0.5rem; font-size: 0.8rem; color: #6b21a8;">
                            This enhanced prompt will be used for generation to ensure high-quality, professional results.
                        </div>
                    </div>
                </div>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1.5rem;">
                    <div>
                        <label style="display: block; color: #e0e0e0; margin-bottom: 0.5rem; font-weight: bold;">Model</label>
                        <select id="modalModelSelect" style="
                            width: 100%;
                            padding: 0.75rem;
                            border-radius: 0.5rem;
                            background: #3a3a3a;
                            color: #e0e0e0;
                            border: 1px solid #4a4a4a;
                            font-size: 1rem;
                        ">
                            <option value="flux">Flux (Default)</option>
                            <option value="flux-realism">Flux Realism</option>
                            <option value="any-dark">Any Dark</option>
                            <option value="flux-anime">Flux Anime</option>
                            <option value="flux-3d">Flux 3D</option>
                            <option value="turbo">Turbo</option>
                        </select>
                    </div>
                    <div>
                        <label style="display: block; color: #e0e0e0; margin-bottom: 0.5rem; font-weight: bold;">Seed</label>
                        <input type="number" id="modalSeedInput" style="
                            width: 100%;
                            padding: 0.75rem;
                            border-radius: 0.5rem;
                            background: #3a3a3a;
                            color: #e0e0e0;
                            border: 1px solid #4a4a4a;
                            font-size: 1rem;
                        " value="42" min="0">
                    </div>
                </div>
                
                <div style="margin-bottom: 1.5rem;">
                    <label style="display: block; color: #e0e0e0; margin-bottom: 0.5rem; font-weight: bold;">Aspect Ratio</label>
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.5rem;">
                        <button class="aspect-ratio-btn active" data-width="1024" data-height="1024" style="
                            background: #6b21a8;
                            color: #e0e0e0;
                            border: 1px solid #6b21a8;
                            padding: 0.75rem;
                            border-radius: 0.5rem;
                            cursor: pointer;
                            font-size: 0.9rem;
                        ">1:1<br><span style="font-size: 0.7rem; opacity: 0.8;">(1024x1024)</span></button>
                        <button class="aspect-ratio-btn" data-width="1280" data-height="720" style="
                            background: #3a3a3a;
                            color: #e0e0e0;
                            border: 1px solid #4a4a4a;
                            padding: 0.75rem;
                            border-radius: 0.5rem;
                            cursor: pointer;
                            font-size: 0.9rem;
                        ">16:9<br><span style="font-size: 0.7rem; opacity: 0.8;">(1280x720)</span></button>
                        <button class="aspect-ratio-btn" data-width="720" data-height="1280" style="
                            background: #3a3a3a;
                            color: #e0e0e0;
                            border: 1px solid #4a4a4a;
                            padding: 0.75rem;
                            border-radius: 0.5rem;
                            cursor: pointer;
                            font-size: 0.9rem;
                        ">9:16<br><span style="font-size: 0.7rem; opacity: 0.8;">(720x1280)</span></button>
                        <button class="aspect-ratio-btn" data-width="1024" data-height="768" style="
                            background: #3a3a3a;
                            color: #e0e0e0;
                            border: 1px solid #4a4a4a;
                            padding: 0.75rem;
                            border-radius: 0.5rem;
                            cursor: pointer;
                            font-size: 0.9rem;
                        ">4:3<br><span style="font-size: 0.7rem; opacity: 0.8;">(1024x768)</span></button>
                        <button class="aspect-ratio-btn" data-width="768" data-height="1024" style="
                            background: #3a3a3a;
                            color: #e0e0e0;
                            border: 1px solid #4a4a4a;
                            padding: 0.75rem;
                            border-radius: 0.5rem;
                            cursor: pointer;
                            font-size: 0.9rem;
                        ">3:4<br><span style="font-size: 0.7rem; opacity: 0.8;">(768x1024)</span></button>
                        <button class="aspect-ratio-btn" data-width="1920" data-height="822" style="
                            background: #3a3a3a;
                            color: #e0e0e0;
                            border: 1px solid #4a4a4a;
                            padding: 0.75rem;
                            border-radius: 0.5rem;
                            cursor: pointer;
                            font-size: 0.9rem;
                        ">21:9<br><span style="font-size: 0.7rem; opacity: 0.8;">(1920x822)</span></button>
                    </div>
                </div>
                
                <button id="modalGenerateButton" onclick="generateImageFromModal()" style="
                    width: 100%;
                    background: #6b21a8;
                    color: white;
                    padding: 1rem;
                    border-radius: 0.5rem;
                    font-weight: bold;
                    font-size: 1.1rem;
                    border: none;
                    cursor: pointer;
                    margin-bottom: 1.5rem;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 0.5rem;
                ">
                    <span id="modalButtonText">Generate Image</span>
                    <div id="modalLoader" style="
                        display: none;
                        border: 3px solid #4a4a4a;
                        border-top: 3px solid #e0e0e0;
                        border-radius: 50%;
                        width: 20px;
                        height: 20px;
                        animation: spin 1s linear infinite;
                    "></div>
                </button>
                
                <div id="modalImageContainer" style="text-align: center; display: none;">
                    <img id="modalGeneratedImage" style="
                        max-width: 100%;
                        height: auto;
                        border-radius: 0.5rem;
                        border: 1px solid #4a4a4a;
                        margin-bottom: 1rem;
                    " alt="Generated Image">
                    <div style="margin-bottom: 1rem;">
                        <a id="modalDownloadButton" style="
                            display: inline-block;
                            background: #059669;
                            color: white;
                            padding: 0.75rem 1.5rem;
                            border-radius: 0.5rem;
                            text-decoration: none;
                            font-weight: bold;
                            margin-right: 0.5rem;
                        ">Download Image</a>
                        <button onclick="insertImageToEditor()" style="
                            background: #2563eb;
                            color: white;
                            padding: 0.75rem 1.5rem;
                            border-radius: 0.5rem;
                            border: none;
                            cursor: pointer;
                            font-weight: bold;
                            margin-right: 0.5rem;
                        ">Insert to Editor</button>
                        <button id="modalSetFeaturedButton" onclick="handleSetFeaturedImageFromModal()" style="
                            background: #dc2626;
                            color: white;
                            padding: 0.75rem 1.5rem;
                            border-radius: 0.5rem;
                            border: none;
                            cursor: pointer;
                            font-weight: bold;
                        ">Set as Featured Image</button>
                    </div>
                </div>
                
                <div id="modalStatus" style="
                    text-align: center;
                    color: #a0a0a0;
                    margin-top: 1rem;
                    font-style: italic;
                "></div>
            </div>
        </div>
        
        <style>
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            .aspect-ratio-btn:hover {
                background: #4a4a4a !important;
            }
        </style>
    `;

    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    populateAIImageModelSelect(document.getElementById('modalModelSelect'));

    // Add event listeners for aspect ratio buttons
    const aspectRatioBtns = document.querySelectorAll('.aspect-ratio-btn');
    aspectRatioBtns.forEach(btn => {
        btn.addEventListener('click', function () {
            aspectRatioBtns.forEach(b => {
                b.style.background = '#3a3a3a';
                b.style.borderColor = '#4a4a4a';
            });
            this.style.background = '#6b21a8';
            this.style.borderColor = '#6b21a8';
        });
    });

    // Add event listener for prompt input to show enhanced preview


    // Prefill prompt with selected text if available
    setTimeout(() => {
        try {
            const promptEl = document.getElementById('modalPromptInput');
            if (promptEl) {
                let selected = '';
                if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
                    selected = tinymce.activeEditor.selection.getContent({ format: 'text' }) || '';
                }
                if (selected) {
                    promptEl.value = selected.trim();
                }
                promptEl.focus();
            }
        } catch (e) { console.warn(e); }
    }, 100);
}

function closeImageGenerationModal() {
    const modal = document.getElementById('imageGenerationModal');
    if (modal) {
        modal.remove();
    }
}

async function generateImageFromModal() {
    try {
        const promptInput = document.getElementById('modalPromptInput');
        const generateBtn = document.getElementById('modalGenerateButton');
        const buttonText = document.getElementById('modalButtonText');
        const loader = document.getElementById('modalLoader');
        const imageContainer = document.getElementById('modalImageContainer');
        const imageEl = document.getElementById('modalGeneratedImage');
        const downloadBtn = document.getElementById('modalDownloadButton');
        const statusEl = document.getElementById('modalStatus');

        if (!promptInput) {
            alert('Prompt input not found.');
            return;
        }

        const userPrompt = (promptInput.value || '').trim();
        if (!userPrompt) {
            alert('Please enter your prompt.');
            promptInput.focus();
            return;
        }

        const setLoading = (isLoading) => {
            if (generateBtn) generateBtn.disabled = isLoading;
            if (buttonText) buttonText.textContent = isLoading ? 'Generating...' : 'Generate Image';
            if (loader) loader.style.display = isLoading ? 'inline-block' : 'none';
        };

        setLoading(true);
        if (statusEl) statusEl.textContent = '';

        // Step 1: Generate AI-enhanced prompt
        if (statusEl) statusEl.textContent = 'Step 1/3: Generating AI-enhanced prompt...';
        const enhancedPrompt = await generateAIImagePrompt(userPrompt);

        // Show enhanced prompt preview
        const enhancedPromptPreview = document.getElementById('enhancedPromptPreview');
        const enhancedPromptText = document.getElementById('enhancedPromptText');
        if (enhancedPromptPreview && enhancedPromptText) {
            enhancedPromptText.textContent = enhancedPrompt;
            enhancedPromptPreview.style.display = 'block';
        }

        // Get selected aspect ratio
        const activeAspectBtn = document.querySelector('.aspect-ratio-btn[style*="6b21a8"]');
        const width = activeAspectBtn ? parseInt(activeAspectBtn.dataset.width) : 1024;
        const height = activeAspectBtn ? parseInt(activeAspectBtn.dataset.height) : 1024;

        // Get other parameters
        const modalModelSelect = document.getElementById('modalModelSelect');
        populateAIImageModelSelect(modalModelSelect, modalModelSelect ? modalModelSelect.value : '');
        const model = modalModelSelect?.value || '';
        const seed = document.getElementById('modalSeedInput')?.value || 42;

        // Step 2: Generate image via Pollinations using AI-enhanced prompt
        if (statusEl) statusEl.textContent = 'Step 2/3: Creating AI image...';
        const url = await generateImageFromAPI(enhancedPrompt, {
            model: model,
            seed: seed,
            width: width,
            height: height,
            nologo: true,
            negative_prompt: 'worst quality, blurry'
        });

        // Step 3: Upload to WP Media Library and get new link
        if (statusEl) statusEl.textContent = 'Step 3/3: Uploading to WordPress...';
        let finalImageUrl = url;
        let mediaLibraryId = null;

        try {
            if (typeof uploadImageToMediaLibrary === 'function') {
                const saved = await uploadImageToMediaLibrary(url, enhancedPrompt);
                if (saved) {
                    finalImageUrl = saved;
                    // Extract media ID from URL if possible
                    const match = saved.match(/wp-content\/uploads\/(\d{4}\/\d{2}\/.*)/);
                    if (match) {
                        mediaLibraryId = match[1];
                    }
                }
            }
        } catch (e) {
            console.warn('Upload to media library failed:', e);
            if (statusEl) statusEl.textContent = 'Warning: Could not save to media library, using direct URL.';
        }

        // Display image
        if (imageEl) {
            const finalUrl = finalImageUrl + (finalImageUrl.includes('?') ? '&' : '?') + 'ts=' + Date.now();
            imageEl.src = finalUrl;
        }
        if (imageContainer) {
            imageContainer.style.display = 'block';
        }

        // Update download button with final URL
        if (downloadBtn) {
            downloadBtn.href = finalImageUrl;
            downloadBtn.download = 'ai-image-' + Date.now() + '.png';
        }

        // Show final status
        if (statusEl) {
            const statusText = mediaLibraryId
                ? `✅ Image created and saved to WordPress Media Library! Model: ${model} • Seed: ${seed} • ${width}x${height}`
                : `✅ Image generated! Model: ${model} • Seed: ${seed} • ${width}x${height}`;
            statusEl.textContent = statusText;
        }

    } catch (err) {
        console.error('Generate Image Error:', err);
        const statusEl = document.getElementById('modalStatus');
        if (statusEl) statusEl.textContent = err && err.message ? err.message : 'Failed to generate image.';
    } finally {
        const generateBtn = document.getElementById('modalGenerateButton');
        const buttonText = document.getElementById('modalButtonText');
        const loader = document.getElementById('modalLoader');
        if (generateBtn) generateBtn.disabled = false;
        if (buttonText) buttonText.textContent = 'Generate Image';
        if (loader) loader.style.display = 'none';
    }
}

function insertImageToEditor() {
    const imageEl = document.getElementById('modalGeneratedImage');
    if (!imageEl || !imageEl.src) {
        alert('No image to insert.');
        return;
    }

    try {
        if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
            const imgHtml = `<img src="${imageEl.src}" alt="AI Generated Image" style="max-width: 100%; height: auto;">`;
            tinymce.activeEditor.insertContent(imgHtml);
            closeImageGenerationModal();
        } else {
            // Fallback for non-TinyMCE editors
            const textarea = document.querySelector('textarea[name="content"], #content, .wp-editor-area');
            if (textarea) {
                const imgHtml = `\n![AI Generated Image](${imageEl.src})\n`;
                const start = textarea.selectionStart;
                const end = textarea.selectionEnd;
                textarea.value = textarea.value.substring(0, start) + imgHtml + textarea.value.substring(end);
                textarea.selectionStart = textarea.selectionEnd = start + imgHtml.length;
                textarea.focus();
                closeImageGenerationModal();
            } else {
                alert('Editor not found. Please copy the image URL manually.');
            }
        }
    } catch (e) {
        console.error('Error inserting image:', e);
        alert('Error inserting image. Please copy the image URL manually.');
    }
}
// ===== End Image Generation Modal Popup =====

// ===== Professional Prompt Enhancement System =====
function enhancePromptToProfessional(userPrompt) {
    // Parse the user's prompt and create a professional AI image generation prompt
    const promptAnalysis = analyzeUserPrompt(userPrompt);

    // Build the enhanced prompt following the professional structure
    const enhancedPrompt = buildProfessionalPrompt(promptAnalysis);

    return enhancedPrompt;
}

function analyzeUserPrompt(userPrompt) {
    const prompt = (userPrompt || '').toLowerCase().trim();

    // Analyze content type and extract key elements
    let sceneType = 'general';
    let keyElements = [];
    let textIntegration = '';
    let lighting = 'cinematic dramatic lighting, natural ambient light, professional studio setup';
    let background = 'depth of field blur, clean professional environment';

    // Detect scene type based on keywords
    if (/(tech|ai|artificial intelligence|digital|computer|software|app)/i.test(prompt)) {
        sceneType = 'technology';
        keyElements = ['modern tech workspace', 'digital interface elements', 'professional tech environment'];
    } else if (/(business|finance|market|economy|corporate|office)/i.test(prompt)) {
        sceneType = 'business';
        keyElements = ['professional business environment', 'corporate setting', 'modern office space'];
    } else if (/(education|learning|school|university|classroom)/i.test(prompt)) {
        sceneType = 'education';
        keyElements = ['modern learning environment', 'educational technology', 'professional classroom'];
    } else if (/(nature|landscape|outdoor|environment|scenic)/i.test(prompt)) {
        sceneType = 'nature';
        keyElements = ['breathtaking natural landscape', 'outdoor environment', 'scenic beauty'];
        lighting = 'natural golden hour lighting, dramatic sunset atmosphere, natural ambient light';
        background = 'depth of field blur, natural environment, professional photography';
    } else if (/(portrait|person|people|human|face)/i.test(prompt)) {
        sceneType = 'portrait';
        keyElements = ['professional portrait setting', 'studio environment', 'high-quality photography'];
        lighting = 'professional studio lighting, dramatic portrait lighting, natural skin tones';
    } else if (/(art|creative|design|artistic|painting)/i.test(prompt)) {
        sceneType = 'artistic';
        keyElements = ['artistic composition', 'creative elements', 'artistic atmosphere'];
        lighting = 'artistic lighting, creative atmosphere, dramatic shadows';
    }

    // Extract specific elements from user prompt
    const specificElements = prompt.split(/\s+/).filter(word =>
        word.length > 3 && !['the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by'].includes(word)
    );

    if (specificElements.length > 0) {
        keyElements = [...keyElements, ...specificElements.slice(0, 3)];
    }

    // Determine if text integration is needed
    if (/(text|word|letter|title|headline|label)/i.test(prompt)) {
        textIntegration = 'elegant typography, clear readable text, integrated naturally into scene';
    }

    return {
        sceneType,
        keyElements: keyElements.join(', '),
        textIntegration,
        lighting,
        background,
        originalPrompt: userPrompt
    };
}

function buildProfessionalPrompt(analysis) {
    const { sceneType, keyElements, textIntegration, lighting, background, originalPrompt } = analysis;

    // Build main scene description
    let mainScene = '';
    switch (sceneType) {
        case 'technology':
            mainScene = 'modern tech workspace, minimalist professional environment';
            break;
        case 'business':
            mainScene = 'professional business environment, corporate setting';
            break;
        case 'education':
            mainScene = 'modern learning environment, advanced educational setting';
            break;
        case 'nature':
            mainScene = 'breathtaking natural landscape, outdoor environment';
            break;
        case 'portrait':
            mainScene = 'professional portrait setting, studio environment';
            break;
        case 'artistic':
            mainScene = 'artistic creative environment, studio setting';
            break;
        default:
            mainScene = 'professional modern environment, clean setting';
    }

    // Build the complete professional prompt
    let enhancedPrompt = `${mainScene} | ${keyElements}`;

    if (textIntegration) {
        enhancedPrompt += ` | ${textIntegration}`;
    }

    enhancedPrompt += ` | ${lighting} | ${background} | 8k resolution, hyperrealistic, photorealistic quality, octane render, cinematic composition, sharp focus, high detail, professional photography`;

    // Add specific enhancements based on scene type
    if (sceneType === 'nature') {
        enhancedPrompt += ', natural textures, environmental realism';
    } else if (sceneType === 'portrait') {
        enhancedPrompt += ', professional portrait photography, natural skin tones';
    } else if (sceneType === 'technology') {
        enhancedPrompt += ', modern tech aesthetics, digital precision';
    }

    return enhancedPrompt;
}

function createPromptJSON(userPrompt) {
    const enhancedPrompt = enhancePromptToProfessional(userPrompt);

    return {
        prompt_image: {
            prompt: enhancedPrompt,
            original_input: userPrompt,
            enhanced: true,
            parameters: {
                resolution: "8k",
                quality: "hyperrealistic",
                render: "octane",
                composition: "cinematic",
                focus: "sharp",
                detail: "high"
            }
        }
    };
}

// Function to get the enhanced prompt text (for API calls)
function getEnhancedPromptText(userPrompt) {
    const enhancedPrompt = enhancePromptToProfessional(userPrompt);
    return enhancedPrompt;
}
// ===== End Professional Prompt Enhancement System =====

function showEnhancedPromptPreview(userPrompt) {
    const previewDiv = document.getElementById('enhancedPromptPreview');
    const enhancedText = document.getElementById('enhancedPromptText');

    if (previewDiv && enhancedText) {
        // Show loading state
        enhancedText.textContent = 'Generating AI-enhanced prompt...';
        previewDiv.style.display = 'block';

        // Generate AI-enhanced prompt
        generateAIImagePrompt(userPrompt)
            .then(enhancedPrompt => {
                enhancedText.textContent = enhancedPrompt;
            })
            .catch(error => {
                console.warn('Error generating AI prompt:', error);
                enhancedText.textContent = 'AI prompt generation failed. Using fallback enhancement.';
            });
    }
}

function hideEnhancedPromptPreview() {
    const previewDiv = document.getElementById('enhancedPromptPreview');
    if (previewDiv) {
        previewDiv.style.display = 'none';
    }
}

// ===== AI-Powered Prompt Enhancement System =====
async function generateAIImagePrompt(userPrompt) {
    try {
        // Call AI API to generate professional image prompt
        const aiPrompt = `You are an expert AI image prompt generator. Create a professional, detailed prompt for AI image generation based on this user input: "${userPrompt}"

Requirements:
- Output 100% in English
- Create a detailed, professional prompt following this structure:
  [Main Scene] | [Key Elements] | [Text Integration if needed] | [Lighting & Atmosphere] | [Technical Parameters]
- Include: 8k resolution, hyperrealistic, photorealistic quality, cinematic composition
- Make it suitable for AI image generation APIs
- Keep it under 200 words
- Focus on visual details and professional quality

Generate only the enhanced prompt, no explanations or additional text.`;

        // Use existing AI content generation function if available
        var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : (typeof sendbardToServer !== 'undefined' ? sendbardToServer : null);
        if (sendFn) {
            try {
                const enhancedPrompt = await sendFn(aiPrompt, null, 'content', 'en', 'gemini');
                return enhancedPrompt ? enhancedPrompt.trim() : '';
            } catch (error) {
                // Error message is already shown by sendbardToServer (Swal/alert)
                console.error('Error enhancing prompt:', error);
                // Fallback to simple enhancement
                return enhancePromptFallback(userPrompt);
            }
        }

        // Fallback: use a simple enhancement if AI API is not available
        return enhancePromptFallback(userPrompt);

    } catch (error) {
        console.warn('AI prompt generation failed, using fallback:', error);
        return enhancePromptFallback(userPrompt);
    }
}

function enhancePromptFallback(userPrompt) {
    // Simple fallback enhancement when AI is not available
    const basePrompt = userPrompt.trim();
    const enhancements = [
        '8k resolution',
        'hyperrealistic quality',
        'photorealistic',
        'cinematic composition',
        'professional photography',
        'sharp focus',
        'high detail',
        'dramatic lighting'
    ];

    return `${basePrompt}, ${enhancements.join(', ')}`;
}

function createPromptJSON(userPrompt, enhancedPrompt) {
    return {
        prompt_image: {
            prompt: enhancedPrompt,
            original_input: userPrompt,
            enhanced: true,
            ai_generated: true,
            parameters: {
                resolution: "8k",
                quality: "hyperrealistic",
                composition: "cinematic",
                focus: "sharp",
                detail: "high"
            }
        }
    };
}

// Function to get the enhanced prompt text (for API calls)
async function getEnhancedPromptText(userPrompt) {
    const enhancedPrompt = await generateAIImagePrompt(userPrompt);
    return enhancedPrompt;
}
// ===== End AI-Powered Prompt Enhancement System =====

// Function test và demo chức năng suggest image đã được cải tiến
async function testEnhancedImageSuggestion() {
    try {
        console.log('=== Testing Enhanced Image Suggestion System ===');

        // Test content mẫu
        const testContent = `
            <h2>Quy trình phát triển phần mềm</h2>
            <p>Phát triển phần mềm là một quy trình phức tạp bao gồm nhiều bước quan trọng. Đầu tiên, chúng ta cần phân tích yêu cầu từ khách hàng để hiểu rõ những gì họ mong muốn.</p>
            
            <p>Bước thứ hai là thiết kế hệ thống. Trong giai đoạn này, các kiến trúc sư phần mềm sẽ tạo ra các sơ đồ và mô hình để mô tả cách hệ thống sẽ hoạt động.</p>
            
            <p>So sánh với phương pháp truyền thống, phương pháp Agile mang lại nhiều lợi ích hơn. Phương pháp truyền thống thường mất nhiều thời gian và khó thay đổi, trong khi Agile linh hoạt và nhanh chóng hơn.</p>
            
            <p>Theo thống kê mới nhất, 78% các dự án sử dụng phương pháp Agile thành công hơn so với các dự án sử dụng phương pháp Waterfall. Điều này cho thấy hiệu quả của việc áp dụng Agile trong phát triển phần mềm.</p>
            
            <p>Sản phẩm của chúng tôi có nhiều tính năng nổi bật như giao diện thân thiện, tốc độ xử lý nhanh, và khả năng mở rộng cao. Những tính năng này giúp người dùng có trải nghiệm tốt nhất.</p>
        `;

        const testTitle = 'Quy trình phát triển phần mềm hiện đại';

        console.log('Test Content:', testContent);
        console.log('Test Title:', testTitle);

        // Step 1: Phân tích vị trí chèn hình ảnh
        console.log('\n--- Step 1: Analyzing Image Positions ---');
        const imagePositions = await analyzeImagePositions(testContent);
        console.log('Found positions:', imagePositions.length);

        imagePositions.forEach((pos, index) => {
            console.log(`Position ${index + 1}:`, {
                index: pos.index,
                score: pos.score,
                style: pos.suggestedStyle,
                contentType: pos.contentType,
                visualElements: pos.visualElements,
                reason: pos.reason,
                paragraphPreview: pos.paragraph.substring(0, 100) + '...'
            });
        });

        // Step 2: Tạo prompt hình ảnh
        console.log('\n--- Step 2: Generating Image Prompts ---');
        const imagePrompts = await generateImagePrompts(testTitle, testContent, imagePositions);
        console.log('Generated prompts:', imagePrompts.length);

        imagePrompts.forEach((prompt, index) => {
            console.log(`Prompt ${index + 1}:`, {
                style: prompt.suggestedStyle,
                contentType: prompt.contentType,
                visualElements: prompt.visualElements,
                aiScore: prompt.aiScore,
                enhanced: prompt.enhanced,
                fallback: prompt.fallback,
                prompt: prompt.prompt,
                paragraphPreview: prompt.originalParagraph.substring(0, 100) + '...'
            });
        });

        // Step 3: Hiển thị thống kê
        console.log('\n--- Step 3: Statistics ---');
        const styles = getUniqueStyles(imagePrompts);
        const contentTypes = getUniqueContentTypes(imagePrompts);
        const enhancedCount = imagePrompts.filter(p => p.enhanced).length;
        const fallbackCount = imagePrompts.filter(p => p.fallback).length;

        console.log('Unique styles:', styles);
        console.log('Content types:', contentTypes);
        console.log('Enhanced prompts:', enhancedCount);
        console.log('Fallback prompts:', fallbackCount);

        console.log('\n=== Enhanced Image Suggestion Test Completed ===');

        return {
            positions: imagePositions,
            prompts: imagePrompts,
            statistics: {
                styles,
                contentTypes,
                enhancedCount,
                fallbackCount
            }
        };

    } catch (error) {
        console.error('Error in test:', error);
        throw error;
    }
}

// Function demo chức năng suggest image với giao diện
function demoEnhancedImageSuggestion() {
    // Tạo modal demo
    const demoModal = document.createElement('div');
    demoModal.innerHTML = `
        <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 9999; display: flex; align-items: center; justify-content: center;">
            <div style="background: white; padding: 30px; border-radius: 10px; max-width: 800px; max-height: 80vh; overflow-y: auto;">
                <h2>Enhanced Image Suggestion Demo</h2>
                <p>Testing the improved image suggestion system with professional prompt generation.</p>
                
                <div style="margin: 20px 0;">
                    <button id="runTestBtn" style="background: #00875c; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">
                        Run Enhanced Test
                    </button>
                </div>
                
                <div id="testResults" style="display: none;">
                    <h3>Test Results</h3>
                    <div id="testOutput" style="background: #f5f5f5; padding: 15px; border-radius: 5px; font-family: monospace; white-space: pre-wrap;"></div>
                </div>
                
                <div style="margin-top: 20px;">
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" style="background: #666; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">
                        Close
                    </button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(demoModal);

    // Xử lý sự kiện test
    document.getElementById('runTestBtn').addEventListener('click', async () => {
        const btn = document.getElementById('runTestBtn');
        const results = document.getElementById('testResults');
        const output = document.getElementById('testOutput');

        btn.textContent = 'Running Test...';
        btn.disabled = true;
        output.textContent = 'Starting enhanced image suggestion test...\n';

        try {
            const testResult = await testEnhancedImageSuggestion();

            let outputText = '=== Enhanced Image Suggestion Test Results ===\n\n';

            outputText += `Found ${testResult.positions.length} image positions\n`;
            outputText += `Generated ${testResult.prompts.length} enhanced prompts\n\n`;

            outputText += '=== Statistics ===\n';
            outputText += `Styles: ${testResult.statistics.styles}\n`;
            outputText += `Content Types: ${testResult.statistics.contentTypes}\n`;
            outputText += `Enhanced Prompts: ${testResult.statistics.enhancedCount}\n`;
            outputText += `Fallback Prompts: ${testResult.statistics.fallbackCount}\n\n`;

            outputText += '=== Detailed Results ===\n';
            testResult.prompts.forEach((prompt, index) => {
                outputText += `Prompt ${index + 1}:\n`;
                outputText += `  Style: ${prompt.suggestedStyle}\n`;
                outputText += `  Content Type: ${prompt.contentType}\n`;
                outputText += `  AI Score: ${prompt.aiScore}\n`;
                outputText += `  Enhanced: ${prompt.enhanced}\n`;
                outputText += `  Fallback: ${prompt.fallback}\n`;
                outputText += `  Prompt: ${prompt.prompt}\n\n`;
            });

            output.textContent = outputText;
            results.style.display = 'block';

        } catch (error) {
            output.textContent += `Error: ${error.message}\n`;
            results.style.display = 'block';
        }

        btn.textContent = 'Run Enhanced Test';
        btn.disabled = false;
    });
}

// Function để lấy post ID hiện tại
function getCurrentPostId() {
    // Thử lấy từ URL trước
    const urlParams = new URLSearchParams(window.location.search);
    const postId = urlParams.get('post');

    if (postId) {
        return parseInt(postId);
    }

    // Thử lấy từ WordPress global
    if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
        try {
            return wp.data.select('core/editor').getCurrentPostId();
        } catch (e) {
            console.log('Could not get post ID from WordPress data');
        }
    }

    // Thử lấy từ URL path
    const pathMatch = window.location.pathname.match(/post\.php\?post=(\d+)/);
    if (pathMatch) {
        return parseInt(pathMatch[1]);
    }

    // Thử lấy từ hidden input
    const postIdInput = document.querySelector('input[name="post_ID"]');
    if (postIdInput && postIdInput.value) {
        return parseInt(postIdInput.value);
    }

    return null;
}

// Function để save draft và lấy post ID
async function saveDraftAndGetId() {
    try {
        const title = getPostTitle();
        const content = getEditorContent();

        if (!title || !content) {
            throw new Error('Title and content are required to save draft');
        }

        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'aiautotool_save_draft',
                security: aiautotool_js_setting.security,
                title: title,
                content: content
            })
        });

        const data = await response.json();

        if (data.success && data.data.post_id) {
            return data.data.post_id;
        } else {
            throw new Error(data.data || 'Failed to save draft');
        }
    } catch (error) {
        console.error('Error saving draft:', error);
        throw error;
    }
}

// Function để set featured image
async function setFeaturedImage(imageUrl, postId) {
    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'aiautotool_set_featured_image',
                security: aiautotool_js_setting.security,
                image_url: imageUrl,
                post_id: postId
            })
        });

        const data = await response.json();

        if (data.success) {
            return data.data;
        } else {
            throw new Error(data.data || 'Failed to set featured image');
        }
    } catch (error) {
        console.error('Error setting featured image:', error);
        throw error;
    }
}

// Function để xử lý set featured image
async function handleSetFeaturedImage(imageUrl) {
    try {
        let postId = getCurrentPostId();

        // Nếu chưa có post ID, save draft trước
        if (!postId) {
            showSuccess('Saving draft first...');
            postId = await saveDraftAndGetId();
            showSuccess('Draft saved successfully!');
        }

        // Set featured image
        showSuccess('Setting featured image...');
        const result = await setFeaturedImage(imageUrl, postId);

        if (result.success) {
            showSuccess('Featured image set successfully!');
            // Reload page để hiển thị featured image
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showError('Failed to set featured image: ' + result.message);
        }

    } catch (error) {
        showError('Error: ' + error.message);
    }
}

// Function để xử lý set featured image từ modal
async function handleSetFeaturedImageFromModal() {
    const imageEl = document.getElementById('modalGeneratedImage');
    if (!imageEl || !imageEl.src) {
        showError('No image to set as featured image.');
        return;
    }

    try {
        await handleSetFeaturedImage(imageEl.src);
    } catch (error) {
        showError('Error setting featured image: ' + error.message);
    }
}

// Function để hiển thị modal cho AI Post Tools
function showAIPostToolModal(action, toolName) {
    // Remove existing modal if any
    const existingModal = document.querySelector('.aiautotool-ai-post-modal');
    if (existingModal) {
        existingModal.remove();
    }

    // Create modal container
    const modal = document.createElement('div');
    modal.className = 'aiautotool-ai-post-modal';
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999999;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    `;

    // Create modal content
    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
        background: white;
        border-radius: 12px;
        padding: 30px;
        max-width: 500px;
        width: 90%;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
        position: relative;
    `;

    // Create header
    const header = document.createElement('div');
    header.style.cssText = `
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f3f4f6;
    `;

    const title = document.createElement('h3');
    title.textContent = toolName;
    title.style.cssText = `
        margin: 0;
        color: #1f2937;
        font-size: 20px;
        font-weight: 600;
    `;

    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '&times;';
    closeBtn.style.cssText = `
        background: none;
        border: none;
        font-size: 24px;
        cursor: pointer;
        color: #6b7280;
        padding: 0;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: all 0.2s;
    `;

    closeBtn.addEventListener('mouseenter', () => {
        closeBtn.style.background = '#f3f4f6';
        closeBtn.style.color = '#374151';
    });

    closeBtn.addEventListener('mouseleave', () => {
        closeBtn.style.background = 'none';
        closeBtn.style.color = '#6b7280';
    });

    closeBtn.addEventListener('click', () => {
        modal.remove();
    });

    header.appendChild(title);
    header.appendChild(closeBtn);

    // Create form
    const form = document.createElement('form');
    form.style.cssText = 'margin-bottom: 20px;';

    const label = document.createElement('label');
    label.textContent = 'Enter topic or keyword:';
    label.style.cssText = `
        display: block;
        margin-bottom: 8px;
        color: #374151;
        font-weight: 500;
        font-size: 14px;
    `;

    const input = document.createElement('input');
    input.type = 'text';
    input.placeholder = 'e.g., Digital Marketing, WordPress SEO, Content Strategy...';
    input.style.cssText = `
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        font-size: 16px;
        transition: border-color 0.2s;
        box-sizing: border-box;
    `;

    input.addEventListener('focus', () => {
        input.style.borderColor = '#3b82f6';
    });

    input.addEventListener('blur', () => {
        input.style.borderColor = '#e5e7eb';
    });

    const submitBtn = document.createElement('button');
    submitBtn.type = 'submit';
    submitBtn.textContent = `Generate ${toolName}`;
    submitBtn.style.cssText = `
        width: 100%;
        padding: 12px 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        margin-top: 16px;
    `;

    submitBtn.addEventListener('mouseenter', () => {
        submitBtn.style.transform = 'translateY(-2px)';
        submitBtn.style.boxShadow = '0 10px 20px rgba(0, 0, 0, 0.2)';
    });

    submitBtn.addEventListener('mouseleave', () => {
        submitBtn.style.transform = 'translateY(0)';
        submitBtn.style.boxShadow = 'none';
    });

    // Handle form submission
    form.addEventListener('submit', (e) => {
        e.preventDefault();

        const topic = input.value.trim();

        if (!topic) {
            showError('Please enter a topic or keyword.');
            input.focus();
            return;
        }

        // Close modal
        modal.remove();

        // Create temporary input element to use existing logic
        const tempInput = document.createElement('input');
        tempInput.id = 'temp-ai-post-input';
        tempInput.value = topic;
        tempInput.style.display = 'none';

        // Create temporary button element
        const tempButton = document.createElement('button');
        tempButton.id = 'temp-ai-post-button';
        tempButton.textContent = 'Processing...';
        tempButton.style.display = 'none';

        // Add to DOM temporarily
        document.body.appendChild(tempInput);
        document.body.appendChild(tempButton);

        // Process the tool request using existing function
        if (typeof window.processToolRequest === 'function') {
            window.processToolRequest(action, 'temp-ai-post-input');
        } else {
            showError('AI service not available. Please try again later.');
        }

        // Clean up after a delay
        setTimeout(() => {
            if (tempInput.parentNode) tempInput.parentNode.removeChild(tempInput);
            if (tempButton.parentNode) tempButton.parentNode.removeChild(tempButton);
        }, 1000);
    });

    form.appendChild(label);
    form.appendChild(input);
    form.appendChild(submitBtn);

    // Create description
    const description = document.createElement('div');
    description.style.cssText = `
        background: #f8fafc;
        padding: 16px;
        border-radius: 8px;
        border-left: 4px solid #3b82f6;
        font-size: 14px;
        color: #64748b;
        line-height: 1.5;
    `;

    let descText = '';
    switch (action) {
        case 'Outline':
            descText = 'AI will create a comprehensive, SEO-friendly outline with main topics and subtopics organized in a logical structure.';
            break;
        case 'Introduction':
            descText = 'AI will generate an engaging introduction that hooks readers and clearly states the article\'s purpose and scope.';
            break;
        case 'Conclusion':
            descText = 'AI will create a compelling conclusion that summarizes key points and provides a memorable ending.';
            break;
        case 'FAQ':
            descText = 'AI will generate relevant questions and detailed answers covering common concerns and user needs.';
            break;
        case 'TitleSuggestion':
            descText = 'AI will generate 5-8 engaging and SEO-friendly title suggestions based on your topic. These titles will be optimized for search engines and user engagement.';
            break;
        case 'MetaDescription':
            descText = 'AI will create compelling meta descriptions optimized for SEO, keeping them within the ideal 150-160 character limit for search engine snippets.';
            break;
        case 'SocialMedia':
            descText = 'AI will generate engaging social media posts optimized for different platforms including Facebook, Twitter, LinkedIn, and Instagram with relevant hashtags.';
            break;
        case 'ContentSummary':
            descText = 'AI will create concise summaries of your content, highlighting key points and takeaways in an easy-to-understand format.';
            break;
        case 'KeywordResearch':
            descText = 'AI will research and suggest relevant keywords, including search volume estimates, difficulty levels, and content ideas based on keyword analysis.';
            break;
        case 'ContentRewrite':
            descText = 'AI will rewrite your content in different styles (professional, casual, creative) while maintaining the same core message and information.';
            break;
        case 'BlogPostIdeas':
            descText = 'AI will generate creative blog post ideas with different content types, angles, and perspectives to expand your content strategy.';
            break;
        case 'ContentCalendar':
            descText = 'AI will create a strategic content calendar planning content for the next 30 days across different platforms and content types.';
            break;
    }

    description.textContent = descText;

    // Assemble modal
    modalContent.appendChild(header);
    modalContent.appendChild(form);
    modalContent.appendChild(description);
    modal.appendChild(modalContent);

    // Add to page
    document.body.appendChild(modal);

    // Focus input
    setTimeout(() => {
        input.focus();
    }, 100);

    // Close on outside click
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });

    // Close on Escape key
    document.addEventListener('keydown', function closeOnEscape(e) {
        if (e.key === 'Escape') {
            modal.remove();
            document.removeEventListener('keydown', closeOnEscape);
        }
    });
}

// Function để xử lý processToolRequest với input trực tiếp
function processToolRequest(type, inputText) {
    if (!inputText.trim()) {
        showError('Please enter a topic or keyword.');
        return;
    }

    if (!check_aipost_premium()) {
        showError('AI Post Limit Quota. Please Upgrade Pro.');
        return;
    }

    // Get language settings
    const post_language = get_lang();
    let resolvedLang = '';
    if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
        resolvedLang = languageCodes[post_language];
    } else if (typeof langcheck !== 'undefined') {
        resolvedLang = langcheck;
    } else {
        resolvedLang = post_language;
    }

    // Open the AI tool sidebar
    open_box_aiautotool();

    // Close modal if open
    const modalClose = document.querySelector('.aiautotool-modal-close');
    if (modalClose) {
        modalClose.click();
    }

    const divId = "outbard";
    let text = '';

    // Enhanced prompts for better AI responses
    switch (type) {
        case "Outline":
            text = `Create a comprehensive and well-structured outline for an article about "${inputText}". 
            
Requirements:
- Include main topics and subtopics organized in a hierarchical numbered list format
- Make it SEO-friendly and engaging for readers
- Include 5-8 main sections with relevant subsections
- Focus on user intent and search optimization
- Structure should be logical and flow naturally

Format the response with clear headings and subheadings.`;
            break;

        case "Introduction":
            text = `Write an engaging and compelling introduction for an article titled "${inputText}".
            
Requirements:
- The introduction should be 50-100 words
- Hook the reader's attention with an interesting opening
- Clearly state the topic and its importance
- Provide a preview of what the article will cover
- Make it professional, engaging, and SEO-friendly
- Include a clear thesis statement or main argument`;
            break;

        case "Conclusion":
            text = `Write a strong and compelling conclusion for an article about "${inputText}".
            
Requirements:
- Summarize the key points discussed in the article
- Reinforce the main message and takeaways
- Provide a memorable ending that encourages reader engagement
- Include a call-to-action if appropriate
- Make it professional and impactful
- Tie back to the introduction and main thesis`;
            break;

        case "FAQ":
            text = `Create a comprehensive FAQ section for "${inputText}".
            
Requirements:
- Generate 5-8 frequently asked questions and detailed answers
- Make the questions relevant, specific, and user-focused
- Provide informative and easy-to-understand answers
- Format it clearly with Q&A structure
- Cover common concerns and pain points
- Include both basic and advanced questions
- Make answers actionable and helpful

Format as:
Q: [Question]
A: [Detailed answer]

Q: [Next question]
A: [Next answer]`;
            break;

        case "TitleSuggestion":
            text = `Generate 5-8 engaging and SEO-friendly title suggestions for an article about "${inputText}".
            
Requirements:
- Create titles that are compelling and click-worthy
- Optimize for search engines with relevant keywords
- Include different title formats (question, how-to, listicle, etc.)
- Make titles specific and benefit-focused
- Keep titles between 50-60 characters for optimal SEO
- Use power words that drive engagement
- Ensure titles accurately represent the content

Format the response as a numbered list with each title on a new line.`;
            break;

        case "MetaDescription":
            text = `Create 3-5 compelling meta descriptions for an article about "${inputText}".
            
Requirements:
- Keep each description between 150-160 characters for optimal SEO
- Include primary and secondary keywords naturally
- Make descriptions compelling and click-worthy
- Include a clear call-to-action
- Optimize for search engine snippets
- Use power words that drive engagement
- Ensure descriptions accurately represent the content

Format as a numbered list with each meta description on a new line.`;
            break;

        case "SocialMedia":
            text = `Generate engaging social media posts for "${inputText}" across different platforms.
            
Requirements:
- Create posts for Facebook, Twitter, LinkedIn, and Instagram
- Include relevant hashtags for each platform
- Make content engaging and shareable
- Include call-to-actions appropriate for each platform
- Optimize character count for each platform
- Use emojis and formatting to increase engagement
- Include platform-specific best practices

Format as:
Facebook: [Post content with hashtags]
Twitter: [Post content with hashtags]
LinkedIn: [Professional post content]
Instagram: [Visual-focused post with hashtags]`;
            break;

        case "ContentSummary":
            text = `Create a comprehensive summary of content about "${inputText}".
            
Requirements:
- Summarize the main points in 3-5 bullet points
- Include key takeaways and insights
- Make it easy to understand for different audiences
- Highlight the most important information
- Use clear and concise language
- Include actionable insights if applicable
- Keep summary under 200 words

Format as a structured summary with bullet points.`;
            break;

        case "KeywordResearch":
            text = `Research and suggest relevant keywords for "${inputText}".
            
Requirements:
- Generate 10-15 primary and long-tail keywords
- Include search volume estimates (high/medium/low)
- Suggest related keyword clusters
- Include keyword difficulty assessment
- Provide keyword intent (informational, navigational, transactional)
- Suggest content ideas based on keywords
- Include competitive analysis insights

Format as a structured keyword research report.`;
            break;

        case "ContentRewrite":
            text = `Rewrite content about "${inputText}" in different writing styles.
            
Requirements:
- Create 3 different versions: professional, casual, and creative
- Maintain the same core message and information
- Adapt tone and style for different audiences
- Include SEO optimization for each version
- Make each version engaging and readable
- Vary sentence structure and vocabulary
- Ensure consistency in accuracy and facts

Format as:
Professional Version: [Content]
Casual Version: [Content]
Creative Version: [Content]`;
            break;

        case "BlogPostIdeas":
            text = `Generate 10-15 blog post ideas related to "${inputText}".
            
Requirements:
- Include different content types (how-to, listicle, case study, etc.)
- Make ideas specific and actionable
- Include target audience for each idea
- Suggest content angles and perspectives
- Include potential keywords for each idea
- Make ideas engaging and shareable
- Consider seasonal and trending topics

Format as a numbered list with brief descriptions.`;
            break;

        case "ContentCalendar":
            text = `Create a content calendar strategy for "${inputText}".
            
Requirements:
- Plan content for the next 30 days
- Include different content types and formats
- Suggest posting frequency and timing
- Include content themes and topics
- Plan for different platforms (blog, social media, email)
- Include content goals and KPIs
- Consider seasonal events and trends

Format as a structured content calendar with dates, topics, and platforms.`;
            break;

        default:
            console.error("Unknown type: " + type);
            showError('Unknown tool type. Please try again.');
            return;
    }

    // Show loading message
    showSuccess('Generating content with AI... Please wait.');

    // Send request to AI server
    // Use window.sendbardToServer if available, otherwise use global sendbardToServer
    var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : (typeof sendbardToServer !== 'undefined' ? sendbardToServer : null);

    if (!sendFn) {
        console.error('sendbardToServer function not found');
        showError('AI function not available. Please refresh the page.');
        return;
    }

    sendFn(text, divId, 'writemore', resolvedLang)
        .then(() => {
            showSuccess('Content generated successfully!');
            // Auto-scroll to results
            setTimeout(() => {
                const outbardElement = document.getElementById('outbard');
                if (outbardElement) {
                    outbardElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            }, 500);
        })
        .catch((error) => {
            // Error message is already shown by sendbardToServer (Swal/alert)
            console.error('Error processing tool request:', error);
            // Don't show error again as it's already displayed by sendbardToServer
        });
}

// Function để hiển thị modal cho Title Suggestion
function showTitleSuggestionModal() {
    // Remove existing modal if any
    const existingModal = document.querySelector('.aiautotool-title-suggestion-modal');
    if (existingModal) {
        existingModal.remove();
    }

    // Create modal container
    const modal = document.createElement('div');
    modal.className = 'aiautotool-title-suggestion-modal';
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999999;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    `;

    // Create modal content
    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
        background: white;
        border-radius: 12px;
        padding: 30px;
        max-width: 500px;
        width: 90%;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
        position: relative;
    `;

    // Create header
    const header = document.createElement('div');
    header.style.cssText = `
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f3f4f6;
    `;

    const title = document.createElement('h3');
    title.textContent = 'Suggest Title';
    title.style.cssText = `
        margin: 0;
        color: #1f2937;
        font-size: 20px;
        font-weight: 600;
    `;

    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '&times;';
    closeBtn.style.cssText = `
        background: none;
        border: none;
        font-size: 24px;
        cursor: pointer;
        color: #6b7280;
        padding: 0;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: all 0.2s;
    `;

    closeBtn.addEventListener('mouseenter', () => {
        closeBtn.style.background = '#f3f4f6';
        closeBtn.style.color = '#374151';
    });

    closeBtn.addEventListener('mouseleave', () => {
        closeBtn.style.background = 'none';
        closeBtn.style.color = '#6b7280';
    });

    closeBtn.addEventListener('click', () => {
        modal.remove();
    });

    header.appendChild(title);
    header.appendChild(closeBtn);

    // Create form
    const form = document.createElement('form');
    form.style.cssText = 'margin-bottom: 20px;';

    const label = document.createElement('label');
    label.textContent = 'Enter topic or keyword for title suggestions:';
    label.style.cssText = `
        display: block;
        margin-bottom: 8px;
        color: #374151;
        font-weight: 500;
        font-size: 14px;
    `;

    const input = document.createElement('input');
    input.type = 'text';
    input.placeholder = 'e.g., Digital Marketing, WordPress SEO, Content Strategy...';
    input.style.cssText = `
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        font-size: 16px;
        transition: border-color 0.2s;
        box-sizing: border-box;
    `;

    input.addEventListener('focus', () => {
        input.style.borderColor = '#3b82f6';
    });

    input.addEventListener('blur', () => {
        input.style.borderColor = '#e5e7eb';
    });

    const submitBtn = document.createElement('button');
    submitBtn.type = 'submit';
    submitBtn.textContent = 'Generate Title Suggestions';
    submitBtn.style.cssText = `
        width: 100%;
        padding: 12px 20px;
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        margin-top: 16px;
    `;

    submitBtn.addEventListener('mouseenter', () => {
        submitBtn.style.transform = 'translateY(-2px)';
        submitBtn.style.boxShadow = '0 10px 20px rgba(0, 0, 0, 0.2)';
    });

    submitBtn.addEventListener('mouseleave', () => {
        submitBtn.style.transform = 'translateY(0)';
        submitBtn.style.boxShadow = 'none';
    });

    // Handle form submission
    form.addEventListener('submit', (e) => {
        e.preventDefault();

        const topic = input.value.trim();

        if (!topic) {
            showError('Please enter a topic or keyword.');
            input.focus();
            return;
        }

        // Close modal
        modal.remove();

        // Create temporary input element to use existing logic
        const tempInput = document.createElement('input');
        tempInput.id = 'temp-title-suggestion-input';
        tempInput.value = topic;
        tempInput.style.display = 'none';

        // Create temporary button element
        const tempButton = document.createElement('button');
        tempButton.id = 'temp-title-suggestion-button';
        tempButton.textContent = 'Processing...';
        tempButton.style.display = 'none';

        // Add to DOM temporarily
        document.body.appendChild(tempInput);
        document.body.appendChild(tempButton);

        // Process the title suggestion request using existing function
        if (typeof window.processToolRequest === 'function') {
            // Use a special type for title suggestions
            window.processToolRequest('TitleSuggestion', 'temp-title-suggestion-input');
        } else {
            showError('AI service not available. Please try again later.');
        }

        // Clean up after a delay
        setTimeout(() => {
            if (tempInput.parentNode) tempInput.parentNode.removeChild(tempInput);
            if (tempButton.parentNode) tempButton.parentNode.removeChild(tempButton);
        }, 1000);
    });

    form.appendChild(label);
    form.appendChild(input);
    form.appendChild(submitBtn);

    // Create description
    const description = document.createElement('div');
    description.style.cssText = `
        background: #f0fdf4;
        padding: 16px;
        border-radius: 8px;
        border-left: 4px solid #10b981;
        font-size: 14px;
        color: #065f46;
        line-height: 1.5;
    `;

    description.textContent = 'AI will generate multiple engaging and SEO-friendly title suggestions based on your topic. These titles will be optimized for search engines and user engagement.';

    // Assemble modal
    modalContent.appendChild(header);
    modalContent.appendChild(form);
    modalContent.appendChild(description);
    modal.appendChild(modalContent);

    // Add to page
    document.body.appendChild(modal);

    // Focus input
    setTimeout(() => {
        input.focus();
    }, 100);

    // Close on outside click
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });

    // Close on Escape key
    document.addEventListener('keydown', function closeOnEscape(e) {
        if (e.key === 'Escape') {
            modal.remove();
            document.removeEventListener('keydown', closeOnEscape);
        }
    });
}

function aiautotoolResolveAiRoute(model) {
    const route = {
        provider_id: '',
        model: model || ''
    };

    if (route.model === 'auto' || route.model === 'provider-default' || route.model === 'gemini' || route.model === 'chatgpt') {
        route.model = '';
    }

    if (route.model.indexOf('::') !== -1) {
        const parts = route.model.split('::');
        route.provider_id = parts.shift() || '';
        route.model = parts.join('::') || '';
    }

    return route;
}

function aiautotoolAppendProviderModelOptions(select, includeAuto = true) {
    const settings = window.aiautotool_js_setting || {};
    const aipostSettings = window.aipost || {};
    const providers = settings.ai_providers || aipostSettings.ai_providers || {};
    const activeProvider = settings.active_ai_provider || aipostSettings.active_ai_provider || '';
    const activeModel = settings.active_ai_model || aipostSettings.active_ai_model || '';
    let added = 0;

    select.innerHTML = '';

    if (includeAuto) {
        const autoOption = document.createElement('option');
        autoOption.value = '';
        autoOption.textContent = 'Auto - use AI Provider settings';
        select.appendChild(autoOption);
    }

    Object.keys(providers).forEach((providerId) => {
        const provider = providers[providerId] || {};
        const models = provider.models || {};
        if (!provider.configured || !Object.keys(models).length) {
            return;
        }

        Object.keys(models).forEach((modelId) => {
            const option = document.createElement('option');
            option.value = providerId + '::' + modelId;
            option.textContent = (provider.name || providerId) + ' - ' + (models[modelId] || modelId);
            option.selected = !includeAuto && providerId === activeProvider && modelId === activeModel;
            select.appendChild(option);
            added += 1;
        });
    });

    if (!added && !includeAuto) {
        const emptyOption = document.createElement('option');
        emptyOption.value = '';
        emptyOption.textContent = 'No configured AI Provider. Add API key first.';
        select.appendChild(emptyOption);
    }
}

// Function để hiển thị modal cho Custom Prompt Write
function showCustomPromptModal() {
    // Remove existing modal if any
    const existingModal = document.querySelector('.aiautotool-custom-prompt-modal');
    if (existingModal) {
        existingModal.remove();
    }

    // Create modal container
    const modal = document.createElement('div');
    modal.className = 'aiautotool-custom-prompt-modal';
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999999;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    `;

    // Create modal content
    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
        background: white;
        border-radius: 12px;
        padding: 30px;
        max-width: 600px;
        width: 90%;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
        position: relative;
        max-height: 90vh;
        overflow-y: auto;
    `;

    // Create header
    const header = document.createElement('div');
    header.style.cssText = `
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f3f4f6;
    `;

    const title = document.createElement('h3');
    title.textContent = 'Write with Custom Prompt';
    title.style.cssText = `
        margin: 0;
        color: #1f2937;
        font-size: 20px;
        font-weight: 600;
    `;

    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '&times;';
    closeBtn.style.cssText = `
        background: none;
        border: none;
        font-size: 24px;
        cursor: pointer;
        color: #6b7280;
        padding: 0;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: all 0.2s;
    `;

    closeBtn.addEventListener('mouseenter', () => {
        closeBtn.style.background = '#f3f4f6';
        closeBtn.style.color = '#374151';
    });

    closeBtn.addEventListener('mouseleave', () => {
        closeBtn.style.background = 'none';
        closeBtn.style.color = '#6b7280';
    });

    closeBtn.addEventListener('click', () => {
        modal.remove();
    });

    header.appendChild(title);
    header.appendChild(closeBtn);

    // Create form
    const form = document.createElement('form');
    form.style.cssText = 'margin-bottom: 20px;';

    // AI Selection
    const aiLabel = document.createElement('label');
    aiLabel.textContent = 'Select AI Provider / Model:';
    aiLabel.style.cssText = `
        display: block;
        margin-bottom: 8px;
        color: #374151;
        font-weight: 500;
        font-size: 14px;
    `;

    const aiSelect = document.createElement('select');
    aiSelect.id = 'custom-prompt-ai-select';
    aiSelect.style.cssText = `
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        font-size: 16px;
        transition: border-color 0.2s;
        box-sizing: border-box;
        margin-bottom: 20px;
        background: white;
        cursor: pointer;
    `;

    aiautotoolAppendProviderModelOptions(aiSelect, true);

    aiSelect.addEventListener('focus', () => {
        aiSelect.style.borderColor = '#3b82f6';
    });

    aiSelect.addEventListener('blur', () => {
        aiSelect.style.borderColor = '#e5e7eb';
    });

    // Prompt input label
    const promptLabel = document.createElement('label');
    promptLabel.textContent = 'Enter your custom prompt:';
    promptLabel.style.cssText = `
        display: block;
        margin-bottom: 8px;
        color: #374151;
        font-weight: 500;
        font-size: 14px;
    `;

    // Prompt textarea
    const textarea = document.createElement('textarea');
    textarea.id = 'custom-prompt-textarea';
    textarea.placeholder = 'Enter your custom prompt here...\n\nExample: Write a comprehensive guide about WordPress SEO optimization with practical tips and examples.';
    textarea.style.cssText = `
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        font-size: 16px;
        transition: border-color 0.2s;
        box-sizing: border-box;
        min-height: 150px;
        resize: vertical;
        font-family: inherit;
    `;

    textarea.addEventListener('focus', () => {
        textarea.style.borderColor = '#3b82f6';
    });

    textarea.addEventListener('blur', () => {
        textarea.style.borderColor = '#e5e7eb';
    });

    // Submit button
    const submitBtn = document.createElement('button');
    submitBtn.type = 'submit';
    submitBtn.textContent = 'Generate Content';
    submitBtn.style.cssText = `
        width: 100%;
        padding: 12px 20px;
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        margin-top: 16px;
    `;

    submitBtn.addEventListener('mouseenter', () => {
        submitBtn.style.transform = 'translateY(-2px)';
        submitBtn.style.boxShadow = '0 10px 20px rgba(59, 130, 246, 0.3)';
    });

    submitBtn.addEventListener('mouseleave', () => {
        submitBtn.style.transform = 'translateY(0)';
        submitBtn.style.boxShadow = 'none';
    });

    // Handle form submission
    form.addEventListener('submit', (e) => {
        e.preventDefault();

        const customPrompt = textarea.value.trim();
        const selectedAI = aiSelect.value || '';

        if (!customPrompt) {
            showError('Please enter a custom prompt.');
            textarea.focus();
            return;
        }

        // Check if title is filled
        var titleValue = get_title().value;
        if (!titleValue.trim()) {
            showError('Please fill in the title first.');
            modal.remove();
            return;
        }

        // Close modal
        modal.remove();

        // Open AI content box
        open_box_aiautotool();
        openTab('aiContentTab');

        // Get language
        var divId = "outbard";
        var post_language = jQuery('#post_language').val();
        if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
            window.langcheck = languageCodes[post_language];
        }

        // Use custom prompt directly (don't use aiautotool_fix_question as we want the exact custom prompt)
        var prompt_article = customPrompt;

        // If title is available, optionally include it in the prompt
        if (titleValue.trim()) {
            prompt_article = `Title: ${titleValue}\n\n${customPrompt}`;
        }

        // Call AI with custom prompt
        var sendFn = (typeof window.sendbardToServer !== 'undefined') ? window.sendbardToServer : sendbardToServer;
        if (sendFn) {
            submitBtn.disabled = true;
            submitBtn.textContent = 'Generating...';

            sendFn(prompt_article, divId, 'writefull', window.langcheck, selectedAI)
                .catch((error) => {
                    console.error('Error generating content with custom prompt:', error);
                    submitBtn.disabled = false;
                    submitBtn.textContent = 'Generate Content';
                });
        } else {
            showError('AI service not available. Please try again later.');
        }
    });

    form.appendChild(aiLabel);
    form.appendChild(aiSelect);
    form.appendChild(promptLabel);
    form.appendChild(textarea);
    form.appendChild(submitBtn);

    // Create description
    const description = document.createElement('div');
    description.style.cssText = `
        background: #eff6ff;
        padding: 16px;
        border-radius: 8px;
        border-left: 4px solid #3b82f6;
        font-size: 14px;
        color: #1e40af;
        line-height: 1.5;
    `;

    description.textContent = 'Enter your custom prompt to generate content. The AI will use your exact prompt to create the content. You can include specific instructions, style preferences, or any requirements.';

    // Assemble modal
    modalContent.appendChild(header);
    modalContent.appendChild(form);
    modalContent.appendChild(description);
    modal.appendChild(modalContent);

    // Add to page
    document.body.appendChild(modal);

    // Focus textarea
    setTimeout(() => {
        textarea.focus();
    }, 100);

    // Close on outside click
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });

    // Close on Escape key
    document.addEventListener('keydown', function closeOnEscape(e) {
        if (e.key === 'Escape') {
            modal.remove();
            document.removeEventListener('keydown', closeOnEscape);
        }
    });
}

// Function để xử lý Content Rewrite
function showContentRewriteModal() {
    // Remove existing modal if any
    const existingModal = document.querySelector('.aiautotool-content-rewrite-modal');
    if (existingModal) {
        existingModal.remove();
    }

    // Create modal container
    const modal = document.createElement('div');
    modal.className = 'aiautotool-content-rewrite-modal';
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999999;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    `;

    // Create modal content
    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
        background: white;
        border-radius: 12px;
        padding: 30px;
        max-width: 700px;
        width: 95%;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
        position: relative;
    `;

    // Create header
    const header = document.createElement('div');
    header.style.cssText = `
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f3f4f6;
    `;

    const title = document.createElement('h3');
    title.textContent = 'Content Rewrite';
    title.style.cssText = `
        margin: 0;
        color: #1f2937;
        font-size: 20px;
        font-weight: 600;
    `;

    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '&times;';
    closeBtn.style.cssText = `
        background: none;
        border: none;
        font-size: 24px;
        cursor: pointer;
        color: #6b7280;
        padding: 0;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: all 0.2s;
    `;

    closeBtn.addEventListener('mouseenter', () => {
        closeBtn.style.background = '#f3f4f6';
        closeBtn.style.color = '#374151';
    });

    closeBtn.addEventListener('mouseleave', () => {
        closeBtn.style.background = 'none';
        closeBtn.style.color = '#6b7280';
    });

    closeBtn.addEventListener('click', () => {
        modal.remove();
    });

    header.appendChild(title);
    header.appendChild(closeBtn);

    // Create form
    const form = document.createElement('form');
    form.style.cssText = 'margin-bottom: 20px;';

    // Content input section
    const contentLabel = document.createElement('label');
    contentLabel.textContent = 'Enter content to rewrite:';
    contentLabel.style.cssText = `
        display: block;
        margin-bottom: 8px;
        color: #374151;
        font-weight: 500;
        font-size: 14px;
    `;

    const contentTextarea = document.createElement('textarea');
    contentTextarea.placeholder = 'Paste your content here that you want to rewrite...';
    contentTextarea.style.cssText = `
        width: 100%;
        min-height: 200px;
        padding: 16px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        font-size: 16px;
        line-height: 1.6;
        font-family: inherit;
        resize: vertical;
        transition: border-color 0.2s;
        box-sizing: border-box;
    `;

    contentTextarea.addEventListener('focus', () => {
        contentTextarea.style.borderColor = '#8b5cf6';
    });

    contentTextarea.addEventListener('blur', () => {
        contentTextarea.style.borderColor = '#e5e7eb';
    });

    // Style selection
    const styleLabel = document.createElement('label');
    styleLabel.textContent = 'Select rewrite style:';
    styleLabel.style.cssText = `
        display: block;
        margin: 20px 0 8px 0;
        color: #374151;
        font-weight: 500;
        font-size: 14px;
    `;

    const styleSelect = document.createElement('select');
    styleSelect.style.cssText = `
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        font-size: 16px;
        background: white;
        cursor: pointer;
        transition: border-color 0.2s;
        box-sizing: border-box;
    `;

    const styleOptions = [
        { value: 'professional', text: 'Professional & Formal' },
        { value: 'casual', text: 'Casual & Conversational' },
        { value: 'creative', text: 'Creative & Engaging' },
        { value: 'academic', text: 'Academic & Scholarly' },
        { value: 'marketing', text: 'Marketing & Persuasive' },
        { value: 'technical', text: 'Technical & Detailed' }
    ];

    styleOptions.forEach(option => {
        const optionElement = document.createElement('option');
        optionElement.value = option.value;
        optionElement.textContent = option.text;
        styleSelect.appendChild(optionElement);
    });

    styleSelect.addEventListener('focus', () => {
        styleSelect.style.borderColor = '#8b5cf6';
    });

    styleSelect.addEventListener('blur', () => {
        styleSelect.style.borderColor = '#e5e7eb';
    });

    // Submit button
    const submitBtn = document.createElement('button');
    submitBtn.type = 'submit';
    submitBtn.textContent = 'Rewrite Content';
    submitBtn.style.cssText = `
        width: 100%;
        padding: 14px 20px;
        background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        margin-top: 20px;
    `;

    submitBtn.addEventListener('mouseenter', () => {
        submitBtn.style.transform = 'translateY(-2px)';
        submitBtn.style.boxShadow = '0 10px 20px rgba(0, 0, 0, 0.2)';
    });

    submitBtn.addEventListener('mouseleave', () => {
        submitBtn.style.transform = 'translateY(0)';
        submitBtn.style.boxShadow = 'none';
    });

    // Handle form submission
    form.addEventListener('submit', (e) => {
        e.preventDefault();

        const content = contentTextarea.value.trim();
        const style = styleSelect.value;

        if (!content) {
            showError('Please enter content to rewrite.');
            contentTextarea.focus();
            return;
        }

        if (content.length < 50) {
            showError('Content should be at least 50 characters long.');
            contentTextarea.focus();
            return;
        }

        // Close modal
        modal.remove();

        // Process the content rewrite request
        processContentRewrite(content, style);
    });

    form.appendChild(contentLabel);
    form.appendChild(contentTextarea);
    form.appendChild(styleLabel);
    form.appendChild(styleSelect);
    form.appendChild(submitBtn);

    // Create description
    const description = document.createElement('div');
    description.style.cssText = `
        background: #faf5ff;
        padding: 16px;
        border-radius: 8px;
        border-left: 4px solid #8b5cf6;
        font-size: 14px;
        color: #581c87;
        line-height: 1.5;
    `;

    description.innerHTML = `
        <strong>How it works:</strong><br>
        • Paste your content in the textarea above<br>
        • Select your preferred writing style<br>
        • AI will rewrite your content while maintaining the same message<br>
        • You'll get 3 different versions: Professional, Casual, and Creative
    `;

    // Assemble modal
    modalContent.appendChild(header);
    modalContent.appendChild(form);
    modalContent.appendChild(description);
    modal.appendChild(modalContent);

    // Add to page
    document.body.appendChild(modal);

    // Focus textarea
    setTimeout(() => {
        contentTextarea.focus();
    }, 100);

    // Close on outside click
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });

    // Close on Escape key
    document.addEventListener('keydown', function closeOnEscape(e) {
        if (e.key === 'Escape') {
            modal.remove();
            document.removeEventListener('keydown', closeOnEscape);
        }
    });
}

// Function để xử lý Content Rewrite
function processContentRewrite(content, style) {
    if (!content.trim()) {
        showError('Please enter content to rewrite.');
        return;
    }

    if (!check_aipost_premium()) {
        showError('AI Post Limit Quota. Please Upgrade Pro.');
        return;
    }

    // Get language settings
    const post_language = get_lang();
    let resolvedLang = '';
    if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(post_language)) {
        resolvedLang = languageCodes[post_language];
    } else if (typeof langcheck !== 'undefined') {
        resolvedLang = langcheck;
    } else {
        resolvedLang = post_language;
    }

    // Open the AI tool sidebar
    if (typeof open_box_aiautotool === 'function') {
        open_box_aiautotool();
    } else {
        console.warn('open_box_aiautotool function not found');
    }

    // Close modal if open
    const modalClose = document.querySelector('.aiautotool-modal-close');
    if (modalClose) {
        modalClose.click();
    }

    const divId = "outbard";

    // Create enhanced prompt for content rewrite
    const text = `Rewrite the following content in ${style} style while maintaining the same core message and information:

ORIGINAL CONTENT:
${content}

Requirements:
- Maintain the same key information and facts
- Adapt the tone and style to be ${style}
- Make the content engaging and readable
- Optimize for SEO if applicable
- Vary sentence structure and vocabulary
- Ensure consistency in accuracy
- Keep similar length or slightly longer

Please provide the rewritten version in ${style} style.`;

    // Show loading message
    showSuccess('Rewriting content with AI... Please wait.');

    // Send request to AI server
    if (typeof window.sendbardToServer === 'function') {
        console.log('sendbardToServer function found, calling API for content rewrite...');
        window.sendbardToServer(text, divId, 'writemore', resolvedLang)
            .then(() => {
                console.log('Content rewrite completed successfully');
                showSuccess('Content rewritten successfully!');
                // Auto-scroll to results
                setTimeout(() => {
                    const outbardElement = document.getElementById('outbard');
                    if (outbardElement) {
                        outbardElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                }, 500);
            })
            .catch((error) => {
                console.error('Error processing content rewrite:', error);
                showError('An error occurred while rewriting your content. Please try again.');
            });
    } else {
        console.error('sendbardToServer function not found');
        showError('AI service not available. Please try again later.');
    }
}

// Dynamic loader for Remote Rewrite module
(function () {
    if (typeof window.showRemoteRewriteModal !== 'undefined') return;
    function loadRemoteRewrite() {
        try {
            var scripts = document.getElementsByTagName('script');
            var base = '';
            for (var i = 0; i < scripts.length; i++) {
                var src = scripts[i].getAttribute('src') || '';
                if (src.indexOf('aipost.js') !== -1) {
                    base = src.replace(/aipost\.js(?:\?.*)?$/, '');
                    break;
                }
            }
            if (!base) return;
            var s = document.createElement('script');
            var version = 'v=' + Math.random().toString(36).substr(2, 8);
            s.src = base + 'remote_rewrite.js?' + version;
            s.async = true;
            s.onload = function () { try { console.log('Remote Rewrite module loaded'); } catch (e) { } };
            document.head.appendChild(s);
        } catch (e) { }
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', loadRemoteRewrite);
    } else {
        loadRemoteRewrite();
    }
})();

// Test function to verify JSON parsing improvements
function testJsonParsing() {
    console.log('Testing JSON parsing improvements...');

    // Test case 1: Valid JSON
    const validJson = '{"positions":[{"index":0,"paragraph":"test","score":80}]}';
    try {
        const parsed = JSON.parse(validJson);
        console.log('✅ Valid JSON parsed successfully:', parsed);
    } catch (e) {
        console.error('❌ Valid JSON parsing failed:', e);
    }

    // Test case 2: JSON with markdown code blocks
    const jsonWithMarkdown = '```json\n{"positions":[{"index":1,"paragraph":"test2","score":90}]}\n```';
    try {
        const cleaned = jsonWithMarkdown.replace(/```json\s*/g, '').replace(/```\s*$/g, '');
        const parsed = JSON.parse(cleaned);
        console.log('✅ JSON with markdown parsed successfully:', parsed);
    } catch (e) {
        console.error('❌ JSON with markdown parsing failed:', e);
    }

    // Test case 3: Malformed JSON with extra text
    const malformedJson = 'Here is the analysis: {"positions":[{"index":2,"paragraph":"test3","score":70}]} and some extra text';
    try {
        const jsonMatch = malformedJson.match(/\{[\s\S]*\}/);
        if (jsonMatch) {
            const parsed = JSON.parse(jsonMatch[0]);
            console.log('✅ Malformed JSON extracted successfully:', parsed);
        } else {
            console.error('❌ No JSON found in malformed response');
        }
    } catch (e) {
        console.error('❌ Malformed JSON extraction failed:', e);
    }

    // Test case 4: HTML-wrapped JSON
    const htmlWrappedJson = '<p>{"positions":[{"index":3,"paragraph":"test4","score":75}]}</p>';
    try {
        const cleaned = htmlWrappedJson.replace(/<[^>]*>/g, '');
        const parsed = JSON.parse(cleaned);
        console.log('✅ HTML-wrapped JSON parsed successfully:', parsed);
    } catch (e) {
        console.error('❌ HTML-wrapped JSON parsing failed:', e);
    }

    // Test case 5: Real-world scenario (exact format from error logs)
    const realWorldJson = '<p>{"positions":[{"index":0,"paragraph":"Gia Hưng – \"Gia\" là gia đình, \"Hưng\" là thịnh vượng. Ý nghĩa con giúp gia đình phát triển, sung túc.","score":85,"reason":"This paragraph offers a conceptual explanation of the name\'s meaning, making it suitable for an illustrative depiction of family prosperity and growth themes.","suggested_style":"illustration","content_type":"concept","visual_elements":"family icons, tree of growth, prosperous symbols"}]}</p>';
    try {
        const cleaned = realWorldJson.replace(/<[^>]*>/g, '');
        const parsed = JSON.parse(cleaned);
        console.log('✅ Real-world HTML-wrapped JSON parsed successfully:', parsed);
    } catch (e) {
        console.error('❌ Real-world HTML-wrapped JSON parsing failed:', e);
    }

    console.log('JSON parsing test completed.');
}

// Make test function available globally for debugging
window.testJsonParsing = testJsonParsing;

// Test function to check if sendbardToServerWithAnalysis is available
window.testArticleAnalysisFunction = function () {
    console.log('=== Testing Article Analysis Function ===');
    console.log('sendbardToServerWithAnalysis type:', typeof window.sendbardToServerWithAnalysis);
    console.log('sendbardToServerWithAnalysis:', window.sendbardToServerWithAnalysis);
    console.log('aiautotool_js_setting:', typeof aiautotool_js_setting !== 'undefined' ? aiautotool_js_setting : 'NOT DEFINED');
    console.log('ajax_url:', typeof aiautotool_js_setting !== 'undefined' ? aiautotool_js_setting.ajax_url : 'NOT DEFINED');
    return typeof window.sendbardToServerWithAnalysis === 'function';
};

/**
 * Write article with analysis using SSE streaming
 * @param {string} title - Article title
 * @param {string} divId - Target div ID to display content
 * @param {string} lang - Language code
 * @param {string} model - AI model to use
 * @param {string} originalPrompt - Original prompt template (optional)
 * @returns {Promise} Promise that resolves when article is complete
 */
window.sendbardToServerWithAnalysis = function (title, divId, lang, model = '', originalPrompt = '') {
    return new Promise((resolve, reject) => {
        if (!title || !title.trim()) {
            const errorMsg = 'Please provide a title for the article.';
            if (typeof showError === 'function') {
                showError(errorMsg);
            } else if (typeof Swal !== 'undefined' && Swal) {
                Swal.fire({
                    title: 'Error!',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonText: 'Close'
                });
            } else {
                alert(errorMsg);
            }
            reject(new Error(errorMsg));
            return;
        }

        // Hide info_content div when streaming starts
        const infoContentDiv = document.getElementById('info_content');
        if (infoContentDiv) {
            infoContentDiv.style.display = 'none';
        }

        // Show loading
        if (typeof showLoading === 'function') {
            showLoading('Starting article generation with analysis...');
        }

        // Clear target div and add analysis container + content container
        if (divId) {
            const targetDiv = document.getElementById(divId);
            if (targetDiv) {
                targetDiv.innerHTML = '<div id="article-analysis-container" style="padding: 0px; font-family: Arial, sans-serif; border-bottom: 2px solid #e0e0e0; margin-bottom: 20px;"></div>' +
                    '<div id="article-content-container" style="padding: 20px; font-family: Arial, sans-serif;"></div>';
            }
        }

        // Generate message ID
        const messageId = 'article_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);

        // Get article settings
        const articleSettings = getArticleSettings();
        const aiRoute = aiautotoolResolveAiRoute(model);

        // Prepare data
        const dataToSend = {
            title: title,
            lang: lang,
            provider_id: aiRoute.provider_id,
            model: aiRoute.model,
            message_id: messageId,
            original_prompt: originalPrompt,
            domain: (window.aiautotool_js_setting && window.aiautotool_js_setting.fsdata && window.aiautotool_js_setting.fsdata.domain) || '',
            info: (window.aiautotool_js_setting && window.aiautotool_js_setting.fsdata) || {},
            // Add article settings if available
            targetAudience: articleSettings ? articleSettings.targetAudience : '',
            tone: articleSettings ? articleSettings.tone : '',
            lengthType: articleSettings ? articleSettings.lengthType : '',
            competitors: articleSettings ? articleSettings.competitors : [],
            brandVoiceRules: articleSettings ? articleSettings.brandVoiceRules : '',
            autoInternalLinks: articleSettings ? (articleSettings.autoInternalLinks !== false) : true
        };

        // Create form data
        const formData = new FormData();
        formData.append('action', 'aiautotool_write_article_with_analysis');
        formData.append('data', JSON.stringify(dataToSend));
        formData.append('security', (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) ? aiautotool_js_setting.security : '');

        // Variables for tracking steps
        let currentStepElement = null;
        let currentStepNumber = 0;
        let articleContent = '';
        let receivedCompleteEvent = false;
        let receivedErrorEvent = false;
        let streamErrorMessage = '';
        let stepOutputs = {};

        console.log('Sending request to:', aiautotool_js_setting.ajax_url);
        console.log('Request data:', dataToSend);

        // Use fetch to POST and get streaming response
        fetch(aiautotool_js_setting.ajax_url, {
            method: 'POST',
            body: formData
        }).then(response => {
            console.log('Response status:', response.status);
            console.log('Response headers:', response.headers);

            if (!response.ok) {
                // Try to get error message from response
                return response.text().then(text => {
                    console.error('Error response body:', text);
                    throw new Error('Network response was not ok: ' + response.status + ' - ' + text.substring(0, 200));
                });
            }

            // Check if response is SSE
            const contentType = response.headers.get('content-type');
            console.log('Response content-type:', contentType);

            if (!contentType || !contentType.includes('text/event-stream')) {
                console.warn('Response is not SSE stream, content-type:', contentType);
                // Try to parse as JSON for error
                return response.text().then(text => {
                    console.log('Non-SSE response text:', text.substring(0, 500));
                    try {
                        const jsonData = JSON.parse(text);
                        if (jsonData.code && jsonData.code !== '200') {
                            throw new Error(jsonData.msg || 'Server error');
                        }
                        // If it's JSON but not error, might be a different format
                        throw new Error('Unexpected response format. Expected SSE stream.');
                    } catch (e) {
                        if (e.message && e.message.includes('Unexpected')) {
                            throw e;
                        }
                        // Not JSON, might be HTML error page
                        throw new Error('Server returned non-SSE response. Content-type: ' + contentType);
                    }
                });
            }

            // Process SSE stream
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';
            let currentEvent = null;
            let receivedCompleteEvent = false;
            let receivedErrorEvent = false;
            let streamErrorMessage = '';

            function processStream() {
                return reader.read().then(({ done, value }) => {
                    if (done) {
                        if (typeof hideLoading === 'function') {
                            hideLoading();
                        }

                        // Finalize article display
                        const finalContent = articleContent;

                        if (receivedErrorEvent) {
                            throw new Error(streamErrorMessage || 'AI Auto Writer failed before creating a complete article.');
                        }

                        if (!receivedCompleteEvent) {
                            throw new Error('AI Auto Writer stream ended before the article was complete. Nội dung mới viết được một phần, vui lòng chạy lại hoặc đổi provider.');
                        }

                        // Store in global variable for btnaddpost button
                        if (typeof window !== 'undefined' && finalContent) {
                            window.aiautotool_content = finalContent;
                        }
                        // Also set global variable if it exists
                        if (typeof aiautotool_content !== 'undefined' && finalContent) {
                            aiautotool_content = finalContent;
                        }

                        if (divId && finalContent) {
                            // Update only the content container, keep analysis container intact
                            const contentContainer = document.getElementById('article-content-container');
                            if (contentContainer) {
                                contentContainer.innerHTML = finalContent;

                                // Show Add Post button
                                const btnAddPost = document.querySelector('.btnaddpost');
                                if (btnAddPost) {
                                    btnAddPost.style.display = 'block';
                                    btnAddPost.style.marginTop = '15px';
                                    btnAddPost.style.marginBottom = '15px';
                                }

                                if (typeof scrollToBottom === 'function') {
                                    scrollToBottom();
                                }
                            } else {
                                // Fallback: if content container doesn't exist, update targetDiv
                                const targetDiv = document.getElementById(divId);
                                if (targetDiv) {
                                    // Check if analysis container exists, if not create both
                                    let analysisContainer = document.getElementById('article-analysis-container');
                                    if (!analysisContainer) {
                                        targetDiv.innerHTML = '<div id="article-analysis-container" style="padding: 0px; font-family: Arial, sans-serif; border-bottom: 2px solid #e0e0e0; margin-bottom: 20px;"></div>' +
                                            '<div id="article-content-container" style="padding: 0px; font-family: Arial, sans-serif;">' + finalContent + '</div>';
                                    } else {
                                        // Analysis container exists, just add content container
                                        const contentDiv = document.createElement('div');
                                        contentDiv.id = 'article-content-container';
                                        contentDiv.style.cssText = 'padding: 0px; font-family: Arial, sans-serif;';
                                        contentDiv.innerHTML = finalContent;
                                        targetDiv.appendChild(contentDiv);
                                    }

                                    // Show Add Post button
                                    const btnAddPost = document.querySelector('.btnaddpost');
                                    if (btnAddPost) {
                                        btnAddPost.style.display = 'block';
                                        btnAddPost.style.marginTop = '15px';
                                        btnAddPost.style.marginBottom = '15px';
                                    }

                                    if (typeof scrollToBottom === 'function') {
                                        scrollToBottom();
                                    }
                                }
                            }
                        }

                        resolve(finalContent);
                        return;
                    }

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');

                    // Keep the last incomplete line in buffer
                    buffer = lines.pop() || '';

                    lines.forEach(line => {
                        line = line.trim();

                        if (!line) {
                            // Empty line signals end of event
                            currentEvent = null;
                            return;
                        }

                        if (line.startsWith('event:')) {
                            currentEvent = line.substring(6).trim();
                            console.log('SSE Event:', currentEvent);
                        } else if (line.startsWith('data:')) {
                            try {
                                const jsonData = line.substring(5).trim();
                                if (!jsonData) {
                                    return; // Skip empty data
                                }

                                const data = JSON.parse(jsonData);
                                console.log('SSE Data received:', currentEvent, data);

                                // Check for error message even if event type is not set
                                if (data && data.message && (data.message.toLowerCase().includes('pro account') ||
                                    data.message.toLowerCase().includes('upgrade to pro') ||
                                    data.message.toLowerCase().includes('requires a pro'))) {
                                    // Force event type to 'error' if it's a pro account error
                                    if (!currentEvent || currentEvent === 'null' || currentEvent === 'undefined') {
                                        currentEvent = 'error';
                                        console.log('Detected Pro account error, setting eventType to error');
                                    }
                                }

                                // Handle SSE event
                                handleArticleSSEEvent(data, currentEvent, divId, {
                                    currentStepElement: () => currentStepElement,
                                    setCurrentStepElement: (el) => { currentStepElement = el; },
                                    currentStepNumber: () => currentStepNumber,
                                    setCurrentStepNumber: (num) => { currentStepNumber = num; },
                                    articleContent: () => articleContent,
                                    appendArticleContent: (text) => { articleContent += text; },
                                    setArticleContent: (content) => { articleContent = content; },
                                    stepOutputs: () => stepOutputs,
                                    setStepOutput: (step, output) => { stepOutputs[step] = output; }
                                });

                                // Update articleContent from complete event
                                if (currentEvent === 'complete' && data.content) {
                                    articleContent = data.content;
                                    console.log('Article content received, length:', articleContent.length);
                                }
                            } catch (e) {
                                console.error('Failed to parse SSE data:', e);
                                console.error('Line that failed:', line);
                                console.error('Current event:', currentEvent);
                            }
                        }
                    });

                    return processStream();
                });
            }

            processStream().catch(error => {
                console.error('Stream processing error:', error);
                if (typeof hideLoading === 'function') {
                    hideLoading();
                }

                const errorMsg = 'Error processing stream: ' + error.message;
                const contentContainer = document.getElementById('auto-writer-content-container');
                if (contentContainer) {
                    contentContainer.classList.remove('is-loading');
                    contentContainer.innerHTML = '<div class="aiautotool-agent-panel aiautotool-agent-error" style="margin-top:12px;"><div class="aiautotool-agent-panel-title">Chưa tạo được bài hoàn chỉnh</div><div class="aiautotool-agent-panel-text">' + escapeHtml(errorMsg) + '</div></div>';
                }
                const btnAddPost = document.querySelector('.btnaddpost');
                if (btnAddPost) {
                    btnAddPost.style.display = 'none';
                }
                if (typeof window !== 'undefined') {
                    window.aiautotool_content = '';
                }
                if (typeof aiautotool_content !== 'undefined') {
                    aiautotool_content = '';
                }
                if (typeof showError === 'function') {
                    showError(errorMsg);
                } else if (typeof Swal !== 'undefined' && Swal) {
                    Swal.fire({
                        title: 'Error!',
                        text: errorMsg,
                        icon: 'error',
                        confirmButtonText: 'Close'
                    });
                } else {
                    alert(errorMsg);
                }

                reject(error);
            });

        }).catch(error => {
            if (typeof hideLoading === 'function') {
                hideLoading();
            }

            const errorMsg = 'Connection error: ' + error.message;
            const contentContainer = document.getElementById('auto-writer-content-container');
            if (contentContainer) {
                contentContainer.classList.remove('is-loading');
                contentContainer.innerHTML = '<div class="aiautotool-agent-panel aiautotool-agent-error" style="margin-top:12px;"><div class="aiautotool-agent-panel-title">Kết nối bị ngắt</div><div class="aiautotool-agent-panel-text">' + escapeHtml(errorMsg) + '</div></div>';
            }
            const btnAddPost = document.querySelector('.btnaddpost');
            if (btnAddPost) {
                btnAddPost.style.display = 'none';
            }
            if (typeof window !== 'undefined') {
                window.aiautotool_content = '';
            }
            if (typeof aiautotool_content !== 'undefined') {
                aiautotool_content = '';
            }
            if (typeof showError === 'function') {
                showError(errorMsg);
            } else if (typeof Swal !== 'undefined' && Swal) {
                Swal.fire({
                    title: 'Error!',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonText: 'Close'
                });
            } else {
                alert(errorMsg);
            }

            reject(error);
        });
    });
};

/**
 * Write article with AI Auto Writer using SSE streaming
 * @param {string} title - Article title
 * @param {string} divId - Target div ID to display content
 * @param {string} lang - Language code
 * @returns {Promise} Promise that resolves when article is complete
 */
window.writeArticleWithAutoWriter = function (title, divId, lang = 'vi') {
    return new Promise((resolve, reject) => {
        console.log('=== writeArticleWithAutoWriter called ===');
        console.log('Title:', title);
        console.log('DivId:', divId);
        console.log('Lang:', lang);
        
        if (!title || !title.trim()) {
            const errorMsg = 'Please provide a title for the article.';
            console.error('Error: No title provided');
            if (typeof showError === 'function') {
                showError(errorMsg);
            } else if (typeof Swal !== 'undefined' && Swal) {
                Swal.fire({
                    title: 'Error!',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonText: 'Close'
                });
            } else {
                alert(errorMsg);
            }
            reject(new Error(errorMsg));
            return;
        }

        // Check if ajax_url is available
        if (typeof aiautotool_js_setting === 'undefined' || !aiautotool_js_setting.ajax_url) {
            const errorMsg = 'AJAX URL not configured. Please refresh the page.';
            console.error('Error:', errorMsg);
            if (typeof Swal !== 'undefined' && Swal) {
                Swal.fire({
                    title: 'Error!',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonText: 'Close'
                });
            } else {
                alert(errorMsg);
            }
            reject(new Error(errorMsg));
            return;
        }

        // Hide info_content div when streaming starts
        const infoContentDiv = document.getElementById('info_content');
        if (infoContentDiv) {
            infoContentDiv.style.display = 'none';
        }

        // Show loading
        if (typeof showLoading === 'function') {
            showLoading('Starting AI Auto Writer...');
        }

        // Clear target div and add container
        if (divId) {
            const targetDiv = document.getElementById(divId);
            if (targetDiv) {
                targetDiv.innerHTML = '<div id="auto-writer-status-container" class="aiautotool-agent-run-wrap"></div>' +
                        '<div id="auto-writer-content-container" class="aiautotool-agent-content-wrap"></div>';
                const contentContainer = document.getElementById('auto-writer-content-container');
                if (contentContainer) {
                    aiautotoolSetAutoWriterContentLoading(contentContainer, 'Đang chờ nội dung đầu tiên...');
                }
                const statusContainer = document.getElementById('auto-writer-status-container');
                if (statusContainer) {
                    const run = aiautotoolEnsureAutoWriterRunUI(statusContainer);
                    aiautotoolSetAgentStep(run, 'connect');
                    aiautotoolSetAgentCurrent(run, 'Đang gửi yêu cầu đến AI Provider...', 'Starting');
                    aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Đang khởi tạo', 'AI Writer đang chuẩn bị provider/model và mở kết nối realtime.');
                    aiautotoolSetAgentPanel(run, '[data-agent-next]', 'Tiếp theo', 'Kết nối provider, tạo outline, rồi viết từng phần nội dung.');
                }
            } else {
                console.warn('Target div not found:', divId);
            }
        }

        // Generate message ID
        const messageId = 'auto_writer_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        const articleSettings = typeof getArticleSettings === 'function' ? getArticleSettings() : {};

        // Prepare data
        const dataToSend = {
            title: title,
            lang: lang,
            message_id: messageId,
            provider_id: articleSettings.aiProvider || '',
            model: articleSettings.aiModel || '',
            article_settings: articleSettings
        };

        // Create form data
        const formData = new FormData();
        formData.append('action', 'aiautotool_write_article_with_auto_writer');
        formData.append('data', JSON.stringify(dataToSend));
        formData.append('security', (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) ? aiautotool_js_setting.security : '');

        // Variables for tracking content
        let articleContent = '';
        let receivedCompleteEvent = false;
        let receivedErrorEvent = false;
        let streamErrorMessage = '';

        console.log('Sending request to AI Auto Writer:', aiautotool_js_setting.ajax_url);
        console.log('Request data:', dataToSend);
        console.log('Security nonce:', (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) ? 'Present' : 'Missing');

        // Use fetch to POST and get streaming response
        fetch(aiautotool_js_setting.ajax_url, {
            method: 'POST',
            body: formData
        }).then(response => {
            console.log('Response status:', response.status);

            if (!response.ok) {
                console.error('Response not OK. Status:', response.status);
                return response.text().then(text => {
                    console.error('Error response body:', text);
                    const errorMsg = 'Network response was not ok: ' + response.status + ' - ' + text.substring(0, 200);
                    if (typeof hideLoading === 'function') {
                        hideLoading();
                    }
                    if (typeof Swal !== 'undefined' && Swal) {
                        Swal.fire({
                            title: 'Error!',
                            text: errorMsg,
                            icon: 'error',
                            confirmButtonText: 'Close'
                        });
                    }
                    throw new Error(errorMsg);
                });
            }

            // Check if response is SSE
            const contentType = response.headers.get('content-type');
            console.log('Response content-type:', contentType);

            if (!contentType || !contentType.includes('text/event-stream')) {
                console.warn('Response is not SSE stream. Content-type:', contentType);
                return response.text().then(text => {
                    console.log('Non-SSE response text (first 500 chars):', text.substring(0, 500));
                    try {
                        const jsonData = JSON.parse(text);
                        console.log('Parsed JSON response:', jsonData);
                        if (jsonData.code && jsonData.code !== '200') {
                            const errorMsg = jsonData.msg || 'Server error';
                            if (typeof hideLoading === 'function') {
                                hideLoading();
                            }
                            if (typeof Swal !== 'undefined' && Swal) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: errorMsg,
                                    icon: 'error',
                                    confirmButtonText: 'Close'
                                });
                            }
                            throw new Error(errorMsg);
                        }
                        throw new Error('Unexpected response format. Expected SSE stream.');
                    } catch (e) {
                        if (e.message && e.message.includes('Unexpected')) {
                            throw e;
                        }
                        const errorMsg = 'Server returned non-SSE response. Content-type: ' + contentType;
                        if (typeof hideLoading === 'function') {
                            hideLoading();
                        }
                        if (typeof Swal !== 'undefined' && Swal) {
                            Swal.fire({
                                title: 'Error!',
                                text: errorMsg + '\n\nResponse: ' + text.substring(0, 200),
                                icon: 'error',
                                confirmButtonText: 'Close'
                            });
                        }
                        throw new Error(errorMsg);
                    }
                });
            }
            
            console.log('SSE stream detected. Starting to process...');
            if (typeof hideLoading === 'function') {
                hideLoading();
            }

            // Process SSE stream
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';
            let currentEvent = null;

            function processStream() {
                return reader.read().then(({ done, value }) => {
                    if (done) {
                        if (typeof hideLoading === 'function') {
                            hideLoading();
                        }

                        // Finalize article display
                        const finalContent = articleContent;

                        if (receivedErrorEvent) {
                            throw new Error(streamErrorMessage || 'AI Auto Writer failed before creating a complete article.');
                        }

                        if (!receivedCompleteEvent) {
                            throw new Error('AI Auto Writer stream ended before the article was complete. Nội dung mới viết được một phần, vui lòng chạy lại hoặc đổi provider.');
                        }

                        // Store in global variable for btnaddpost button
                        if (typeof window !== 'undefined' && finalContent) {
                            window.aiautotool_content = finalContent;
                        }
                        if (typeof aiautotool_content !== 'undefined' && finalContent) {
                            aiautotool_content = finalContent;
                        }

                        if (divId && finalContent) {
                            const contentContainer = document.getElementById('auto-writer-content-container');
                            if (contentContainer) {
                                aiautotoolCompleteAutoWriterChunkLoaders(contentContainer);
                                aiautotoolRenderAutoWriterFinalContent(contentContainer, finalContent);

                                // Show Add Post button
                                const btnAddPost = document.querySelector('.btnaddpost');
                                if (btnAddPost) {
                                    btnAddPost.style.display = 'block';
                                    btnAddPost.style.marginTop = '15px';
                                    btnAddPost.style.marginBottom = '15px';
                                }

                                if (typeof scrollToBottom === 'function') {
                                    scrollToBottom();
                                }
                            }
                        }

                        resolve(finalContent);
                        return;
                    }

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');

                    // Keep the last incomplete line in buffer
                    buffer = lines.pop() || '';

                    lines.forEach(line => {
                        line = line.trim();

                        if (!line) {
                            currentEvent = null;
                            return;
                        }

                        if (line.startsWith('event:')) {
                            currentEvent = line.substring(6).trim();
                            console.log('SSE Event:', currentEvent);
                        } else if (line.startsWith('data:')) {
                            try {
                                const jsonData = line.substring(5).trim();
                                if (!jsonData) {
                                    return;
                                }

                                const data = JSON.parse(jsonData);
                                console.log('SSE Data received:', currentEvent, data);

                                // Update articleContent from complete event
                                if (currentEvent === 'complete' && data.content) {
                                    receivedCompleteEvent = true;
                                    articleContent = data.content;
                                    console.log('Article content received, length:', articleContent.length);
                                }
                                if (currentEvent === 'error') {
                                    receivedErrorEvent = true;
                                    streamErrorMessage = (data && data.message) ? data.message : 'AI Auto Writer failed.';
                                }

                                // Handle different event types
                                handleAutoWriterSSEEvent(data, currentEvent, divId, {
                                    articleContent: () => articleContent,
                                    appendArticleContent: (text) => { articleContent += text; },
                                    setArticleContent: (content) => { articleContent = content; }
                                });
                            } catch (e) {
                                console.error('Failed to parse SSE data:', e);
                                console.error('Line that failed:', line);
                                console.error('Current event:', currentEvent);
                            }
                        }
                    });

                    return processStream();
                });
            }

            processStream().catch(error => {
                console.error('Stream processing error:', error);
                if (typeof hideLoading === 'function') {
                    hideLoading();
                }

                const errorMsg = 'Error processing stream: ' + error.message;
                const contentContainer = document.getElementById('auto-writer-content-container');
                if (contentContainer) {
                    aiautotoolCompleteAutoWriterChunkLoaders(contentContainer);
                    contentContainer.classList.remove('is-loading');
                    contentContainer.innerHTML = '<div class="aiautotool-agent-panel aiautotool-agent-error" style="margin-top:12px;"><div class="aiautotool-agent-panel-title">Chưa tạo được bài hoàn chỉnh</div><div class="aiautotool-agent-panel-text">' + escapeHtml(errorMsg) + '</div></div>';
                }
                const btnAddPost = document.querySelector('.btnaddpost');
                if (btnAddPost) {
                    btnAddPost.style.display = 'none';
                }
                if (typeof window !== 'undefined') {
                    window.aiautotool_content = '';
                }
                if (typeof aiautotool_content !== 'undefined') {
                    aiautotool_content = '';
                }
                if (typeof showError === 'function') {
                    showError(errorMsg);
                } else if (typeof Swal !== 'undefined' && Swal) {
                    Swal.fire({
                        title: 'Error!',
                        text: errorMsg,
                        icon: 'error',
                        confirmButtonText: 'Close'
                    });
                } else {
                    alert(errorMsg);
                }

                reject(error);
            });

        }).catch(error => {
            if (typeof hideLoading === 'function') {
                hideLoading();
            }

            const errorMsg = 'Connection error: ' + error.message;
            const contentContainer = document.getElementById('auto-writer-content-container');
            if (contentContainer) {
                aiautotoolCompleteAutoWriterChunkLoaders(contentContainer);
                contentContainer.classList.remove('is-loading');
                contentContainer.innerHTML = '<div class="aiautotool-agent-panel aiautotool-agent-error" style="margin-top:12px;"><div class="aiautotool-agent-panel-title">Kết nối bị ngắt</div><div class="aiautotool-agent-panel-text">' + escapeHtml(errorMsg) + '</div></div>';
            }
            const btnAddPost = document.querySelector('.btnaddpost');
            if (btnAddPost) {
                btnAddPost.style.display = 'none';
            }
            if (typeof window !== 'undefined') {
                window.aiautotool_content = '';
            }
            if (typeof aiautotool_content !== 'undefined') {
                aiautotool_content = '';
            }
            if (typeof showError === 'function') {
                showError(errorMsg);
            } else if (typeof Swal !== 'undefined' && Swal) {
                Swal.fire({
                    title: 'Error!',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonText: 'Close'
                });
            } else {
                alert(errorMsg);
            }

            reject(error);
        });
    });
};

/**
 * Handle SSE events for AI Auto Writer
 */
function aiautotoolEnsureAgentRunStyles() {
    if (document.getElementById('aiautotool-agent-run-styles')) {
        return;
    }

    const style = document.createElement('style');
    style.id = 'aiautotool-agent-run-styles';
    style.textContent = `
        .aiautotool-agent-run-wrap {
            padding: 14px;
            border-bottom: 1px solid #d8e4dc;
            margin-bottom: 12px;
            font-family: Arial, sans-serif;
        }
        .aiautotool-agent-content-wrap {
            padding: 14px;
            font-family: Arial, sans-serif;
        }
        .aiautotool-agent-content-wrap.is-loading {
            position: relative;
            min-height: 220px;
            border: 1px solid #d8e4dc;
            border-radius: 8px;
            background: #fbfdfc;
            overflow: hidden;
        }
        .aiautotool-agent-content-wrap.is-loading::before {
            content: "";
            position: absolute;
            inset: 0;
            pointer-events: none;
            background: linear-gradient(110deg, transparent 0%, rgba(0, 139, 97, 0.07) 38%, rgba(255, 255, 255, 0.85) 50%, rgba(0, 139, 97, 0.07) 62%, transparent 100%);
            transform: translateX(-120%);
            animation: aiautotoolAgentSweep 2.1s ease-in-out infinite;
        }
        .aiautotool-agent-content-loading {
            position: relative;
            display: grid;
            gap: 12px;
            padding: 2px;
            color: #486257;
            font-size: 12px;
            line-height: 1.45;
        }
        .aiautotool-agent-content-loading-title {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #173b2f;
            font-weight: 750;
        }
        .aiautotool-agent-content-spinner {
            width: 18px;
            height: 18px;
            border-radius: 50%;
            border: 2px solid #bfe8d1;
            border-top-color: #008b61;
            animation: aiautotoolAgentSpin 0.9s linear infinite;
        }
        .aiautotool-agent-content-lines {
            display: grid;
            gap: 9px;
            margin-top: 4px;
        }
        .aiautotool-agent-content-line {
            height: 11px;
            border-radius: 999px;
            background: linear-gradient(90deg, #edf6f1 0%, #d8eee3 45%, #edf6f1 100%);
            background-size: 220% 100%;
            animation: aiautotoolAgentLinePulse 1.35s ease-in-out infinite;
        }
        .aiautotool-agent-content-line:nth-child(2) {
            width: 82%;
            animation-delay: 0.12s;
        }
        .aiautotool-agent-content-line:nth-child(3) {
            width: 64%;
            animation-delay: 0.24s;
        }
        .aiautotool-agent-run {
            background: #fbfdfc;
            border: 1px solid #d8e4dc;
            border-radius: 8px;
            overflow: hidden;
            color: #173b2f;
        }
        .aiautotool-agent-run.is-active {
            position: relative;
            box-shadow: 0 0 0 1px rgba(0, 139, 97, 0.05), 0 10px 24px rgba(0, 139, 97, 0.08);
        }
        .aiautotool-agent-run.is-active::before {
            content: "";
            position: absolute;
            inset: 0;
            pointer-events: none;
            background: linear-gradient(110deg, transparent 0%, rgba(0, 139, 97, 0.08) 38%, rgba(255, 255, 255, 0.7) 50%, rgba(0, 139, 97, 0.08) 62%, transparent 100%);
            transform: translateX(-120%);
            animation: aiautotoolAgentSweep 2.2s ease-in-out infinite;
        }
        .aiautotool-agent-run-head {
            padding: 13px 14px;
            background: #f1faf5;
            border-bottom: 1px solid #d8e4dc;
        }
        .aiautotool-agent-run-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 700;
            color: #123b2e;
        }
        .aiautotool-agent-pill {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 8px;
            border-radius: 999px;
            background: #e8f7ef;
            color: #008b61;
            border: 1px solid #bfe8d1;
            font-size: 11px;
            font-weight: 700;
            white-space: nowrap;
        }
        .aiautotool-agent-run.is-active .aiautotool-agent-pill {
            animation: aiautotoolAgentPulse 1.4s ease-in-out infinite;
        }
        .aiautotool-agent-pill.is-warning {
            background: #fff7ed;
            color: #c2410c;
            border-color: #fed7aa;
            animation: none;
        }
        .aiautotool-agent-current {
            color: #486257;
            font-size: 12px;
            line-height: 1.45;
        }
        .aiautotool-agent-body {
            padding: 12px 14px 14px;
        }
        .aiautotool-agent-timeline {
            display: grid;
            gap: 8px;
            margin: 0 0 12px;
        }
        .aiautotool-agent-step {
            display: grid;
            grid-template-columns: 24px 1fr;
            gap: 9px;
            align-items: start;
        }
        .aiautotool-agent-dot {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #d8e4dc;
            background: #fff;
            color: #7a8d85;
            font-size: 11px;
            font-weight: 800;
        }
        .aiautotool-agent-step.is-running .aiautotool-agent-dot {
            background: #008b61;
            border-color: #008b61;
            color: #fff;
            box-shadow: 0 0 0 4px rgba(0, 139, 97, 0.12);
            animation: aiautotoolAgentDotPulse 1.15s ease-in-out infinite;
        }
        .aiautotool-agent-step.is-done .aiautotool-agent-dot {
            background: #e8f7ef;
            border-color: #9bdabb;
            color: #008b61;
        }
        .aiautotool-agent-step.is-warning .aiautotool-agent-dot {
            background: #fff7ed;
            border-color: #fdba74;
            color: #c2410c;
        }
        .aiautotool-agent-step-title {
            font-size: 12px;
            font-weight: 700;
            color: #173b2f;
            line-height: 1.35;
        }
        .aiautotool-agent-step-desc {
            color: #6b7c74;
            font-size: 11px;
            line-height: 1.35;
            margin-top: 2px;
        }
        .aiautotool-agent-panel {
            border: 1px solid #e3ece7;
            border-radius: 8px;
            background: #fff;
            padding: 10px;
            margin-top: 9px;
        }
        .aiautotool-agent-panel-title {
            font-size: 12px;
            color: #173b2f;
            font-weight: 750;
            margin-bottom: 6px;
        }
        .aiautotool-agent-panel-text {
            font-size: 12px;
            color: #4b6359;
            line-height: 1.55;
            white-space: pre-wrap;
            word-break: break-word;
        }
        .aiautotool-agent-outline-grid {
            display: grid;
            gap: 8px;
        }
        .aiautotool-agent-outline-meta {
            display: grid;
            gap: 6px;
            grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
        }
        .aiautotool-agent-mini-card {
            background: #f8fbf9;
            border: 1px solid #e3ece7;
            border-radius: 7px;
            padding: 8px;
            min-width: 0;
        }
        .aiautotool-agent-mini-card strong {
            display: block;
            color: #008b61;
            font-size: 11px;
            margin-bottom: 4px;
        }
        .aiautotool-agent-mini-card span {
            color: #344d43;
            font-size: 12px;
            line-height: 1.4;
        }
        .aiautotool-agent-section-list {
            display: grid;
            gap: 6px;
            max-height: 260px;
            overflow: auto;
            padding-right: 2px;
        }
        .aiautotool-agent-section-item {
            display: grid;
            grid-template-columns: 22px 1fr;
            gap: 8px;
            padding: 8px;
            border: 1px solid #e3ece7;
            border-radius: 7px;
            background: #fff;
        }
        .aiautotool-agent-section-index {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            background: #e8f7ef;
            color: #008b61;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 11px;
            font-weight: 800;
        }
        .aiautotool-agent-section-title {
            font-size: 12px;
            font-weight: 750;
            color: #173b2f;
            line-height: 1.35;
        }
        .aiautotool-agent-section-desc {
            font-size: 11px;
            color: #6b7c74;
            line-height: 1.4;
            margin-top: 3px;
        }
        .aiautotool-agent-review {
            border-color: #bfe8d1;
            background: #f6fcf9;
        }
        .aiautotool-agent-error {
            border-color: #fecaca;
            background: #fef2f2;
        }
        .aiautotool-agent-error .aiautotool-agent-panel-title,
        .aiautotool-agent-error .aiautotool-agent-panel-text {
            color: #991b1b;
        }
        .aiautotool-agent-run.is-complete,
        .aiautotool-agent-run.is-error {
            box-shadow: none;
        }
        .aiautotool-agent-run.is-complete::before,
        .aiautotool-agent-run.is-error::before {
            display: none;
        }
        .aiautotool-agent-run.is-complete .aiautotool-agent-pill,
        .aiautotool-agent-run.is-error .aiautotool-agent-pill,
        .aiautotool-agent-run.is-complete .aiautotool-agent-dot,
        .aiautotool-agent-run.is-error .aiautotool-agent-dot {
            animation: none;
        }
        .auto-writer-chunk.is-writing {
            position: relative;
            box-shadow: 0 0 0 1px rgba(0, 139, 97, 0.06), 0 10px 22px rgba(0, 139, 97, 0.08);
        }
        .auto-writer-chunk-loader {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            margin-top: 12px;
            padding-top: 10px;
            border-top: 1px solid #d8e4dc;
            color: #008b61;
            font-size: 12px;
            font-weight: 700;
            line-height: 1.2;
        }
        .auto-writer-chunk-loader-dots {
            display: inline-flex;
            align-items: center;
            gap: 3px;
        }
        .auto-writer-chunk-loader-dots span {
            width: 4px;
            height: 4px;
            border-radius: 50%;
            background: #008b61;
            animation: aiautotoolChunkDot 1s ease-in-out infinite;
        }
        .auto-writer-chunk-loader-dots span:nth-child(2) {
            animation-delay: 0.15s;
        }
        .auto-writer-chunk-loader-dots span:nth-child(3) {
            animation-delay: 0.3s;
        }
        @keyframes aiautotoolAgentSweep {
            0% { transform: translateX(-120%); opacity: 0; }
            20% { opacity: 1; }
            70% { opacity: 1; }
            100% { transform: translateX(120%); opacity: 0; }
        }
        @keyframes aiautotoolAgentPulse {
            0%, 100% { box-shadow: 0 0 0 0 rgba(0, 139, 97, 0.24); }
            50% { box-shadow: 0 0 0 5px rgba(0, 139, 97, 0.08); }
        }
        @keyframes aiautotoolAgentDotPulse {
            0%, 100% { box-shadow: 0 0 0 4px rgba(0, 139, 97, 0.12); transform: scale(1); }
            50% { box-shadow: 0 0 0 7px rgba(0, 139, 97, 0.05); transform: scale(1.04); }
        }
        @keyframes aiautotoolAgentSpin {
            to { transform: rotate(360deg); }
        }
        @keyframes aiautotoolAgentLinePulse {
            0% { background-position: 120% 0; opacity: 0.72; }
            50% { opacity: 1; }
            100% { background-position: -120% 0; opacity: 0.72; }
        }
        @keyframes aiautotoolChunkDot {
            0%, 80%, 100% { opacity: 0.35; transform: translateY(0); }
            40% { opacity: 1; transform: translateY(-2px); }
        }
    `;
    document.head.appendChild(style);
}

function aiautotoolSetAutoWriterContentLoading(contentContainer, message) {
    if (!contentContainer) return;
    aiautotoolEnsureAgentRunStyles();
    const safeMessage = (() => {
        const div = document.createElement('div');
        div.textContent = message || 'AI đang chuẩn bị nội dung...';
        return div.innerHTML;
    })();
    contentContainer.classList.add('is-loading');
    contentContainer.innerHTML = `
        <div class="aiautotool-agent-content-loading" data-auto-writer-content-loading>
            <div class="aiautotool-agent-content-loading-title">
                <span class="aiautotool-agent-content-spinner" aria-hidden="true"></span>
                <span>${safeMessage}</span>
            </div>
            <div>Vùng này sẽ cập nhật realtime khi AI bắt đầu trả từng phần bài viết.</div>
            <div class="aiautotool-agent-content-lines" aria-hidden="true">
                <span class="aiautotool-agent-content-line"></span>
                <span class="aiautotool-agent-content-line"></span>
                <span class="aiautotool-agent-content-line"></span>
            </div>
        </div>
    `;
}

function aiautotoolPrepareAutoWriterContentStreaming(contentContainer) {
    if (!contentContainer) return;
    contentContainer.classList.add('is-loading');
    const placeholder = contentContainer.querySelector('[data-auto-writer-content-loading]');
    if (placeholder) {
        placeholder.remove();
    }
}

function aiautotoolFinishAutoWriterContentLoading(contentContainer) {
    if (!contentContainer) return;
    if (contentContainer.classList.contains('is-loading')) {
        contentContainer.classList.remove('is-loading');
    }
}

function aiautotoolCompleteAutoWriterChunkLoaders(contentContainer) {
    if (!contentContainer) return;
    contentContainer.querySelectorAll('.auto-writer-chunk.is-writing').forEach(chunk => {
        chunk.classList.remove('is-writing');
        const loader = chunk.querySelector('[data-auto-writer-chunk-loader]');
        if (loader) {
            loader.remove();
        }
    });
}

function aiautotoolBuildAutoWriterChunkLoader(label) {
    const safeLabel = (() => {
        const div = document.createElement('div');
        div.textContent = label || 'Đang viết tiếp';
        return div.innerHTML;
    })();

    return '<div class="auto-writer-chunk-loader" data-auto-writer-chunk-loader>' +
        '<span class="auto-writer-chunk-loader-label">' + safeLabel + '</span>' +
        '<span class="auto-writer-chunk-loader-dots" aria-hidden="true"><span></span><span></span><span></span></span>' +
        '</div>';
}

function aiautotoolEnsureAutoWriterRunUI(statusContainer) {
    aiautotoolEnsureAgentRunStyles();

    let run = statusContainer.querySelector('.aiautotool-agent-run');
    if (run) {
        return run;
    }

    statusContainer.innerHTML = `
        <div class="aiautotool-agent-run">
            <div class="aiautotool-agent-run-head">
                <div class="aiautotool-agent-run-title">
                    <span>AI Writer đang xử lý</span>
                    <span class="aiautotool-agent-pill" data-agent-pill>Live</span>
                </div>
                <div class="aiautotool-agent-current" data-agent-current>Đang kết nối provider...</div>
            </div>
            <div class="aiautotool-agent-body">
                <div class="aiautotool-agent-timeline" data-agent-timeline></div>
                <div class="aiautotool-agent-panel" data-agent-result>
                    <div class="aiautotool-agent-panel-title">Kết quả hiện tại</div>
                    <div class="aiautotool-agent-panel-text">Chưa có dữ liệu. Khi AI chốt outline hoặc viết xong từng phần, kết quả sẽ cập nhật tại đây.</div>
                </div>
                <div class="aiautotool-agent-panel" data-agent-next>
                    <div class="aiautotool-agent-panel-title">Tiếp theo</div>
                    <div class="aiautotool-agent-panel-text">Phân tích tiêu đề và lập outline.</div>
                </div>
                <div data-agent-outline></div>
                <div data-agent-review></div>
            </div>
        </div>
    `;

    run = statusContainer.querySelector('.aiautotool-agent-run');
    run.classList.add('is-active');
    run._aiautotoolAgentState = {
        currentStep: 'connect',
        doneSteps: {},
        warningSteps: {},
        lastMessages: [],
        sectionsDone: 0,
        totalSections: 0,
        contentChunks: 0
    };
    aiautotoolUpdateAgentTimeline(run);
    return run;
}

function aiautotoolGetAgentRunState(run) {
    if (!run._aiautotoolAgentState) {
        run._aiautotoolAgentState = {
            currentStep: 'connect',
            doneSteps: {},
            warningSteps: {},
            lastMessages: [],
            sectionsDone: 0,
            totalSections: 0,
            contentChunks: 0
        };
    }
    return run._aiautotoolAgentState;
}

function aiautotoolSetAgentCurrent(run, message, pillText, pillMode) {
    const current = run.querySelector('[data-agent-current]');
    const pill = run.querySelector('[data-agent-pill]');
    if (current && message) {
        current.textContent = message;
    }
    if (pill) {
        pill.textContent = pillText || 'Live';
        pill.className = 'aiautotool-agent-pill' + (pillMode === 'warning' ? ' is-warning' : '');
    }
    run.classList.remove('is-complete', 'is-error');
    run.classList.add('is-active');
}

function aiautotoolSetAgentStep(run, stepKey, options) {
    const state = aiautotoolGetAgentRunState(run);
    state.currentStep = stepKey || state.currentStep;
    if (options && options.done) {
        state.doneSteps[stepKey] = true;
    }
    if (options && options.warning) {
        state.warningSteps[stepKey] = true;
    }
    aiautotoolUpdateAgentTimeline(run);
}

function aiautotoolUpdateAgentTimeline(run) {
    const state = aiautotoolGetAgentRunState(run);
    const timeline = run.querySelector('[data-agent-timeline]');
    if (!timeline) {
        return;
    }

    const steps = [
        { key: 'connect', title: 'Kết nối provider', desc: 'Chọn provider/model và mở luồng realtime.' },
        { key: 'plan', title: 'Phân tích & outline', desc: 'Xác định intent, độc giả, giọng văn và bố cục.' },
        { key: 'draft', title: 'Viết nội dung', desc: 'Sinh mở bài, từng phần chính và kết luận.' },
        { key: 'review', title: 'Review kết quả', desc: 'Kiểm tra độ đủ ý, flow bài và khả năng xuất bản.' },
        { key: 'finish', title: 'Hoàn tất', desc: 'Đưa bài viết vào editor và bật thao tác lưu.' }
    ];

    timeline.innerHTML = steps.map((step, index) => {
        const isDone = !!state.doneSteps[step.key];
        const isRunning = state.currentStep === step.key && !isDone;
        const isWarning = !!state.warningSteps[step.key];
        const className = 'aiautotool-agent-step' + (isDone ? ' is-done' : '') + (isRunning ? ' is-running' : '') + (isWarning ? ' is-warning' : '');
        const dot = isDone ? '&#10003;' : (index + 1);
        return '<div class="' + className + '">' +
            '<span class="aiautotool-agent-dot">' + dot + '</span>' +
            '<span><span class="aiautotool-agent-step-title">' + step.title + '</span>' +
            '<span class="aiautotool-agent-step-desc">' + step.desc + '</span></span>' +
            '</div>';
    }).join('');
}

function aiautotoolSetAgentPanel(run, selector, title, text) {
    const panel = run.querySelector(selector);
    if (!panel) {
        return;
    }
    panel.innerHTML = '<div class="aiautotool-agent-panel-title">' + aiautotoolEscapeHtml(title) + '</div>' +
        '<div class="aiautotool-agent-panel-text">' + aiautotoolEscapeHtml(text || '') + '</div>';
}

function aiautotoolTrackAgentStatus(run, message) {
    const state = aiautotoolGetAgentRunState(run);
    if (!message) {
        return;
    }

    state.lastMessages.push(message);
    state.lastMessages = state.lastMessages.slice(-3);

    const lower = String(message).toLowerCase();
    if (lower.indexOf('provider hiện tại thất bại') !== -1 || lower.indexOf('failed') !== -1 || lower.indexOf('dự phòng') !== -1) {
        aiautotoolSetAgentStep(run, 'connect', { warning: true });
        aiautotoolSetAgentCurrent(run, message, 'Đổi provider', 'warning');
        aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Kết quả suy nghĩ', 'Provider/model hiện tại không trả lời đúng. Hệ thống đang chuyển sang provider dự phòng để tiếp tục bài viết.');
        aiautotoolSetAgentPanel(run, '[data-agent-next]', 'Tiếp theo', 'Thử provider/model kế tiếp trong router rồi quay lại bước tạo outline.');
        return;
    }

    if (lower.indexOf('outline') !== -1 || lower.indexOf('phân tích') !== -1 || lower.indexOf('tiêu đề') !== -1) {
        aiautotoolSetAgentStep(run, 'plan');
        aiautotoolSetAgentCurrent(run, message, 'Đang lập kế hoạch');
        aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Đang suy nghĩ', 'AI đang đọc tiêu đề, xác định mục tiêu bài viết và dựng khung nội dung.');
        aiautotoolSetAgentPanel(run, '[data-agent-next]', 'Tiếp theo', 'Chốt outline rồi bắt đầu viết mở bài.');
        return;
    }

    if (lower.indexOf('viết') !== -1 || lower.indexOf('nội dung') !== -1 || lower.indexOf('phần') !== -1 || lower.indexOf('mở bài') !== -1) {
        aiautotoolSetAgentStep(run, 'draft');
        aiautotoolSetAgentCurrent(run, message, 'Đang viết');
        aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Kết quả đang tạo', state.lastMessages.join('\n'));
        aiautotoolSetAgentPanel(run, '[data-agent-next]', 'Tiếp theo', 'Hoàn thành từng phần, sau đó review bài viết tổng thể.');
        return;
    }

    aiautotoolSetAgentCurrent(run, message, 'Live');
    aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Cập nhật realtime', state.lastMessages.join('\n'));
}

function aiautotoolRenderAgentOutline(run, outline) {
    const holder = run.querySelector('[data-agent-outline]');
    if (!holder || !outline) {
        return;
    }

    const sections = Array.isArray(outline.sections) ? outline.sections : [];
    const state = aiautotoolGetAgentRunState(run);
    state.totalSections = sections.length;

    const metaCards = [
        outline.detected_industry ? '<div class="aiautotool-agent-mini-card"><strong>Ngành</strong><span>' + aiautotoolEscapeHtml(outline.detected_industry) + '</span></div>' : '',
        outline.target_audience ? '<div class="aiautotool-agent-mini-card"><strong>Độc giả</strong><span>' + aiautotoolEscapeHtml(outline.target_audience) + '</span></div>' : '',
        outline.tone ? '<div class="aiautotool-agent-mini-card"><strong>Giọng văn</strong><span>' + aiautotoolEscapeHtml(outline.tone) + '</span></div>' : ''
    ].join('');

    const sectionHtml = sections.map((section, index) => {
        return '<div class="aiautotool-agent-section-item">' +
            '<span class="aiautotool-agent-section-index">' + (index + 1) + '</span>' +
            '<span><span class="aiautotool-agent-section-title">' + aiautotoolEscapeHtml(section.title || 'Phần ' + (index + 1)) + '</span>' +
            (section.description ? '<span class="aiautotool-agent-section-desc">' + aiautotoolEscapeHtml(section.description) + '</span>' : '') +
            '</span></div>';
    }).join('');

    holder.innerHTML = '<div id="auto-writer-outline-display" class="aiautotool-agent-panel">' +
        '<div class="aiautotool-agent-panel-title">Kết quả phân tích & outline</div>' +
        '<div class="aiautotool-agent-outline-grid">' +
        (outline.analysis ? '<div class="aiautotool-agent-panel-text">' + aiautotoolEscapeHtml(outline.analysis) + '</div>' : '') +
        (metaCards ? '<div class="aiautotool-agent-outline-meta">' + metaCards + '</div>' : '') +
        (sectionHtml ? '<div class="aiautotool-agent-panel-title">Các phần sẽ viết (' + sections.length + ')</div><div class="aiautotool-agent-section-list">' + sectionHtml + '</div>' : '') +
        '</div></div>';

    aiautotoolSetAgentStep(run, 'plan', { done: true });
    aiautotoolSetAgentStep(run, 'draft');
    aiautotoolSetAgentCurrent(run, 'Outline đã chốt. AI bắt đầu viết bài theo từng phần.', 'Đang viết');
    aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Kết quả suy nghĩ', 'Đã xác định bố cục bài viết gồm ' + sections.length + ' phần. Outline được ghim lại để bạn review nhanh trong lúc nội dung tiếp tục chạy.');
    aiautotoolSetAgentPanel(run, '[data-agent-next]', 'Tiếp theo', 'Viết mở bài và triển khai từng section theo outline.');
}

function aiautotoolRenderAgentReview(run, data, state) {
    const holder = run.querySelector('[data-agent-review]');
    if (!holder) {
        return;
    }

    const content = data && data.content ? String(data.content) : (state && state.articleContent ? String(state.articleContent()) : '');
    const plainText = content.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
    const wordCount = plainText ? plainText.split(/\s+/).length : 0;
    const h2Count = (content.match(/<h2\b/gi) || []).length;
    const paragraphCount = (content.match(/<p\b/gi) || []).length;

    holder.innerHTML = '<div class="aiautotool-agent-panel aiautotool-agent-review">' +
        '<div class="aiautotool-agent-panel-title">Review kết quả</div>' +
        '<div class="aiautotool-agent-panel-text">' +
        'Bài viết đã hoàn tất. Tóm tắt nhanh: khoảng ' + wordCount + ' từ, ' + h2Count + ' heading H2, ' + paragraphCount + ' đoạn nội dung. ' +
        'Bạn nên đọc lại phần mở bài, kiểm tra factual details và thêm ảnh/video nếu bài cần minh họa.' +
        '</div></div>';

    aiautotoolSetAgentStep(run, 'draft', { done: true });
    aiautotoolSetAgentStep(run, 'review', { done: true });
    aiautotoolSetAgentStep(run, 'finish', { done: true });
    aiautotoolSetAgentCurrent(run, 'Hoàn tất. Nội dung đã được đưa vào khung kết quả.', 'Done');
    run.classList.remove('is-active', 'is-error');
    run.classList.add('is-complete');
    aiautotoolSetAgentPanel(run, '[data-agent-next]', 'Tiếp theo', 'Review thủ công, thêm media nếu cần, rồi lưu hoặc xuất bản bài.');
}

function aiautotoolRenderAutoWriterFinalContent(contentContainer, finalContent) {
    if (!contentContainer || !finalContent) {
        return;
    }
    contentContainer.classList.remove('is-loading');

    if (typeof window !== 'undefined') {
        window.aiautotool_content = finalContent;
    }
    if (typeof aiautotool_content !== 'undefined') {
        aiautotool_content = finalContent;
    }

    contentContainer.innerHTML =
        '<div class="aiautotool-auto-writer-final" style="border:1px solid #d8e4dc;border-radius:8px;background:#fff;overflow:hidden;margin-top:12px;">' +
            '<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 12px;background:#f1faf5;border-bottom:1px solid #d8e4dc;">' +
                '<strong style="color:#173b2f;font-size:13px;">Bài viết đã tạo</strong>' +
                '<span style="color:#008b61;font-size:11px;font-weight:700;">Ready</span>' +
            '</div>' +
            '<div class="aiautotool-auto-writer-preview" style="padding:12px;color:#263b33;line-height:1.65;max-height:420px;overflow:auto;">' +
                finalContent +
            '</div>' +
            '<div style="padding:12px;border-top:1px solid #d8e4dc;background:#fbfdfc;position:sticky;bottom:0;">' +
                '<button type="button" class="button button-primary btnaddpost" style="width:100%;display:block;height:40px;font-weight:700;">Add To Post</button>' +
            '</div>' +
        '</div>';

    const btnAddPost = contentContainer.querySelector('.btnaddpost');
    if (btnAddPost) {
        btnAddPost.style.display = 'block';
    }
}

function handleAutoWriterSSEEvent(data, eventType, divId, state) {
    // Get status container
    let statusContainer = divId ? document.getElementById('auto-writer-status-container') : null;
    let contentContainer = divId ? document.getElementById('auto-writer-content-container') : null;

    if (!statusContainer && divId) {
        const targetDiv = document.getElementById(divId);
        if (targetDiv) {
            targetDiv.innerHTML = '<div id="auto-writer-status-container" class="aiautotool-agent-run-wrap"></div>' +
                '<div id="auto-writer-content-container" class="aiautotool-agent-content-wrap"></div>';
            statusContainer = document.getElementById('auto-writer-status-container');
            contentContainer = document.getElementById('auto-writer-content-container');
            if (contentContainer) {
                aiautotoolSetAutoWriterContentLoading(contentContainer, 'Đang chờ nội dung đầu tiên...');
            }
        }
    }
    if (!statusContainer && divId) return;
    const run = statusContainer ? aiautotoolEnsureAutoWriterRunUI(statusContainer) : null;

    const normalizedEventType = eventType || (data && data.type) || 'unknown';
    console.log('handleAutoWriterSSEEvent called with eventType:', normalizedEventType, 'data:', data);

    const escapeHtml = (text) => {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    };

    switch (normalizedEventType) {
        case 'connected':
            if (typeof hideLoading === 'function') {
                hideLoading();
            }
            if (run) {
                aiautotoolSetAgentStep(run, 'connect');
                aiautotoolSetAgentCurrent(run, 'Đã kết nối AI Auto Writer. Đang chuẩn bị provider/model.', 'Connected');
                aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Kết quả hiện tại', 'Luồng realtime đã mở thành công.');
                aiautotoolSetAgentPanel(run, '[data-agent-next]', 'Tiếp theo', 'Phân tích tiêu đề và lập outline.');
            }
            break;

        case 'status':
        case 'status_chunk':
            if (typeof hideLoading === 'function') {
                hideLoading();
            }
            if (run && data.message) {
                aiautotoolTrackAgentStatus(run, data.message);
                if (typeof scrollToBottom === 'function') scrollToBottom();
            }
            break;

        case 'content_chunk':
            // Handle content chunks (introduction, sections, conclusion)
            if (contentContainer && data.content) {
                aiautotoolPrepareAutoWriterContentStreaming(contentContainer);
                aiautotoolCompleteAutoWriterChunkLoaders(contentContainer);
                const chunkType = data.type || 'section';
                const chunkContent = data.content;
                const chunkLoader = aiautotoolBuildAutoWriterChunkLoader(chunkType === 'conclusion' ? 'Đang review bài viết' : 'Đang viết tiếp');

                // Append content to article
                state.appendArticleContent(chunkContent + '\n\n');
                if (run) {
                    const runState = aiautotoolGetAgentRunState(run);
                    runState.contentChunks += 1;
                    aiautotoolSetAgentStep(run, 'draft');
                    aiautotoolSetAgentCurrent(run, 'Đang viết ' + (data.title || chunkType) + '...', 'Đang viết');
                    aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Kết quả đang viết', 'Đã nhận ' + runState.contentChunks + ' khối nội dung từ AI.');
                    aiautotoolSetAgentPanel(run, '[data-agent-next]', 'Tiếp theo', chunkType === 'conclusion' ? 'Review bài viết và đưa kết quả vào editor.' : 'Tiếp tục viết phần kế tiếp trong outline.');
                }

                // Display content in container
                const chunkDiv = document.createElement('div');
                chunkDiv.className = 'auto-writer-chunk is-writing';
                chunkDiv.style.cssText = 'margin-bottom: 20px; padding: 15px; background: #fbfdfc; border-left: 4px solid #008b61; border-radius: 8px;';
                
                if (chunkType === 'introduction') {
                    chunkDiv.innerHTML = '<div style="font-weight: bold; color: #008b61; margin-bottom: 10px;">📝 Mở bài</div>' +
                        '<div style="line-height: 1.8;">' + chunkContent + '</div>' + chunkLoader;
                } else if (chunkType === 'section') {
                    const sectionTitle = data.title || 'Section';
                    const sectionNumber = data.section_number || '';
                    chunkDiv.innerHTML = '<div style="font-weight: bold; color: #008b61; margin-bottom: 10px;">📄 ' + 
                        (sectionNumber ? 'Phần ' + sectionNumber + ': ' : '') + sectionTitle + '</div>' +
                        '<div style="line-height: 1.8;">' + chunkContent + '</div>' + chunkLoader;
                } else if (chunkType === 'conclusion') {
                    chunkDiv.innerHTML = '<div style="font-weight: bold; color: #008b61; margin-bottom: 10px;">📌 Kết bài</div>' +
                        '<div style="line-height: 1.8;">' + chunkContent + '</div>' + chunkLoader;
                } else {
                    chunkDiv.innerHTML = '<div style="line-height: 1.8;">' + chunkContent + '</div>' + chunkLoader;
                }

                contentContainer.appendChild(chunkDiv);
                if (typeof scrollToBottom === 'function') scrollToBottom();
            }
            break;

        case 'complete':
            // Final content received
            if (run) {
                aiautotoolRenderAgentReview(run, data, state);
            }
            if (contentContainer && data.content) {
                aiautotoolCompleteAutoWriterChunkLoaders(contentContainer);
                state.setArticleContent(data.content);
                aiautotoolRenderAutoWriterFinalContent(contentContainer, data.content);

                // Show Add Post button
                const btnAddPost = document.querySelector('.btnaddpost');
                if (btnAddPost) {
                    btnAddPost.style.display = 'block';
                    btnAddPost.style.marginTop = '15px';
                    btnAddPost.style.marginBottom = '15px';
                }

                if (typeof scrollToBottom === 'function') {
                    scrollToBottom();
                }
            }
            break;

        case 'outline':
            // Display outline with analysis, industry, audience, tone, and sections
            console.log('Outline event received in handleAutoWriterSSEEvent, data:', data);
            
            // Use statusContainer for outline display
            if (run && data && data.outline) {
                aiautotoolRenderAgentOutline(run, data.outline);
                console.log('Outline displayed successfully in auto-writer-status-container');
                
                if (typeof scrollToBottom === 'function') {
                    scrollToBottom();
                }
            } else {
                console.error('Cannot display outline in handleAutoWriterSSEEvent:', {
                    statusContainer: !!statusContainer,
                    hasData: !!data,
                    hasOutline: !!(data && data.outline)
                });
            }
            break;

        case 'error':
            const errorMsg = data.message || 'An error occurred';
            console.error('Auto Writer Error:', errorMsg);

            if (run) {
                aiautotoolSetAgentCurrent(run, errorMsg, 'Error', 'warning');
                run.classList.remove('is-active', 'is-complete');
                run.classList.add('is-error');
                aiautotoolSetAgentPanel(run, '[data-agent-result]', 'Lỗi khi thực thi', errorMsg);
                const reviewHolder = run.querySelector('[data-agent-review]');
                if (reviewHolder) {
                    reviewHolder.innerHTML = '<div class="aiautotool-agent-panel aiautotool-agent-error"><div class="aiautotool-agent-panel-title">Cần xử lý</div><div class="aiautotool-agent-panel-text">' + escapeHtml(errorMsg) + '</div></div>';
                }
            }
            if (contentContainer) {
                aiautotoolCompleteAutoWriterChunkLoaders(contentContainer);
                contentContainer.classList.remove('is-loading');
                contentContainer.innerHTML = '<div class="aiautotool-agent-panel aiautotool-agent-error" style="margin-top:12px;"><div class="aiautotool-agent-panel-title">Chưa tạo được bài hoàn chỉnh</div><div class="aiautotool-agent-panel-text">' + escapeHtml(errorMsg) + '</div></div>';
            }
            if (typeof window !== 'undefined') {
                window.aiautotool_content = '';
            }
            if (typeof aiautotool_content !== 'undefined') {
                aiautotool_content = '';
            }

            if (typeof Swal !== 'undefined' && Swal) {
                Swal.fire({
                    title: 'Error!',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonText: 'Close'
                });
            } else if (typeof showError === 'function') {
                showError(errorMsg);
            } else {
                alert('Error: ' + errorMsg);
            }
            break;

        case 'done':
            console.log('Auto Writer stream closed:', data);
            break;

        default:
            console.log('Unknown event type:', normalizedEventType, 'data:', data);
            break;
    }
}

/**
 * Handle SSE events for article writing
 */
function handleArticleSSEEvent(data, eventType, divId, state) {
    // Get analysis container - this should always exist and never be cleared
    let container = divId ? document.getElementById('article-analysis-container') : null;
    // If container doesn't exist, try to create it
    if (!container && divId) {
        const targetDiv = document.getElementById(divId);
        if (targetDiv) {
            // Check if we need to create the structure
            const existingAnalysis = document.getElementById('article-analysis-container');
            if (!existingAnalysis) {
                targetDiv.innerHTML = '<div id="article-analysis-container" style="padding: 20px; font-family: Arial, sans-serif; border-bottom: 2px solid #e0e0e0; margin-bottom: 20px;"></div>' +
                    '<div id="article-content-container" style="padding: 20px; font-family: Arial, sans-serif;"></div>';
            }
        }
        // Try to get container again after creation
        container = document.getElementById('article-analysis-container');
    }
    if (!container && divId) return;

    // Normalize eventType - handle null/undefined
    const normalizedEventType = eventType || (data && data.type) || 'unknown';

    console.log('handleArticleSSEEvent called with eventType:', normalizedEventType, 'data:', data);

    // Helper function to escape HTML
    const escapeHtml = (text) => {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    };

    // Helper function to safely show Swal upgrade prompt
    const showSwalUpgrade = (msg) => {
        // Close any existing Swal modals first
        if (typeof Swal !== 'undefined' && Swal && typeof Swal.close === 'function') {
            try {
                Swal.close();
            } catch (e) {
                // Ignore errors when closing
            }
        }

        // Wait a bit to ensure DOM is ready
        setTimeout(() => {
            if (typeof Swal !== 'undefined' && Swal && typeof Swal.fire === 'function') {
                try {
                    console.log('Attempting to show Swal upgrade prompt...');
                    Swal.fire({
                        title: 'Upgrade to Pro Required',
                        html: '<div style="text-align: left; padding: 10px 0;">' +
                            '<p style="margin-bottom: 15px; color: #333; font-size: 15px;">' +
                            escapeHtml(msg) +
                            '</p>' +
                            '<p style="margin-bottom: 20px; color: #666; font-size: 14px;">' +
                            'Unlock unlimited requests and access to all premium features!' +
                            '</p>' +
                            '</div>',
                        icon: 'info',
                        iconColor: '#667eea',
                        showCancelButton: true,
                        confirmButtonText: '<i class="fa-solid fa-unlock-keyhole" style="margin-right: 8px;"></i> Upgrade to Pro',
                        cancelButtonText: 'Close',
                        confirmButtonColor: '#667eea',
                        cancelButtonColor: '#6c757d',
                        reverseButtons: true,
                        focusConfirm: true,
                        allowOutsideClick: false,
                        allowEscapeKey: true,
                        customClass: {
                            popup: 'aiautotool-upgrade-popup',
                            confirmButton: 'aiautotool-upgrade-btn'
                        }
                    }).then((result) => {
                        if (result && result.isConfirmed) {
                            const adminUrl = typeof ajaxurl !== 'undefined' ? ajaxurl.replace('/admin-ajax.php', '') : window.location.origin + '/wp-admin';
                            const upgradeUrl = adminUrl + '/admin.php?page=ai-auto-tool';
                            window.open(upgradeUrl, '_blank');
                        }
                    }).catch((error) => {
                        console.error('Swal.fire error:', error);
                        alert(msg + '\n\nPlease upgrade to Pro to use this feature.');
                    });
                    console.log('Swal.fire called successfully');
                } catch (error) {
                    console.error('Error showing Swal upgrade prompt:', error);
                    alert(msg + '\n\nPlease upgrade to Pro to use this feature.');
                }
            } else {
                console.log('Swal not available after delay, using alert fallback');
                alert(msg + '\n\nPlease upgrade to Pro to use this feature.');
            }
        }, 100);
    };

    switch (normalizedEventType) {
        case 'connected':
            if (container) {
                container.innerHTML = '<div style="padding: 10px; background: #e3f2fd; border-radius: 5px; margin-bottom: 10px;">✓ Connected to AI</div>';
            }
            break;

        case 'status':
            if (container && data.message) {
                const statusDiv = document.createElement('div');
                statusDiv.style.cssText = 'padding: 10px; background: #fff3cd; border-left: 4px solid #ffc107; margin-bottom: 10px; border-radius: 3px;';
                statusDiv.textContent = data.message;
                container.appendChild(statusDiv);
                if (typeof scrollToBottom === 'function') scrollToBottom();
            }
            break;

        case 'step_start':
            if (container && data.step && data.name && data.description) {
                // Check if step already exists - if so, remove it first to avoid duplicates
                const existingStepDiv = document.getElementById('step-' + data.step);
                if (existingStepDiv) {
                    existingStepDiv.remove();
                }

                const stepDiv = document.createElement('div');
                stepDiv.id = 'step-' + data.step;
                stepDiv.style.cssText = 'margin-bottom: 15px; padding: 0px; background: #f8f9fa; border-left: 4px solid #007bff; border-radius: 5px;';

                const stepHeader = document.createElement('div');
                stepHeader.style.cssText = 'font-weight: bold; font-size: 16px; color: #007bff; margin-bottom: 5px;';
                stepHeader.textContent = 'Step ' + data.step + ': ' + data.name;

                const stepDesc = document.createElement('div');
                stepDesc.style.cssText = 'color: #666; font-size: 14px; margin-bottom: 10px;';
                stepDesc.textContent = data.description;

                const stepContent = document.createElement('div');
                stepContent.id = 'step-content-' + data.step;
                stepContent.style.cssText = 'margin-top: 10px; padding: 0px; background: white; border-radius: 3px; min-height: 50px;';
                stepContent.innerHTML = '<div style="color: #999;">Processing...</div>';

                stepDiv.appendChild(stepHeader);
                stepDiv.appendChild(stepDesc);
                stepDiv.appendChild(stepContent);

                container.appendChild(stepDiv);
                state.setCurrentStepElement(stepContent);
                state.setCurrentStepNumber(data.step);

                // Clear any previous output for this step in state
                state.setStepOutput(data.step, '');

                if (typeof scrollToBottom === 'function') scrollToBottom();
            }
            break;

        case 'step_output':
            if (data.step && data.output) {
                const stepContent = document.getElementById('step-content-' + data.step);
                if (stepContent) {
                    // Store full output in state first
                    const currentOutput = state.stepOutputs()[data.step] || '';
                    const newFullOutput = currentOutput + data.output;
                    state.setStepOutput(data.step, newFullOutput);

                    // Get the full output from state to display
                    const fullOutput = state.stepOutputs()[data.step] || '';

                    // Check if output contains HTML (like article sections)
                    const isHtml = /<[a-z][\s\S]*>/i.test(fullOutput);

                    // Clear processing message
                    if (stepContent.querySelector('div[style*="color: #999"]')) {
                        stepContent.innerHTML = '';
                    }

                    if (isHtml) {
                        // Output is HTML - display it directly with proper styling
                        // Create a wrapper div for the content
                        const contentWrapper = document.createElement('div');
                        contentWrapper.style.cssText = 'padding: 15px; background: white; border-radius: 5px;';

                        // Add CSS for article sections if not already added
                        if (!document.getElementById('article-section-styles')) {
                            const style = document.createElement('style');
                            style.id = 'article-section-styles';
                            style.textContent = `
                                .article-section {
                                    margin-bottom: 25px;
                                    padding: 15px;
                                    background: #ffffff;
                                    border-left: 4px solid #667eea;
                                    border-radius: 5px;
                                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                                }
                                .section-header {
                                    font-size: 18px;
                                    font-weight: bold;
                                    color: #667eea;
                                    margin-bottom: 15px;
                                    padding-bottom: 10px;
                                    border-bottom: 2px solid #e0e0e0;
                                }
                                .article-section p {
                                    margin-bottom: 12px;
                                    line-height: 1.8;
                                    color: #333;
                                }
                                .article-section img {
                                    max-width: 100%;
                                    height: auto;
                                    border-radius: 5px;
                                    margin: 15px 0;
                                    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                                }
                                .article-section h2, .article-section h3 {
                                    color: #333;
                                    margin-top: 20px;
                                    margin-bottom: 15px;
                                }
                                .article-section ul, .article-section ol {
                                    margin-left: 20px;
                                    margin-bottom: 15px;
                                }
                                .article-section li {
                                    margin-bottom: 8px;
                                    line-height: 1.6;
                                }
                            `;
                            document.head.appendChild(style);
                        }

                        // Set HTML content
                        contentWrapper.innerHTML = fullOutput;
                        stepContent.innerHTML = '';
                        stepContent.appendChild(contentWrapper);
                    } else {
                        // Output is plain text - display with text formatting
                        // Remove length limit for better content display
                        stepContent.innerHTML = '<div style="padding: 15px; background: white; border-radius: 5px; line-height: 1.8; white-space: pre-wrap; word-wrap: break-word; color: #333;">' +
                            escapeHtml(fullOutput) +
                            '</div>';
                    }

                    if (typeof scrollToBottom === 'function') scrollToBottom();
                }
            }
            break;

        case 'step_complete':
            if (data.step) {
                const stepDiv = document.getElementById('step-' + data.step);
                if (stepDiv) {
                    stepDiv.style.borderLeftColor = data.status === 'success' ? '#28a745' : '#dc3545';

                    const stepContent = document.getElementById('step-content-' + data.step);
                    if (stepContent && data.status === 'success') {
                        // Check if message contains HTML (like task list)
                        const isHtml = data.message && /<[a-z][\s\S]*>/i.test(data.message);

                        if (isHtml) {
                            // Render HTML content directly
                            stepContent.innerHTML = data.message;
                        } else {
                            // Add checkmark for non-HTML content
                            const checkmark = document.createElement('span');
                            checkmark.style.cssText = 'color: #28a745; font-weight: bold; margin-left: 0px;';
                            checkmark.textContent = '✓';
                            stepContent.appendChild(checkmark);
                        }
                    }
                }
            }
            break;

        case 'section_complete':
            // Update checkbox for completed section in task list
            if (data && data.section_index !== undefined) {
                const sectionTaskId = 'section-task-' + data.section_index;
                const sectionTask = document.getElementById(sectionTaskId);

                if (sectionTask) {
                    const checkbox = sectionTask.querySelector('.task-checkbox');
                    const taskName = sectionTask.querySelector('.task-name');

                    if (checkbox) {
                        checkbox.style.background = '#28a745';
                        checkbox.style.borderColor = '#28a745';
                        checkbox.style.color = 'white';
                        checkbox.textContent = '✓';
                    }

                    if (taskName) {
                        taskName.style.color = '#28a745';
                        taskName.style.textDecoration = 'line-through';
                    }
                }
            }
            break;

        case 'outline':
            // Display outline with analysis, industry, audience, tone, and sections
            console.log('Outline event received, data:', data);
            console.log('Container exists:', !!container);
            console.log('divId:', divId);
            
            // Ensure container exists
            if (!container && divId) {
                const targetDiv = document.getElementById(divId);
                if (targetDiv) {
                    // Check if we need to create the structure
                    const existingAnalysis = document.getElementById('article-analysis-container');
                    if (!existingAnalysis) {
                        targetDiv.innerHTML = '<div id="article-analysis-container" style="padding: 20px; font-family: Arial, sans-serif; border-bottom: 2px solid #e0e0e0; margin-bottom: 20px;"></div>' +
                            '<div id="article-content-container" style="padding: 20px; font-family: Arial, sans-serif;"></div>';
                    }
                    container = document.getElementById('article-analysis-container');
                }
            }
            
            if (!container) {
                console.error('Cannot display outline: container not found');
                // Try to find or create container in body as fallback
                container = document.getElementById('article-analysis-container');
                if (!container) {
                    // Create container in body as last resort
                    container = document.createElement('div');
                    container.id = 'article-analysis-container';
                    container.style.cssText = 'padding: 20px; font-family: Arial, sans-serif; border-bottom: 2px solid #e0e0e0; margin-bottom: 20px;';
                    document.body.insertBefore(container, document.body.firstChild);
                }
            }
            
            if (container && data && data.outline) {
                const outline = data.outline;
                console.log('Displaying outline:', outline);
                
                // Remove any existing outline display
                const existingOutline = document.getElementById('article-outline-display');
                if (existingOutline) {
                    existingOutline.remove();
                }
                
                // Create outline container
                const outlineDiv = document.createElement('div');
                outlineDiv.id = 'article-outline-display';
                outlineDiv.style.cssText = 'margin-bottom: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 2px solid #667eea;';
                
                // Title
                const outlineTitle = document.createElement('div');
                outlineTitle.style.cssText = 'font-size: 20px; font-weight: bold; color: #667eea; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 2px solid #667eea;';
                outlineTitle.innerHTML = '📋 Outline & Analysis';
                outlineDiv.appendChild(outlineTitle);
                
                // Analysis section
                if (outline.analysis) {
                    const analysisDiv = document.createElement('div');
                    analysisDiv.style.cssText = 'margin-bottom: 15px; padding: 15px; background: white; border-radius: 5px; border-left: 4px solid #007bff;';
                    analysisDiv.innerHTML = '<div style="font-weight: bold; color: #007bff; margin-bottom: 8px; font-size: 16px;">📊 Analysis</div>' +
                        '<div style="color: #333; line-height: 1.6; white-space: pre-wrap;">' + escapeHtml(outline.analysis) + '</div>';
                    outlineDiv.appendChild(analysisDiv);
                }
                
                // Info grid (Industry, Audience, Tone)
                const infoGrid = document.createElement('div');
                infoGrid.style.cssText = 'display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; margin-bottom: 15px;';
                
                if (outline.detected_industry) {
                    const industryDiv = document.createElement('div');
                    industryDiv.style.cssText = 'padding: 12px; background: white; border-radius: 5px; border-left: 4px solid #28a745;';
                    industryDiv.innerHTML = '<div style="font-weight: bold; color: #28a745; margin-bottom: 5px; font-size: 14px;">🏭 Industry</div>' +
                        '<div style="color: #333; font-size: 14px;">' + escapeHtml(outline.detected_industry) + '</div>';
                    infoGrid.appendChild(industryDiv);
                }
                
                if (outline.target_audience) {
                    const audienceDiv = document.createElement('div');
                    audienceDiv.style.cssText = 'padding: 12px; background: white; border-radius: 5px; border-left: 4px solid #ffc107;';
                    audienceDiv.innerHTML = '<div style="font-weight: bold; color: #ffc107; margin-bottom: 5px; font-size: 14px;">👥 Target Audience</div>' +
                        '<div style="color: #333; font-size: 14px;">' + escapeHtml(outline.target_audience) + '</div>';
                    infoGrid.appendChild(audienceDiv);
                }
                
                if (outline.tone) {
                    const toneDiv = document.createElement('div');
                    toneDiv.style.cssText = 'padding: 12px; background: white; border-radius: 5px; border-left: 4px solid #dc3545;';
                    toneDiv.innerHTML = '<div style="font-weight: bold; color: #dc3545; margin-bottom: 5px; font-size: 14px;">🎭 Tone</div>' +
                        '<div style="color: #333; font-size: 14px;">' + escapeHtml(outline.tone) + '</div>';
                    infoGrid.appendChild(toneDiv);
                }
                
                outlineDiv.appendChild(infoGrid);
                
                // Sections list
                if (outline.sections && Array.isArray(outline.sections) && outline.sections.length > 0) {
                    const sectionsTitle = document.createElement('div');
                    sectionsTitle.style.cssText = 'font-size: 18px; font-weight: bold; color: #333; margin-bottom: 15px; margin-top: 20px;';
                    sectionsTitle.innerHTML = '📑 Sections (' + outline.sections.length + ')';
                    outlineDiv.appendChild(sectionsTitle);
                    
                    const sectionsList = document.createElement('div');
                    sectionsList.style.cssText = 'display: flex; flex-direction: column; gap: 12px;';
                    
                    outline.sections.forEach((section, index) => {
                        const sectionItem = document.createElement('div');
                        sectionItem.style.cssText = 'padding: 15px; background: white; border-radius: 5px; border-left: 4px solid #667eea; box-shadow: 0 2px 4px rgba(0,0,0,0.1);';
                        
                        let sectionHtml = '<div style="display: flex; align-items: start; gap: 10px;">';
                        sectionHtml += '<div style="flex-shrink: 0; width: 30px; height: 30px; background: #667eea; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 14px;">' + (index + 1) + '</div>';
                        sectionHtml += '<div style="flex: 1;">';
                        sectionHtml += '<div style="font-weight: bold; color: #667eea; margin-bottom: 8px; font-size: 16px;">' + escapeHtml(section.title || 'Untitled Section') + '</div>';
                        
                        if (section.description) {
                            sectionHtml += '<div style="color: #666; margin-bottom: 10px; font-size: 14px; line-height: 1.5;">' + escapeHtml(section.description) + '</div>';
                        }
                        
                        if (section.key_points && Array.isArray(section.key_points) && section.key_points.length > 0) {
                            sectionHtml += '<div style="margin-top: 10px;"><div style="font-weight: bold; color: #333; margin-bottom: 5px; font-size: 13px;">Key Points:</div><ul style="margin: 0; padding-left: 20px; color: #555; font-size: 13px;">';
                            section.key_points.forEach(point => {
                                sectionHtml += '<li style="margin-bottom: 4px;">' + escapeHtml(point) + '</li>';
                            });
                            sectionHtml += '</ul></div>';
                        }
                        
                        if (section.estimated_words) {
                            sectionHtml += '<div style="margin-top: 8px; font-size: 12px; color: #999;">📝 Estimated: ' + section.estimated_words + ' words</div>';
                        }
                        
                        sectionHtml += '</div></div>';
                        sectionItem.innerHTML = sectionHtml;
                        sectionsList.appendChild(sectionItem);
                    });
                    
                    outlineDiv.appendChild(sectionsList);
                }
                
                // Insert outline at the beginning of container
                if (container.firstChild) {
                    container.insertBefore(outlineDiv, container.firstChild);
                } else {
                    container.appendChild(outlineDiv);
                }
                
                console.log('Outline displayed successfully');
                
                if (typeof scrollToBottom === 'function') {
                    scrollToBottom();
                } else {
                    // Fallback scroll
                    setTimeout(() => {
                        outlineDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }, 100);
                }
            } else {
                console.error('Cannot display outline: missing container or data.outline', {
                    container: !!container,
                    hasData: !!data,
                    hasOutline: !!(data && data.outline)
                });
            }
            break;

        case 'progress':
            if (container && data.percentage !== undefined) {
                // Update progress if needed
                console.log('Progress: ' + data.percentage + '%');
            }
            break;

        case 'complete':
            if (data.content) {
                // Store the complete article content
                const finalContent = data.content;

                // Store in global variable for btnaddpost button
                if (typeof window !== 'undefined') {
                    window.aiautotool_content = finalContent;
                }
                // Also set global variable if it exists
                if (typeof aiautotool_content !== 'undefined') {
                    aiautotool_content = finalContent;
                }

                // Update articleContent in state for resolve
                if (state && state.setArticleContent) {
                    state.setArticleContent(finalContent);
                } else {
                    // Fallback: update the closure variable directly
                    // This will be handled by the outer scope
                }

                // Show completion message
                if (container) {
                    const completeDiv = document.createElement('div');
                    completeDiv.style.cssText = 'padding: 15px; background: #d4edda; border-left: 4px solid #28a745; border-radius: 5px; margin-top: 15px;';
                    completeDiv.innerHTML = '<strong style="color: #155724;">✓ Hoàn thành!</strong><br>Bài viết đã được tạo thành công.';
                    container.appendChild(completeDiv);

                    // Ensure article section styles are loaded
                    if (!document.getElementById('article-section-styles')) {
                        const style = document.createElement('style');
                        style.id = 'article-section-styles';
                        style.textContent = `
                            .article-section {
                                margin-bottom: 25px;
                                padding: 15px;
                                background: #ffffff;
                                border-left: 4px solid #667eea;
                                border-radius: 5px;
                                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                            }
                            .section-header {
                                font-size: 18px;
                                font-weight: bold;
                                color: #667eea;
                                margin-bottom: 15px;
                                padding-bottom: 10px;
                                border-bottom: 2px solid #e0e0e0;
                            }
                            .article-section p {
                                margin-bottom: 12px;
                                line-height: 1.8;
                                color: #333;
                            }
                            .article-section img {
                                max-width: 100%;
                                height: auto;
                                border-radius: 5px;
                                margin: 15px 0;
                                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                            }
                            .article-section h2, .article-section h3 {
                                color: #333;
                                margin-top: 20px;
                                margin-bottom: 15px;
                            }
                            .article-section ul, .article-section ol {
                                margin-left: 20px;
                                margin-bottom: 15px;
                            }
                            .article-section li {
                                margin-bottom: 8px;
                                line-height: 1.6;
                            }
                        `;
                        document.head.appendChild(style);
                    }

                    // Update only the content container after a short delay, keep analysis container intact
                    setTimeout(() => {
                        if (divId && finalContent) {
                            const contentContainer = document.getElementById('article-content-container');
                            if (contentContainer) {
                                contentContainer.innerHTML = finalContent;

                                // Show Add Post button
                                const btnAddPost = document.querySelector('.btnaddpost');
                                if (btnAddPost) {
                                    btnAddPost.style.display = 'block';
                                    btnAddPost.style.marginTop = '15px';
                                    btnAddPost.style.marginBottom = '15px';
                                }

                                if (typeof scrollToBottom === 'function') {
                                    scrollToBottom();
                                }
                            } else {
                                // Fallback: if content container doesn't exist, create it
                                const targetDiv = document.getElementById(divId);
                                if (targetDiv) {
                                    const contentDiv = document.createElement('div');
                                    contentDiv.id = 'article-content-container';
                                    contentDiv.style.cssText = 'padding: 20px; font-family: Arial, sans-serif;';
                                    contentDiv.innerHTML = finalContent;
                                    targetDiv.appendChild(contentDiv);

                                    // Show Add Post button
                                    const btnAddPost = document.querySelector('.btnaddpost');
                                    if (btnAddPost) {
                                        btnAddPost.style.display = 'block';
                                        btnAddPost.style.marginTop = '15px';
                                        btnAddPost.style.marginBottom = '15px';
                                    }

                                    if (typeof scrollToBottom === 'function') {
                                        scrollToBottom();
                                    }
                                }
                            }
                        }
                    }, 1000);
                }
            }
            break;

        case 'error':
            if (data && data.message) {
                const errorMsg = data.message;
                console.log('Error event received:', errorMsg, 'EventType:', eventType);

                if (typeof hideLoading === 'function') {
                    hideLoading();
                }

                // Always display error in container first
                if (container) {
                    // Remove any existing error messages to avoid duplicates
                    const existingErrors = container.querySelectorAll('.sse-error-message');
                    existingErrors.forEach(el => el.remove());

                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'sse-error-message';
                    errorDiv.style.cssText = 'padding: 20px; background: #f8d7da; border-left: 5px solid #dc3545; border-radius: 5px; margin: 15px 0; color: #721c24;';
                    errorDiv.innerHTML = '<div style="display: flex; align-items: center; margin-bottom: 10px;">' +
                        '<span style="font-size: 24px; margin-right: 10px;">❌</span>' +
                        '<strong style="font-size: 16px;">Error</strong>' +
                        '</div>' +
                        '<div style="line-height: 1.6; font-size: 14px; white-space: pre-wrap; word-wrap: break-word;">' +
                        escapeHtml(errorMsg) +
                        '</div>';

                    container.appendChild(errorDiv);

                    // Scroll to error message
                    setTimeout(() => {
                        errorDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        if (typeof scrollToBottom === 'function') {
                            scrollToBottom();
                        }
                    }, 100);
                }

                // Check if error is related to Pro account requirement
                const errorMsgLower = errorMsg.toLowerCase();
                const isProAccountError = errorMsgLower.includes('pro account') ||
                    errorMsgLower.includes('upgrade to pro') ||
                    errorMsgLower.includes('requires a pro') ||
                    errorMsgLower.includes('pro to use');

                console.log('Is Pro Account Error:', isProAccountError, 'Swal available:', typeof Swal !== 'undefined');

                // Show additional modal/alert for better visibility
                if (isProAccountError) {
                    // Use helper function to show upgrade prompt
                    showSwalUpgrade(errorMsg);
                } else if (typeof Swal !== 'undefined' && Swal && typeof Swal.fire === 'function') {
                    // Show Swal modal for non-Pro errors too
                    try {
                        Swal.fire({
                            title: 'Error!',
                            html: '<div style="text-align: left; padding: 10px 0;">' +
                                '<p style="margin-bottom: 10px; color: #333; font-size: 15px; white-space: pre-wrap;">' +
                                escapeHtml(errorMsg) +
                                '</p>' +
                                '</div>',
                            icon: 'error',
                            confirmButtonText: 'Close',
                            confirmButtonColor: '#dc3545',
                            allowOutsideClick: true,
                            allowEscapeKey: true
                        });
                    } catch (e) {
                        console.error('Error showing Swal:', e);
                        alert(errorMsg);
                    }
                } else if (typeof showError === 'function') {
                    showError(errorMsg);
                } else {
                    // Fallback to alert
                    alert('Error: ' + errorMsg);
                }
            } else if (data && !data.message) {
                // Handle error without message field
                const errorMsg = JSON.stringify(data);
                console.log('Error event received without message:', errorMsg);

                if (container) {
                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'sse-error-message';
                    errorDiv.style.cssText = 'padding: 20px; background: #f8d7da; border-left: 5px solid #dc3545; border-radius: 5px; margin: 15px 0; color: #721c24;';
                    errorDiv.innerHTML = '<div style="display: flex; align-items: center; margin-bottom: 10px;">' +
                        '<span style="font-size: 24px; margin-right: 10px;">❌</span>' +
                        '<strong style="font-size: 16px;">Error</strong>' +
                        '</div>' +
                        '<div style="line-height: 1.6; font-size: 14px; white-space: pre-wrap; word-wrap: break-word;">' +
                        'An error occurred. Please check the console for details.' +
                        '</div>';
                    container.appendChild(errorDiv);

                    setTimeout(() => {
                        errorDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }, 100);
                }

                if (typeof Swal !== 'undefined' && Swal && typeof Swal.fire === 'function') {
                    try {
                        Swal.fire({
                            title: 'Error!',
                            text: 'An error occurred. Please check the console for details.',
                            icon: 'error',
                            confirmButtonText: 'Close'
                        });
                    } catch (e) {
                        alert('An error occurred. Please check the console for details.');
                    }
                } else {
                    alert('An error occurred. Please check the console for details.');
                }
            }
            break;

        case 'done':
            if (typeof hideLoading === 'function') {
                hideLoading();
            }
            break;

        default:
            // Handle unknown event types - check if it's an error message
            if (data && data.message) {
                const errorMsg = data.message;
                const errorMsgLower = errorMsg.toLowerCase();
                const isProAccountError = errorMsgLower.includes('pro account') ||
                    errorMsgLower.includes('upgrade to pro') ||
                    errorMsgLower.includes('requires a pro') ||
                    errorMsgLower.includes('pro to use');

                // Display error in container
                if (container) {
                    const existingErrors = container.querySelectorAll('.sse-error-message');
                    existingErrors.forEach(el => el.remove());

                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'sse-error-message';
                    errorDiv.style.cssText = 'padding: 20px; background: #f8d7da; border-left: 5px solid #dc3545; border-radius: 5px; margin: 15px 0; color: #721c24;';
                    errorDiv.innerHTML = '<div style="display: flex; align-items: center; margin-bottom: 10px;">' +
                        '<span style="font-size: 24px; margin-right: 10px;">❌</span>' +
                        '<strong style="font-size: 16px;">Error</strong>' +
                        '</div>' +
                        '<div style="line-height: 1.6; font-size: 14px; white-space: pre-wrap; word-wrap: break-word;">' +
                        escapeHtml(errorMsg) +
                        '</div>';
                    container.appendChild(errorDiv);

                    setTimeout(() => {
                        errorDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        if (typeof scrollToBottom === 'function') {
                            scrollToBottom();
                        }
                    }, 100);
                }

                if (isProAccountError) {
                    console.log('Pro account error detected in default case');
                    // Use helper function to show upgrade prompt
                    showSwalUpgrade(errorMsg);
                } else if (typeof Swal !== 'undefined' && Swal && typeof Swal.fire === 'function') {
                    try {
                        Swal.fire({
                            title: 'Error!',
                            html: '<div style="text-align: left; padding: 10px 0;">' +
                                '<p style="margin-bottom: 10px; color: #333; font-size: 15px; white-space: pre-wrap;">' +
                                escapeHtml(errorMsg) +
                                '</p>' +
                                '</div>',
                            icon: 'error',
                            confirmButtonText: 'Close',
                            confirmButtonColor: '#dc3545'
                        });
                    } catch (e) {
                        alert('Error: ' + errorMsg);
                    }
                } else {
                    alert('Error: ' + errorMsg);
                }
            }
            console.log('Unknown event type:', normalizedEventType, 'data:', data);
            break;
    }
}
