

document.querySelectorAll(".nav-tab").forEach(tab => {
    tab.addEventListener("click", function() {
        // Lưu trạng thái tab đã chọn vào localStorage
        localStorage.setItem("selectedTab", this.getAttribute("href"));
    });
});
function aiautotool_checklimit(config) {
    return (config.quota !== -1 && config.quota >= config.usage) || config.quota === -1;
}

function showLoading(title='') {
    // Check if Swal is available, otherwise use fallback
    if (typeof Swal !== 'undefined' && Swal) {
        Swal.fire({
            title: title || 'Loading...',
            html:'<div class="loaderbar"></div>',
            icon: '',
            showConfirmButton: false,
            allowOutsideClick: false,
            allowEscapeKey: false
        });
    } else {
        // Fallback: Show simple loading message
        console.log('Loading: ' + (title || 'Please wait...'));
        // Create a simple loading overlay if needed
        if (!document.getElementById('aiautotool-loading-overlay')) {
            var overlay = document.createElement('div');
            overlay.id = 'aiautotool-loading-overlay';
            overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:999999;display:flex;align-items:center;justify-content:center;color:#fff;font-size:18px;';
            overlay.innerHTML = '<div>' + (title || 'Loading...') + '</div>';
            document.body.appendChild(overlay);
        }
    }
}

function hideLoading() {
    if (typeof Swal !== 'undefined' && Swal) {
        Swal.close();
    } else {
        // Remove fallback overlay if exists
        var overlay = document.getElementById('aiautotool-loading-overlay');
        if (overlay) {
            overlay.remove();
        }
    }
}

function aiautotool_alert_success(title, message) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: title || 'Success!',
            text: message || 'Success',
            icon: 'success',
            confirmButtonText: 'OK'
        });
    } else {
        alert((title || 'Success!') + '\n' + (message || 'Success Ok.'));
    }
}


function aiautotool_alert_error(title, message) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: title || 'Error!',
            text: message || 'An error has occurred. Please try again.',
            icon: 'error',
            confirmButtonText: 'OK'
        });
    } else {
        alert((title || 'Error!') + '\n' + (message || 'An error has occurred. Please try again..'));
    }
}

function decodeHtmlEntities(text) {
    var entities = [
        ['amp', '&'],
        ['apos', '\''],
        ['lt', '<'],
        ['gt', '>'],
        ['quot', '"'],
        ['#39', '\''],
        ['#x27', '\''],
        ['#x2F', '/'],
        ['#x60', '`'],
        ['#x3D', '=']
    ];

    for (var i = 0; i < entities.length; i++) {
        text = text.replace(new RegExp('&'+entities[i][0]+';', 'g'), entities[i][1]);
    }

    return text;
}

function aiautotool_fix_question(prompt, title = '', lang = '', blog = '', cate = '', content = '') {
    // Create an object with keys being the placeholders and values being the actual values
    const replacements = {
        '%%title%%': title,
        '%%lang%%': lang,
        '%%blog%%': blog,
        '%%cate%%': cate,
        '%%content%%': content
    };

    // Replace placeholders in prompt with actual values
    let outprompt = prompt;
    for (const key in replacements) {
        if (Object.hasOwnProperty.call(replacements, key)) {
            outprompt = outprompt.replace(new RegExp(key, 'g'), replacements[key]);
        }
    }

    // Return the modified string
    return outprompt;
}

/**
 * Check if user has premium access (Pro or Trial)
 * @returns {boolean} True if user has premium access (pro or trial), false otherwise
 */
function check_aipost_premium() {
    if (typeof aiautotool_js_setting === 'undefined') {
        return false;
    }

    if (aiautotool_js_setting.freemius_access && typeof aiautotool_js_setting.freemius_access.can_use_pro_features !== 'undefined') {
        return !!aiautotool_js_setting.freemius_access.can_use_pro_features;
    }

    if (typeof aiautotool_js_setting.aiautotool_premium !== 'undefined') {
        return !!aiautotool_js_setting.aiautotool_premium;
    }

    return false;
}

// Make function globally accessible
if (typeof window !== 'undefined') {
    window.check_aipost_premium = check_aipost_premium;
}

function update_usage() {
    var data = {
        action: 'update_usage',
        security: aipost.security
    };

    jQuery.post(aipost.ajax_url, data, function (response) {
        if (response.success) {
            console.log('Update usage successfully.');
        } 
    });
}

const languageCodes = aiautotool_js_setting.languageCodes;

let langcheck = aiautotool_js_setting.langcodedefault;
let hostname = getCurrentDomain();

var post = [];
let indexnow = 0;
let istrue = true;
let question = '';

var divids = 'outbard';
const url = aiautotool_js_setting.ajax_url;

function fttab(evt, tabname) {
  var i, x, sotab;
  x = document.getElementsByClassName("ftbox");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";  
  }
  sotab = document.getElementsByClassName("sotab");
  for (i = 0; i < x.length; i++) {
    sotab[i].className = sotab[i].className.replace(" sotab-select", "");
  }
  document.getElementById(tabname).style.display = "block";
  evt.currentTarget.className += " sotab-select";
  localStorage.setItem('selectedRank', tabname);
}
class ContentOb {
                    constructor(url, question, lang) {
                        this.url = url;
                        this.question = question;
                        this.lang = lang;
                        this.outline = [];
                        this.listhead = [];
                    }

                    async createOutline() {
                        try {
                            const outlinePrompt = 'Create a JSON array of 5 to 7 concise H2 headings for an article about: "' + this.question + '". Respond only with valid JSON array, no markdown, no explanation. Language: ' + this.lang + '.';
                            const responseData = await jQuery.ajax({
                                url: aiautotool_js_setting.ajax_url,
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    action: 'aiautotool_bard_content',
                                    security: aiautotool_js_setting.security,
                                    data: JSON.stringify({
                                        question: outlinePrompt,
                                        lang: this.lang,
                                        model: 'provider-default'
                                    })
                                }
                            });

                            if (!responseData || String(responseData.code) !== '200' || !responseData.result) {
                                throw new Error((responseData && responseData.msg) ? responseData.msg : 'Invalid outline response');
                            }

                            let outlineJson = responseData.result;
                            outlineJson = String(outlineJson)
                                .replace(/```json/gi, '')
                                .replace(/```/g, '')
                                .replace(/<\/?[^>]+(>|$)/g, '')
                                .trim();

                            if (outlineJson) {
                                this.outline = JSON.parse(outlineJson);
                                jQuery(".loadingprocess").addClass("d-none");
                                for (const key in this.outline) {
                                    if (this.outline.hasOwnProperty(key)) {
                                        var headertitle = this.outline[key];
                                        this.listhead.push(headertitle);
                                        var item = {
                                            key: key,
                                            h2: headertitle,
                                            desc: '',
                                            stext: ''
                                        };
                                        post.push(item);
                                    }
                                }
                                if (!Array.isArray(this.listhead)) {
                                    throw new Error('Invalid response data format: outline is not an array');
                                }
                            } else {
                                throw new Error('Invalid response data format');
                            }
                        } catch (error) {
                            console.error('Error creating outline:', error.message);
                        }
                    }
                }
function getCurrentDomain() {
    // Lấy đối tượng URL của trang hiện tại
    var currentUrl = new URL(window.location.href);

    // Lấy phần hostname từ URL
    var currentDomain = currentUrl.hostname;

    return currentDomain;
}


// Tìm div có class aiautotool_left
var aiautotoolLeft = document.querySelector('.aiautotool_left');

// Kiểm tra xem có div aiautotool_left không
if (aiautotoolLeft) {
    // Lấy giá trị top của div aiautotool_left
    var topPosition = aiautotoolLeft.getBoundingClientRect().top;

    // Tìm div có class aiautotool-fixed
    var aiautotoolFixed = document.querySelector('.aiautotool-fixed');

    // Kiểm tra xem có div aiautotool-fixed không
    if (aiautotoolFixed) {
        // Đặt giá trị top của div aiautotool-fixed
        if(topPosition<=0){
            topPosition = 50;
        }
        aiautotoolFixed.style.top =  '50px';
    }
}

var aiautotoolFixed = document.querySelector('.aiautotool-fixed');

// Xác định màn hình có thay đổi kích thước khi cuộn hay không
var isScreenResized = false;

window.addEventListener('resize', function () {
    isScreenResized = true;
});

window.addEventListener('scroll', function () {
    if(aiautotoolFixed){
        var topPosition = aiautotoolFixed.getBoundingClientRect().top;

        // Kiểm tra xem top của aiautotool-fixed có cao hơn chiều cao của màn hình không
        var isTopHigherThanScreen = topPosition < 0;

        // Nếu màn hình đã thay đổi kích thước (resize) hoặc top của aiautotool-fixed cao hơn màn hình
        if (isScreenResized || isTopHigherThanScreen) {
            // Đặt position là 'absolute'
            aiautotoolFixed.style.position = 'absolute';
        } else {
            // Đặt position là 'fixed'
            aiautotoolFixed.style.position = 'fixed';
        }

        // Đặt lại biến isScreenResized
        isScreenResized = false;
    }
    // Lấy giá trị top của div aiautotool-fixed
    
});
 var aiautotool_content = '';
function openTab(tabName) {
    // Check if a tab with the given ID exists
    if (document.getElementById(tabName)) {
        // Declare all variables
        var i, tabcontent, tablinks;

        // Get all elements with class="tabcontent" and hide them
        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }

        // Get all elements with class="tablinks" and remove the class "active"
        tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }

        // Show the current tab, and add an "active" class to the button that opened the tab
        document.getElementById(tabName).style.display = "block";
        jQuery('[data-tab="' + tabName + '"]').addClass("active");
    } else {
        
        console.log('Tab with ID "' + tabName + '" does not exist.');
        // Handle the case where the tab doesn't exist (e.g., show an error message)
    }
}

jQuery(document).ready(function($) {
    // Ẩn toàn bộ các tab content
    const selectedTab = localStorage.getItem("selectedTab");

    $('.tab-content').hide();

    // Hiển thị tab content đầu tiên
    if (selectedTab) {
        var selectedTabWithoutHash = selectedTab.replace("#", "");
        // Validate ID: chỉ cho phép chữ, số, dấu gạch dưới, gạch ngang (tránh URL hoặc ký tự đặc biệt)
        var isValidId = /^[a-zA-Z0-9_-]+$/.test(selectedTabWithoutHash);
        
        if (isValidId && $("#" + selectedTabWithoutHash).length) {
            $('.tab-content').hide();
            $("#" + selectedTabWithoutHash).show();
            var selector = `button[href="${selectedTab}"]`;
            $(selector).addClass('nav-tab-active');
        } else {
            // Nếu không tồn tại id selectedTab, tìm button đầu tiên trong div ft-menu và click vào nó
            var firstButton = $('.ft-menu button').first();
            // firstButton.click();
            var firstTab = $(firstButton.attr('href'));

            firstTab.show();
            firstButton.addClass('nav-tab-active');
            console.log(firstButton.attr('href'));
        }
    } else {
        
        if (document.getElementById('tab-setting')) {
            document.getElementById('tab-setting').style.display = "block";
        }
    }

    $('.nav-tab').click(function(event) {
        event.preventDefault();
        var tabText = $(this).text();
        $('#titlehead').text(tabText);

        var tab_id = $(this).attr('href');

        $('.tab-content').hide();

        $(tab_id).show();
        $('.nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');
    });
});




 function bard_gen_content(button) {
    var post_id = button.getAttribute('data-id');
    var customButton = button;
    var loadingButton = document.getElementById('loading-icon');
    customButton.classList.add('disabled');
    customButton.style.display = 'none';
    loadingButton.style.display = 'block';
  jQuery.ajax({
        url: '/wp-json/aiautotool/v1/createcontentbard', 
        method: 'POST',
        data: {
            post_id: post_id
        },
        success: function(response) {
            // Xử lý phản hồi từ REST route
            // var responseData = JSON.parse(response);
            var url = response.data;

            // Mở tab mới với URL
            // window.open(url, '_blank');
             loadingButton.style.display = 'none';
            customButton.classList.remove('disabled');
            customButton.style.display = 'block';

             Swal.fire({
                    title: 'Thành công',
                    html:
                      '<a class="btn btn-block btn-danger btn-sm" target="_blank" href="'+url+'">Xem Bài viết</a>',
                    icon: 'success',
                    confirmButtonText: 'Đóng'
                  }).then((result) => {
                     
                  })
        },
        error: function(error) {
            // Xử lý lỗi nếu có
            alert('Lỗi: ' + error.responseText);
             loadingButton.style.display = 'none';
            customButton.classList.remove('disabled');
            customButton.style.display = 'block';
        }
    });
}



document.addEventListener('DOMContentLoaded', function () {
    var titleInput = document.getElementById('aiautotool_title');
    var slugInput = document.getElementById('aiautotool_slug');

    if (titleInput && slugInput) {
        titleInput.addEventListener('blur', function () {
            var titleValue = titleInput.value;
            var slugValue = sanitizeTitle(titleValue);
           
        });

        function sanitizeTitle(title) {
            // Gửi AJAX request đến WordPress để lấy slug
            return wp.ajax.post('aiautotool_get_slug', {
                title: title,
            }).done(function (response) {
                slugInput.value = response.slug;
                
            });
        }
    }
});






function create_buttoneditor(){
   


}




// Improved Typing Effect System
var aiautotool_typing_instances = {};

function checkAndCallPlaceholderStreaming() {
  // Find all elements with placeholdertext attribute
  var allElements = document.querySelectorAll('[placeholdertext]');
  
  allElements.forEach(function(element) {
    if (element.id) {
      placeholderStreaming(element.id);
    }
  });
}

// Call when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', checkAndCallPlaceholderStreaming);
} else {
  checkAndCallPlaceholderStreaming();
}

function placeholderStreaming(elementId, speed = 50, interval = 10000) {
    var element = document.getElementById(elementId);
    if (!element) return;
    
    var placeholderText = element.getAttribute('placeholdertext');
    if (!placeholderText) return;
    
    // Clear any existing instance
    if (aiautotool_typing_instances[elementId]) {
        clearInterval(aiautotool_typing_instances[elementId].interval);
        clearTimeout(aiautotool_typing_instances[elementId].timeout);
    }
    
    var placeholders = placeholderText.split(',').map(function(text) {
        return aiwa_removeNumbers2(text).trim();
    }).filter(function(text) {
        return text.length > 0;
    });
    
    if (placeholders.length === 0) return;
    
    // Initialize instance
    aiautotool_typing_instances[elementId] = {
        element: element,
        placeholders: placeholders,
        currentIndex: 0,
        timeouts: [],
        interval: null
    };
    
    // Type first text immediately
    var firstIndex = aiautotool_rand2(0, placeholders.length - 1);
    aiautotool_typeText(elementId, placeholders[firstIndex], speed);
    
    // Set up interval for rotating texts
    aiautotool_typing_instances[elementId].interval = setInterval(function() {
        if (!document.getElementById(elementId)) {
            // Element no longer exists, cleanup
            clearInterval(aiautotool_typing_instances[elementId].interval);
            delete aiautotool_typing_instances[elementId];
            return;
        }
        
        var instance = aiautotool_typing_instances[elementId];
        var randomIndex = aiautotool_rand2(0, instance.placeholders.length - 1);
        aiautotool_typeText(elementId, instance.placeholders[randomIndex], speed);
    }, interval);
}

function aiautotool_typeText(elementId, text, speed = 50) {
    var element = document.getElementById(elementId);
    if (!element || !text) return;
    
    var instance = aiautotool_typing_instances[elementId];
    if (!instance) return;
    
    // Clear any pending timeouts
    if (instance.timeouts) {
        instance.timeouts.forEach(function(timeout) {
            clearTimeout(timeout);
        });
        instance.timeouts = [];
    }
    
    var tagName = element.tagName.toLowerCase();
    var isInputLike = tagName === 'input' || tagName === 'textarea';
    
    // Clear current content
    if (isInputLike) {
        element.setAttribute('placeholder', '');
    } else {
        element.textContent = '';
        element.style.color = '#9ca3af'; // Placeholder color
        element.style.fontStyle = 'italic';
    }
    
    // Type each character
    var chars = text.split('');
    chars.forEach(function(char, index) {
        var timeout = setTimeout(function() {
            if (!document.getElementById(elementId)) return; // Safety check
            
            if (isInputLike) {
                var current = element.getAttribute('placeholder') || '';
                element.setAttribute('placeholder', current + char);
            } else {
                element.textContent += char;
            }
        }, index * speed);
        
        instance.timeouts.push(timeout);
    });
}

function aiautotool_rand2(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function aiwa_removeNumbers2(text) {
    if (!text) return '';
    return text.replace(/^\d+[\.\)]\s*/g, '').trim();
}

// Cleanup on page unload
window.addEventListener('beforeunload', function() {
    Object.keys(aiautotool_typing_instances).forEach(function(key) {
        var instance = aiautotool_typing_instances[key];
        if (instance.interval) clearInterval(instance.interval);
        if (instance.timeouts) {
            instance.timeouts.forEach(function(timeout) {
                clearTimeout(timeout);
            });
        }
    });
});


function setcontent(content){
     var activeEditor = tinyMCE.get('content');
    // var content = 'HTML or plain text content here...';
    if(jQuery('#wp-content-wrap').hasClass('html-active')){ // We are in text mode
        jQuery('#content').val(content); // Update the textarea's content
    } else { // We are in tinyMCE mode
        var activeEditor = tinyMCE.get('content');
        if(activeEditor!==null){ // Make sure we're not calling setContent on null
            activeEditor.setContent(content); // Update tinyMCE's content
        }
    }
  }

jQuery(document).ready(function ($) {

    async function checkAndDoSomething() {
                    open_box_aiautotool();
                    question = get_title().value;

                    if (question.trim() === '') {
                         if(Swal){
                                 Swal.fire({
                                                  title: 'Error!',
                                                  text: 'Please fill a title:\n' ,
                                                  icon: 'error',
                                                  confirmButtonText: 'Close'
                                                });
                                     }else{
                                         alert('Please enter a title!');
                                     }
                       
                    } else {

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

                          lang = get_lang();
                            if (languageCodes.hasOwnProperty(post_language)) {
                               lang = languageCodes[post_language];
                              
                            } 

                        if (document.querySelector('.aiautotool_tab')) {
                            openTab('aiContentTab');
                            // showProcess();
                            showLoading();
                            const contentOb = new ContentOb(url, question, lang);
                            await contentOb.createOutline();
                            console.log(contentOb.listhead);
                        }
                    }
    }
   
    // Event listener for the "Bard write" button
    $('.bard-write').on('click', function () {

        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;
            }
        // Check if the title is filled
        var titleValue = get_title().value;
        
        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 fill in the title.',
                          icon: 'error',
                          confirmButtonText: 'Close'
                        });
             }else{
                alert('Please fill in the title.');
             }
            
            return;
        }
         // $(this).prop('disabled', true);

         

          var divId = "outbard"; // Thay đổi ID của div tại đây
          var post_language = jQuery('#post_language').val();

            if (languageCodes.hasOwnProperty(post_language)) {
               langcheck = languageCodes[post_language];
              
            } 
          var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
          prompt_article = aiautotool_fix_question(prompt_article,titleValue,langcheck);
          sendbardToServer(prompt_article, divId,'writefull',langcheck,'gemini');
          
    });

    $('.chatgpt-write').on('click', function () {

        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;
            }
        // Check if the title is filled
        var titleValue = get_title().value;
        
        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 fill in the title.',
                          icon: 'error',
                          confirmButtonText: 'Close'
                        });
             }else{
                alert('Please fill in the title.');
             }
            
            return;
        }
         // $(this).prop('disabled', true);

         

          var divId = "outbard"; // Thay đổi ID của div tại đây
          var post_language = jQuery('#post_language').val();

            if (languageCodes.hasOwnProperty(post_language)) {
               langcheck = languageCodes[post_language];
              
            } 
          var prompt_article = aiautotool_js_setting.prompt.aiautotool_prompt_artcile;
          prompt_article = aiautotool_fix_question(prompt_article,titleValue,langcheck);
          sendbardToServer(prompt_article, divId,'writefull',langcheck,'');
          
    });



    $('#askprompt').on('click', function () {
        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;
                        }

        var titleValue = $('#promptask').val();
        
        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;
        }

        var askAI = $(this).closest('.askassistant').find('[data-aiautotool-ai-select="ask"]').val() || '';

        if (!titleValue.trim()) {
            if(Swal){
                 Swal.fire({
                          title: 'Error!',
                          text: 'Please fill in Your Prompt.',
                          icon: 'error',
                          confirmButtonText: 'Close'
                        });
             }else{
                alert('Please fill in Your Prompt.');
             }
            
            return;
        }
         // $(this).prop('disabled', true);

         

          var divId = "outbard"; // Thay đổi ID của div tại đây
          var post_language = jQuery('#post_language').val();

            if (languageCodes.hasOwnProperty(post_language)) {
               langcheck = languageCodes[post_language];
              
            } 
        var selectedModel = askAI || '';
        sendbardToServer(titleValue, divId,'writemore',langcheck,selectedModel);
        
    });
     $('.chatgpt-long-write').on('click', function () {
        // Check if the title is filled

        checkAndDoSomething();
    });


     $('.btn_suggettitle').on('click', function () {
        // Check if the title is filled
        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;
                        }
        var titleValue = get_title();
        var post_language = get_lang();
        console.log(post_language);
        if (!titleValue.value.trim()) {
            if(Swal){
                 Swal.fire({
                          title: 'Error!',
                          text: 'Please fill Key for sugget in input title.',
                          icon: 'error',
                          confirmButtonText: 'Close'
                        });
             }else{
                alert('Please fill in the title.');
             }
            
            return;
        }
         $(this).prop('disabled', true);
         showLoading('Suggest title');
        $.ajax({
            url: aiautotool_data.ajax_url,
            method: 'POST',
            data: {
                 action: 'bard_content',
                title: titleValue.value,
                post_language:post_language,
                ac:'suggettitle'
                // Add any other data you need to send to the API
            },
            success: function (response) {
                // Display the result in the 'outbard' div
               console.log(response);
               titleValue.value = response.data.content;
               hideLoading();
               
            },
            error: function () {
                hideLoading();
                alert('An error occurred during the API call.');
            },
            complete: function () {
                // Re-enable the button after AJAX call is complete
                hideLoading();
                $(this).prop('disabled', false);
                // $('#loading-icon').remove();
            }
        });
    });


    $('.btnaddpost').on('click', function () {
        // Check if the title is filled
       
      event.preventDefault();

          $('#outbard').html('');
             
          
          tinymce.activeEditor.insertContent(aiautotool_content);
          $('.btnaddpost').hide();
          return false;
    });
 
    // Only call openTab if the element exists
    if (document.querySelector('.aiautotool_tab')) {
        openTab('aiContentTab');
        // Event listeners for tab buttons
        $('.aiautotool_tab button').on('click', function () {
            var tabName = $(this).data('tab');
            openTab(tabName);
        });
    }



 $("body").on("click", ".img_search", function(res) {
    res.preventDefault();
    let imgSrc = $(this).attr("data-src");
    let imgBox = `<p class="imageBox"><img class="aligncenter" src="${imgSrc}"></p>`;
    tinymce.activeEditor.insertContent(imgBox);
    

    
});

});




jQuery(document).ready(function ($) {
    var postForm = $('#aiautotool_post_form');

    postForm.submit(function (event) {
        event.preventDefault(); // Prevent the default form submission

        // Check if required fields are filled
        var missingFields = checkFields();

        if (missingFields.length > 0) {
            // Alert with specific missing fields
            if(Swal){
                 Swal.fire({
                                  title: 'Error!',
                                  text: 'Please fill in the following fields:\n' + missingFields.join(', '),
                                  icon: 'error',
                                  confirmButtonText: 'Close'
                                });
                     }else{
                        alert('Please fill in the following fields:\n' + missingFields.join(', '));
                     }
            return;
        }
        Swal.fire({
                title:"", 
                text:"Loading...",
                icon: "https://www.boasnotas.com/img/loading2.gif",
                buttons: false,      
                closeOnClickOutside: false,
                timer: 3000,
                //icon: "success"
            });
        // Retrieve form data
        var formData = postForm.serialize();

        // Example: Add additional data to formData if needed
        formData += '&additional_key=additional_value';

        // Add the security nonce
        formData += '&security=' + aiautotool_js_setting.security;
         formData += '&action=save_post_data';
        // Call your plugin's AJAX endpoint
        $.ajax({
            url: aiautotool_js_setting.ajax_url,
            type: 'POST',
            data: formData,
            success: function (response) {
                // Handle the success response from the server
                console.log(response);
                if (response.success) {
                    // Success response
                    if(Swal){

                        Swal.fire({
                            title: 'Thành công',
                            html:
                              'Post successfully saved and published. <a class="btn btn-block btn-danger btn-sm" target="_blank" href="'+response.data.post_url+'">View Post</a>',
                            icon: 'success',
                            confirmButtonText: 'Đóng'
                          }).then((result) => {
                             
                          })

                         
                             }else{
                                alert('Post successfully saved and published!');
                             }
                    
                    // Display the post URL
                    console.log('Post URL:', response.data.post_url);
                } else {
                    // Error response
                    alert('Error: ' + response.data);
                }
            },
            error: function (error) {
                // Handle errors
                console.error('Error:', error);
            }
        });
    });

    // Function to check if required fields are filled
     function checkFields() {
        var titleInput = document.getElementById('aiautotool_title');
        var categoriesCheckboxes = document.querySelectorAll('[name="post_category[]"]');
        var contentInput = document.getElementById('aiautotool_content');

        var missingFields = [];

        // Check each field and add to missingFields if empty
        if (!titleInput.value.trim()) {
            missingFields.push('Title');
        }

        var selectedCategories = Array.from(categoriesCheckboxes).some(checkbox => checkbox.checked);

        if (!selectedCategories) {
            missingFields.push('Categories');
        }

        if (!contentInput.value.trim()) {
            missingFields.push('Content');
        }

        return missingFields;
    }
});




// chatgpt config

function removeMaskData(dataText){if(dataText){if(typeof dataText==='string'||dataText instanceof String){dataText=dataText.replaceAll('Stop article','');dataText=dataText.replaceAll('{stop article}','');dataText=dataText.replaceAll('{stop}','');dataText=dataText.replaceAll('{start}','');dataText=dataText.replaceAll('{done}','');dataText=dataText.replaceAll('{---end---}','');dataText=dataText.replaceAll('---end---','');dataText=dataText.replaceAll('--end--','');dataText=dataText.replaceAll('-end-','');dataText=dataText.replaceAll('ChatGPT','');dataText=dataText.replaceAll('chatGPT','');return dataText;}}}
function replaceH1WithH2(text) {
  // Sử dụng biểu thức chính quy (regular expression) để thay thế tất cả các thẻ <h1> thành <h2>
  return text.replace(/<h1>/g, "<h2>").replace(/<\/h1>/g, "</h2>");
}
function sendTextToServer(text, divId,option,lang) {
    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;
    }
}

function aiautotoolResolveAiRoute(model) {
    var 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) {
        var parts = route.model.split('::');
        route.provider_id = parts.shift() || '';
        route.model = parts.join('::') || '';
    }

    return route;
}

function sendbardToServer(text, divId,option,lang,model='') {
    return new Promise((resolve, reject) => {
        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.');
             }
            
            reject(new Error('AI Post Limit Quota. Please Upgrade Pro.'));
            return;
        }


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

        // Map option to WordPress AJAX action
        var ajaxAction = 'aiautotool_bard_content';
        switch(option){
            case 'writefull':
                ajaxAction = 'aiautotool_bard_contentmore';
                break;
            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 urlapi = aiautotool_js_setting.ajax_url;
        
       jQuery.ajax({
          type: "POST",
          url: urlapi,
          data: {
              action: ajaxAction,
              data: jsonData,
              security: (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) ? aiautotool_js_setting.security : ''
          },
          success: function(data) {
             hideLoading();
             
            // Debug: Log full API response
            console.log('=== API Response Debug ===');
            console.log('Full Response:', data);
            console.log('Response Code:', data.code);
            console.log('Response Message:', data.msg);
            console.log('Result Length:', data.result ? data.result.length : 0);
            if (data.debug) {
                console.log('Debug Info:', data.debug);
            }
            
            // Alert API response info (for debugging)
            if (window.location.search.indexOf('debug_api=1') !== -1 || (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.debug_api)) {
                var debugInfo = 'API Response:\n\n';
                debugInfo += 'Code: ' + (data.code || 'N/A') + '\n';
                debugInfo += 'Message: ' + (data.msg || 'N/A') + '\n';
                debugInfo += 'Result Length: ' + (data.result ? data.result.length : 0) + ' chars\n';
                if (data.debug) {
                    debugInfo += '\nDebug Info:\n';
                    debugInfo += JSON.stringify(data.debug, null, 2);
                }
                alert(debugInfo);
            }
            
            // Check if data is valid
            if (!data || typeof data !== 'object') {
                var errorMsg = 'Invalid response from server';
                console.error('Invalid API Response:', data);
                if(Swal){
                     Swal.fire({
                              title: 'Error!',
                              text: errorMsg,
                              icon: 'error',
                              confirmButtonText: 'Close'
                            });
                 }else{
                    alert(errorMsg);
                 }
                reject(new Error(errorMsg));
                return;
            }
            
            // Check if code is 200 (as string or number)
            var code = data.code;
            var isSuccess = (code == '200' || code == 200) && data.result && data.result !== false;
            
            if(isSuccess){
                console.log('API Success - Result preview:', data.result ? data.result.substring(0, 200) : 'No result');
                
                // Process result: decode HTML entities if needed, then process markdown
                var processedResult = data.result || '';
                
                // Decode HTML entities using virtual DOM
                if (typeof processedResult === 'string' && processedResult.length > 0) {
                    var hasEntities = processedResult.indexOf('&lt;') !== -1 || processedResult.indexOf('&gt;') !== -1 || 
                                     processedResult.indexOf('&amp;') !== -1 || processedResult.indexOf('&#') !== -1;
                    var hasPlainHTML = /<[a-z][\s\S]*>/i.test(processedResult);
                    
                    // Decode entities if present
                    if (hasEntities) {
                        // If has plain HTML, decode entities but keep HTML structure
                        // If no plain HTML, decode all entities
                        var div = document.createElement('div');
                        div.innerHTML = processedResult;
                        processedResult = div.innerHTML;
                    }
                }

                // Check if content already has HTML - if yes, use directly, otherwise process markdown
                var hasPlainHTML = /<[a-z][\s\S]*>/i.test(processedResult);
                if (hasPlainHTML) {
                    // Content already has HTML, use directly (skip markdown processing)
                    aiautotool_content = replaceH1WithH2(removeMaskData(processedResult));
                } else {
                    // Process through markdown and other transformations
                    aiautotool_content = replaceH1WithH2(markdown(removeMaskData(processedResult)));
                }
                // jQuery(`#${divId}`).innerHTML = aiautotool_content;
                jQuery(`#${divId}`).html(aiautotool_content);
                scrollToBottom();
                jQuery('.btnaddpost').show();
                jQuery(".div_proccess").addClass("d-none");
                jQuery(".loadingprocess").addClass("d-none");
               
                update_usage();
                resolve(data.result);
            }else{
                // Display error message from API response
                var errorMsg = data.msg || 'Failed to generate content';
                var errorCode = data.code || 'Unknown';
                
                console.error('API Error Code:', errorCode);
                console.error('API Error Message:', errorMsg);
                console.error('Full Error Response:', data);
                
                // Hide loading indicators
                jQuery(".div_proccess").addClass("d-none");
                jQuery(".loadingprocess").addClass("d-none");
                
                // Show error alert/Swal with 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{
                    alert(errorMsg);
                    reject(new Error(errorMsg));
                 }
            }
            
          },
          error: function(jqXHR, textStatus, errorThrown) {
            hideLoading();
            console.error("=== AJAX Error Debug ===");
            console.error("Status:", textStatus);
            console.error("Error:", errorThrown);
            console.error("Response:", jqXHR.responseText);
            console.error("Status Code:", jqXHR.status);
            console.error("Full XHR Object:", jqXHR);
            
            var errorMsg = errorThrown || textStatus || 'Network error occurred';
            if (window.location.search.indexOf('debug_api=1') !== -1 || (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.debug_api)) {
                var debugError = 'AJAX Error:\n\n';
                debugError += 'Status: ' + textStatus + '\n';
                debugError += 'Error: ' + errorThrown + '\n';
                debugError += 'HTTP Code: ' + jqXHR.status + '\n';
                debugError += 'Response: ' + (jqXHR.responseText ? jqXHR.responseText.substring(0, 500) : 'No response');
                alert(debugError);
            }
            
            reject(new Error(errorMsg));
          }
        });
    });
}


function reformatHTML(htmlRes){
            if (typeof htmlRes === 'string' || htmlRes instanceof String){
                htmlRes = htmlRes.replaceAll('```html\n','');
                htmlRes = htmlRes.replaceAll('```','');
                htmlRes = htmlRes.trim();
                if (htmlRes.substr(0,1) == '"') htmlRes = htmlRes.substr(1);
                if (htmlRes.slice(-1) == '"') htmlRes = htmlRes.slice(0,-1);

                if (htmlRes.indexOf("</") == -1){
                    if (htmlRes.indexOf("\n") > -1){
                        htmlRes = "<p>" + htmlRes + "</p>";
                        htmlRes = htmlRes.replace(/\r\n\r\n/g, "</p><p>").replace(/\n\n/g, "</p><p>");
                        htmlRes = htmlRes.replace(/\r\n/g, "<br />").replace(/\n/g, "<br />");
                    }
                }
                return htmlRes;
            }else{
                return htmlRes;
            }
        }

function sendbardToServerrewrite(text, divId,option,lang,tone='') {
    return new Promise((resolve, reject) => {
        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.');
             }
            
            reject(new Error('AI Post Limit Quota. Please Upgrade Pro.'));
            return;
        }
        showProcess();
        // Map option to WordPress AJAX action
        var ajaxAction = 'aiautotool_bard_content';
        switch(option){
            case 'writefull':
                ajaxAction = 'aiautotool_bard_contentmore';
                break;
            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 urlapi = aiautotool_js_setting.ajax_url;
        var dataToSend = {
          question: text,
          lang: lang,
          toneOfVoice:tone,
          domain:aiautotool_js_setting.fsdata.domain,
          info:aiautotool_js_setting.fsdata
        };
        // Only log in debug mode
        if (window.location.search.indexOf('debug_api=1') !== -1 || (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.debug_api)) {
            console.log('Data to send (Rewrite):', dataToSend);
        }
        var jsonData = JSON.stringify(dataToSend);
       jQuery.ajax({
      type: "POST",
      url: urlapi,
      data: {
          action: ajaxAction,
          data: jsonData,
          security: (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) ? aiautotool_js_setting.security : ''
      },
      success: function(data) {
        // Debug: Log full API response
        console.log('=== API Response Debug (Rewrite) ===');
        console.log('Full Response:', data);
        console.log('Response Code:', data.code);
        console.log('Response Message:', data.msg);
        console.log('Result Length:', data.result ? data.result.length : 0);
        if (data.debug) {
            console.log('Debug Info:', data.debug);
        }
        
        // Alert API response info (for debugging)
        if (window.location.search.indexOf('debug_api=1') !== -1 || (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.debug_api)) {
            var debugInfo = 'API Response (Rewrite):\n\n';
            debugInfo += 'Code: ' + (data.code || 'N/A') + '\n';
            debugInfo += 'Message: ' + (data.msg || 'N/A') + '\n';
            debugInfo += 'Result Length: ' + (data.result ? data.result.length : 0) + ' chars\n';
            if (data.debug) {
                debugInfo += '\nDebug Info:\n';
                debugInfo += JSON.stringify(data.debug, null, 2);
            }
            alert(debugInfo);
        }
        
        // Check if code is 200 (as string or number)
        var code = data.code;
        var isSuccess = (code == '200' || code == 200) && data.result && data.result !== false;
        
        if (isSuccess) {
            console.log('API Success (Rewrite) - Result preview:', data.result.substring(0, 200));
            
            // Process result: decode HTML entities if needed
            var processedResult = data.result || '';
            
            // Decode HTML entities using virtual DOM
            if (typeof processedResult === 'string' && processedResult.length > 0) {
                var hasEntities = processedResult.indexOf('&lt;') !== -1 || processedResult.indexOf('&gt;') !== -1 || 
                                 processedResult.indexOf('&amp;') !== -1 || processedResult.indexOf('&#') !== -1;
                
                // Decode entities if present
                if (hasEntities) {
                    var div = document.createElement('div');
                    div.innerHTML = processedResult;
                    processedResult = div.innerHTML;
                }
            }

            // Check if content already has HTML - if yes, use directly, otherwise process markdown
            var hasPlainHTML = /<[a-z][\s\S]*>/i.test(processedResult);
            if (hasPlainHTML) {
                // Content already has HTML, use directly (skip markdown processing)
                aiautotool_content = decodeHtmlEntities(replaceH1WithH2(removeMaskData(reformatHTML(processedResult))));
            } else {
                // Process through markdown and other transformations
                aiautotool_content = decodeHtmlEntities(replaceH1WithH2(markdown(removeMaskData(reformatHTML(processedResult)))));
            }
            // jQuery(`#${divId}`).innerHTML = aiautotool_content;
            jQuery(`#${divId}`).html(aiautotool_content);
            scrollToBottom();
            jQuery('.btnaddpost').show();
            jQuery(".div_proccess").addClass("d-none");
            jQuery(".loadingprocess").addClass("d-none");
            hideLoading();
            update_usage();
            resolve(data.result || aiautotool_content);
        } else {
            // Display error message from API response
            var errorMsg = data.msg || 'Failed to rewrite content';
            var errorCode = data.code || 'Unknown';
            
            console.error('API Error Code (Rewrite):', errorCode);
            console.error('API Error Message (Rewrite):', errorMsg);
            console.error('Full Error Response:', data);
            
            // Hide loading indicators
            hideLoading();
            jQuery(".div_proccess").addClass("d-none");
            jQuery(".loadingprocess").addClass("d-none");
            
            // Show error alert/Swal with message from API
            if(typeof Swal !== 'undefined' && Swal){
                Swal.fire({
                    title: 'Error!',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonText: 'Close'
                });
            }else{
                alert(errorMsg);
            }
            reject(new Error(errorMsg));
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.error("=== AJAX Error Debug (Rewrite) ===");
        console.error("Status:", textStatus);
        console.error("Error:", errorThrown);
        console.error("Response:", jqXHR.responseText);
        console.error("Status Code:", jqXHR.status);
        console.error("Full XHR Object:", jqXHR);
        
        hideLoading();
        var errorMsg = errorThrown || textStatus || 'Network error occurred';
        if (window.location.search.indexOf('debug_api=1') !== -1 || (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.debug_api)) {
            var debugError = 'AJAX Error (Rewrite):\n\n';
            debugError += 'Status: ' + textStatus + '\n';
            debugError += 'Error: ' + errorThrown + '\n';
            debugError += 'HTTP Code: ' + jqXHR.status + '\n';
            debugError += 'Response: ' + (jqXHR.responseText ? jqXHR.responseText.substring(0, 500) : 'No response');
            alert(debugError);
        }
        
        if(Swal){
            Swal.fire({
                title: 'Error!',
                text: errorMsg,
                icon: 'error',
                confirmButtonText: 'Close'
            });
        }else{
            alert(errorMsg);
        }
        reject(new Error(errorMsg));
      }
    });
    });
}

function markdown(src,showImage=true){src=src.replace(/(#+)(\w+)/g,'\n$1 $2');var rx_lt=/</g;var rx_gt=/>/g;var rx_space=/\t|\r|\uf8ff/g;var rx_escape=/\\([\\\|`*_{}\[\]()#+\-~])/g;var rx_hr=/^([*\-=_] *){3,}$/gm;var rx_blockquote=/\n *&gt; *([^]*?)(?=(\n|$){2})/g;var rx_list=/\n( *)(?:[*\-+]|((\d+)|([a-z])|[A-Z])[.)]) +([^]*?)(?=(\n|$){2})/g;var rx_listjoin=/<\/(ol|ul)>\n\n<\1>/g;var rx_highlight=/(^|[^A-Za-z\d\\])(([*_])|(~)|(\^)|(--)|(\+\+)|`)(\2?)([^<]*?)\2\8(?!\2)(?=\W|_|$)/g;var rx_code=/\n((```|~~~).*\n?([^]*?)\n?\2|((    .*?\n)+))/g;var rx_link=/((!?)\[(.*?)\]\((.*?)( ".*")?\)|\\([\\`*_{}\[\]()#+\-.!~]))/g;var rx_table=/\n(( *\|.*?\| *\n)+)/g;var rx_thead=/^.*\n( *\|( *\:?-+\:?-+\:? *\|)* *\n|)/;var rx_row=/.*\n/g;var rx_cell=/\||(.*?[^\\])\|/g;var rx_heading=/(?=^|>|\n)([>\s]*?)(#{1,6}) (.*?)( #*)? *(?=\n|$)/g;var rx_para=/(?=^|>|\n)\s*\n+([^<]+?)\n+\s*(?=\n|<|$)/g;var rx_stash=/-\d+\uf8ff/g;function replace(rex,fn){src=src.replace(rex,fn);}
function element(tag,content){return '<'+tag+'>'+content+'</'+tag+'>';}
function blockquote(src){return src.replace(rx_blockquote,function(all,content){return element('blockquote',blockquote(highlight(content.replace(/^ *&gt; */gm,''))));});}
function list(src){return src.replace(rx_list,function(all,ind,ol,num,low,content){var entry=element('li',highlight(content.split(RegExp('\n ?'+ind+'(?:(?:\\d+|[a-zA-Z])[.)]|[*\\-+]) +','g')).map(list).join('</li><li>')));return '\n'+(ol?'<ol start="'+(num?ol+'">':parseInt(ol,36)-9+'" style="list-style-type:'+(low?'low':'upp')+'er-alpha">')+entry+'</ol>':element('ul',entry));});}
function highlight(src){return src.replace(rx_highlight,function(all,_,p1,emp,sub,sup,small,big,p2,content){return _+element(emp?(p2?'strong':'em'):sub?(p2?'s':'sub'):sup?'sup':small?'small':big?'big':'code',highlight(content));});}
function unesc(str){return str.replace(rx_escape,'$1');}
var stash=[];var si=0;src='\n'+src+'\n';replace(rx_lt,'&lt;');replace(rx_gt,'&gt;');replace(rx_space,'  ');src=blockquote(src);replace(rx_hr,'<hr/>');src=list(src);replace(rx_listjoin,'');replace(rx_code,function(all,p1,p2,p3,p4){stash[--si]=element('pre',element('code',p3||p4.replace(/^    /gm,'')));return si+'\uf8ff';});replace(rx_link,function(all,p1,p2,p3,p4,p5,p6){stash[--si]=p4?p2?(showImage==true?(p4.indexOf("http")>-1?'<img src="'+p4+'" alt="'+p3+'" onerror="this.style.display=\'none\'"/>':''):''):'<a href="'+p4+'" alt="'+p3+'">'+unesc(highlight(p3))+'</a>':p6;return si+'\uf8ff';});replace(rx_table,function(all,table){var sep=table.match(rx_thead)[1];return '\n'+element('table',table.replace(rx_row,function(row,ri){return row==sep?'':element('tr',row.replace(rx_cell,function(all,cell,ci){return ci?element(sep&&!ri?'th':'td',unesc(highlight(cell||''))):''}))}))});replace(rx_heading,function(all,_,p1,p2){return _+element('h'+p1.length,unesc(highlight(p2)))});replace(rx_para,function(all,content){return element('p',unesc(highlight(content)))});replace(rx_stash,function(all){return stash[parseInt(all)]});return src.trim();};


async function showProcess(totalTime=20000){
    showLoading();
        // jQuery(".div_proccess_0").addClass("d-none");
        // jQuery(".div_proccess_1").removeClass("d-none");
        // let t_1 = await showAProcess("proccess_1",totalTime);
        
    }
    async function showAProcess(process_id,loadingTime=200000){
        // return await new Promise(resolve => {
        //     jQuery(".div_proccess").addClass("d-none");
        //     jQuery(".div_"+process_id).removeClass("d-none");
        //     let interval = loadingTime/100;
        //     let percent = 0;
        //     myInterval = setInterval(() => {
        //         percent +=1;
        //         jQuery("#" + process_id).html(`${percent} %`);
        //         if (percent > 99){
        //             clearInterval(myInterval);
        //             resolve(1);
        //         }
                
        //     }, interval);
        // });
    }





jQuery(document).ready(function($){
    $('#upload-custom-thumbnail').on('click', function(e){
        e.preventDefault();

        var custom_uploader = wp.media({
            title: 'Choose Custom Thumbnail',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });

        custom_uploader.on('select', function() {
            var attachment = custom_uploader.state().get('selection').first().toJSON();
            $('#custom-thumbnail-id').val(attachment.id);
            $('#custom-thumbnail-preview').html('<img src="' + attachment.url + '">');
        });

        custom_uploader.open();
    });
});





const postTagsElement = document.getElementById('post_tags');

if (postTagsElement) {
    postTagsElement.addEventListener('paste', function (event) {
        
        event.preventDefault();

        const pastedData = (event.clipboardData || window.clipboardData).getData('text');

        const replacedData = pastedData.replace(/\n/g, ',');

        this.value = replacedData;
    });
} 



// lay images tu media
jQuery(document).ready(function($) {
    $('.ft-selec').click(function(e) {
        e.preventDefault();
        var inputId = $(this).data('input-id');
        openMediaUploader(inputId);
    });

    function openMediaUploader(inputId) {
        var customUploader = wp.media({
            title: 'Select image',
            button: {
                text: 'Select'
            },
            multiple: false
        });

        customUploader.on('select', function() {
            var attachment = customUploader.state().get('selection').first().toJSON();
            var imageUrl = attachment.url;
            $('#' + inputId).val(imageUrl);
        });

        customUploader.open();
    }
});


jQuery(document).ready(function($) {
        $('form input[type="checkbox"]').change(function() {
            var currentForm = $(this).closest('form');
            $.ajax({
                type: 'POST',
                url: currentForm.attr('action'), 
                data: currentForm.serialize(), 
                success: function(response) {
                    console.log('Turn on successfully');
                },
                error: function() {
                    console.log('Error in AJAX request');
                }
            });
        });
    });



function initializetextare() {
    jQuery('.aiautotool_container textarea').each(function() {
        //var textarea = jQuery(this);
        var editor = CodeMirror.fromTextArea(this, {
            lineNumbers: true,
            lineWrapping: true,
            matchBrackets: true,
            mode: 'text/x-perl',
            theme: 'cobalt',
        });
        jQuery(this).data('CodeMirrorInstance', editor);
       

        jQuery(document).on('keyup', '.CodeMirror-code', function(){
                editor.codemirror.save();
                textarea.html(editor.codemirror.getValue());
                textarea.trigger('change');
            });

    });
}

function updateCodeMirrorSize() {
    jQuery('.aiautotool_container textarea').each(function() {
        var textarea = jQuery(this);
        var editor = wp.codeEditor._instances[textarea.attr('id')];

        // Update CodeMirror's size
        editor.codemirror.setSize("100%", editor.codemirror.getWrapperElement().clientHeight);
    });
}


jQuery(document).ready(function($) {
    // initializetextare();
});




jQuery("body").on("click", ".Youtube_thumb", function(res) {
        res.preventDefault();
        let yId = jQuery(this).attr("data-id");
        let yTubeHTML = `<div class="youtubeVideo"><iframe src="https://www.youtube.com/embed/${yId}" width="560" height="314" allowfullscreen="allowfullscreen"></iframe></div>`;
        tinymce.activeEditor.insertContent(yTubeHTML);
        jQuery("input[name=video]").val("https://www.youtube.com/watch?v=" + yId);
        
    })



// Code Editor Functions
function updateLineNumbers(textarea, lineNumbersId) {
    const lineNumbers = document.getElementById(lineNumbersId);
    const lines = textarea.value.split('\n');
    const lineCount = lines.length;
    
    let lineNumbersHTML = '';
    for (let i = 1; i <= lineCount; i++) {
        lineNumbersHTML += `<div class="line-number">${i}</div>`;
    }
    
    lineNumbers.innerHTML = lineNumbersHTML;
    
    // Sync scroll
    lineNumbers.scrollTop = textarea.scrollTop;
}

function formatCode(button) {
    const container = button.closest('.code-editor-container');
    const textarea = container.querySelector('.ft-code-textarea');
    const code = textarea.value;
    
    try {
        // Basic HTML formatting
        let formatted = code
            .replace(/>\s*</g, '>\n<') // Add line breaks between tags
            .replace(/\n\s*\n/g, '\n') // Remove empty lines
            .replace(/^\s+|\s+$/gm, '') // Trim whitespace from lines
            .replace(/\n{3,}/g, '\n\n'); // Limit consecutive line breaks
        
        // Indent HTML properly
        let lines = formatted.split('\n');
        let indentLevel = 0;
        let formattedLines = [];
        
        for (let line of lines) {
            line = line.trim();
            if (!line) {
                formattedLines.push('');
                continue;
            }
            
            // Decrease indent for closing tags
            if (line.match(/^<\/[^>]+>/) && indentLevel > 0) {
                indentLevel--;
            }
            
            // Add indentation
            const indent = '    '.repeat(indentLevel);
            formattedLines.push(indent + line);
            
            // Increase indent for opening tags (but not self-closing)
            if (line.match(/^<[^/][^>]*>/) && !line.match(/\/>/)) {
                indentLevel++;
            }
        }
        
        textarea.value = formattedLines.join('\n');
        updateLineNumbers(textarea, container.querySelector('.line-numbers').id);
        
        // Show success feedback
        showFormatSuccess(button);
        
    } catch (error) {
        console.error('Formatting error:', error);
        showFormatError(button);
    }
}

function clearCode(button) {
    const container = button.closest('.code-editor-container');
    const textarea = container.querySelector('.ft-code-textarea');
    
    if (confirm('Are you sure you want to clear all code?')) {
        textarea.value = '';
        updateLineNumbers(textarea, container.querySelector('.line-numbers').id);
    }
}

function showFormatSuccess(button) {
    const originalText = button.textContent;
    button.textContent = '✓ Formatted';
    button.style.background = '#4caf50';
    button.style.color = '#fff';
    
    setTimeout(() => {
        button.textContent = originalText;
        button.style.background = '';
        button.style.color = '';
    }, 2000);
}

function showFormatError(button) {
    const originalText = button.textContent;
    button.textContent = '✗ Error';
    button.style.background = '#f44336';
    button.style.color = '#fff';
    
    setTimeout(() => {
        button.textContent = originalText;
        button.style.background = '';
        button.style.color = '';
    }, 2000);
}

// Initialize code editors when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Initialize line numbers for all code editors
    const codeEditors = document.querySelectorAll('.code-editor-container');
    codeEditors.forEach(container => {
        const textarea = container.querySelector('.ft-code-textarea');
        const lineNumbers = container.querySelector('.line-numbers');
        
        if (textarea && lineNumbers) {
            updateLineNumbers(textarea, lineNumbers.id);
            
            // Add scroll sync
            textarea.addEventListener('scroll', function() {
                lineNumbers.scrollTop = this.scrollTop;
            });
            
            // Add tab support
            textarea.addEventListener('keydown', function(e) {
                if (e.key === 'Tab') {
                    e.preventDefault();
                    const start = this.selectionStart;
                    const end = this.selectionEnd;
                    
                    // Insert tab
                    this.value = this.value.substring(0, start) + '    ' + this.value.substring(end);
                    
                    // Move cursor after tab
                    this.selectionStart = this.selectionEnd = start + 4;
                    
                    // Update line numbers
                    updateLineNumbers(this, lineNumbers.id);
                }
            });
        }
    });
});

// Syntax highlighting (basic)
function highlightSyntax(textarea) {
    const code = textarea.value;
    const highlighted = code
        // HTML tags
        .replace(/(<\/?)([a-zA-Z][a-zA-Z0-9]*)([^>]*>)/g, '<span style="color: #569cd6;">$1$2$3</span>')
        // Attributes
        .replace(/(\s+)([a-zA-Z-]+)(=)(")([^"]*)(")/g, '$1<span style="color: #9cdcfe;">$2</span>$3$4<span style="color: #ce9178;">$5</span>$6')
        // Comments
        .replace(/(<!--.*?-->)/g, '<span style="color: #6a9955;">$1</span>')
        // Strings
        .replace(/("([^"]*)")/g, '<span style="color: #ce9178;">$1</span>')
        // Numbers
        .replace(/\b(\d+)\b/g, '<span style="color: #b5cea8;">$1</span>');
    
    return highlighted;
}

// Auto-complete for HTML tags
function setupAutoComplete(textarea) {
    const commonTags = [
        'div', 'span', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'ul', 'ol', 'li', 'a', 'img', 'script', 'style', 'link',
        'meta', 'title', 'head', 'body', 'html', 'form', 'input',
        'button', 'textarea', 'select', 'option', 'table', 'tr',
        'td', 'th', 'thead', 'tbody', 'section', 'article', 'nav',
        'header', 'footer', 'aside', 'main'
    ];
    
    textarea.addEventListener('input', function(e) {
        // Check if value exists and is a string
        if (!this.value || typeof this.value !== 'string') {
            return;
        }
        
        const cursorPos = this.selectionStart || 0;
        const textBeforeCursor = this.value.substring(0, cursorPos);
        const lastWord = textBeforeCursor.match(/<([a-zA-Z]*)$/);
        
        if (lastWord) {
            const partialTag = lastWord[1].toLowerCase();
            const suggestions = commonTags.filter(tag => 
                tag.startsWith(partialTag) && tag !== partialTag
            );
            
            if (suggestions.length > 0) {
                showAutoCompleteSuggestions(textarea, suggestions, cursorPos);
            }
        }
    });
}

function showAutoCompleteSuggestions(textarea, suggestions, cursorPos) {
    // Remove existing suggestions
    const existingSuggestions = document.querySelector('.code-suggestions');
    if (existingSuggestions) {
        existingSuggestions.remove();
    }
    
    // Create suggestions container
    const suggestionsContainer = document.createElement('div');
    suggestionsContainer.className = 'code-suggestions';
    
    suggestions.forEach((suggestion, index) => {
        const item = document.createElement('div');
        item.className = 'code-suggestion-item';
        item.textContent = suggestion;
        item.addEventListener('click', () => {
            insertSuggestion(textarea, suggestion, cursorPos);
            suggestionsContainer.remove();
        });
        suggestionsContainer.appendChild(item);
    });
    
    // Position suggestions
    const rect = textarea.getBoundingClientRect();
    suggestionsContainer.style.position = 'absolute';
    suggestionsContainer.style.left = rect.left + 'px';
    suggestionsContainer.style.top = (rect.top + rect.height) + 'px';
    suggestionsContainer.style.width = rect.width + 'px';
    
    document.body.appendChild(suggestionsContainer);
}

function insertSuggestion(textarea, suggestion, cursorPos) {
    // Check if value exists and is a string
    if (!textarea.value || typeof textarea.value !== 'string') {
        textarea.value = '';
    }
    
    const textBeforeCursor = textarea.value.substring(0, cursorPos || 0);
    const textAfterCursor = textarea.value.substring(cursorPos || 0);
    
    // Find the start of the partial tag
    const lastOpenBracket = textBeforeCursor.lastIndexOf('<');
    const newText = textBeforeCursor.substring(0, lastOpenBracket + 1) + suggestion + textAfterCursor;
    
    textarea.value = newText;
    textarea.selectionStart = textarea.selectionEnd = lastOpenBracket + 1 + suggestion.length;
    textarea.focus();
    
    // Update line numbers
    const container = textarea.closest('.code-editor-container');
    const lineNumbers = container.querySelector('.line-numbers');
    updateLineNumbers(textarea, lineNumbers.id);
}

// Initialize auto-complete for all code editors
document.addEventListener('DOMContentLoaded', function() {
    const codeTextareas = document.querySelectorAll('.ft-code-textarea');
    codeTextareas.forEach(textarea => {
        setupAutoComplete(textarea);
    });
});

// Error checking for HTML
function validateHTML(textarea) {
    // Check if textarea and value exist
    if (!textarea || !textarea.value || typeof textarea.value !== 'string') {
        return [];
    }
    
    const code = textarea.value;
    const errors = [];
    
    // Check for unclosed tags
    const openTags = code.match(/<([a-zA-Z][a-zA-Z0-9]*)(?![^>]*\/>)/g) || [];
    const closeTags = code.match(/<\/([a-zA-Z][a-zA-Z0-9]*)>/g) || [];
    
    const openTagNames = openTags.map(tag => tag.replace(/[<>]/g, ''));
    const closeTagNames = closeTags.map(tag => tag.replace(/[<>/]/g, ''));
    
    // Simple validation - count opening and closing tags
    if (openTagNames.length !== closeTagNames.length) {
        errors.push('Mismatched HTML tags detected');
    }
    
    // Check for common issues
    if (code.includes('<<') || code.includes('>>')) {
        errors.push('Invalid HTML syntax detected');
    }
    
    return errors;
}

// Add validation to form submission
document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const textareas = form.querySelectorAll('.ft-code-textarea');
            let hasErrors = false;
            
            textareas.forEach(textarea => {
                const errors = validateHTML(textarea);
                if (errors.length > 0) {
                    hasErrors = true;
                    textarea.classList.add('error');
                    
                    // Show error message
                    const errorMsg = document.createElement('div');
                    errorMsg.className = 'error-message';
                    errorMsg.style.color = '#f44336';
                    errorMsg.style.fontSize = '12px';
                    errorMsg.style.marginTop = '5px';
                    errorMsg.textContent = errors.join(', ');
                    
                    const container = textarea.closest('.code-editor-container');
                    if (container) {
                        const existingError = container.querySelector('.error-message');
                        if (existingError) {
                            existingError.remove();
                        }
                        container.appendChild(errorMsg);
                    } else {
                        // Fallback: append error message after textarea if no container found
                        const existingError = textarea.parentElement.querySelector('.error-message');
                        if (existingError) {
                            existingError.remove();
                        }
                        textarea.parentElement.appendChild(errorMsg);
                    }
                } else {
                    textarea.classList.remove('error');
                    const container = textarea.closest('.code-editor-container');
                    if (container) {
                        const existingError = container.querySelector('.error-message');
                        if (existingError) {
                            existingError.remove();
                        }
                    } else {
                        // Fallback: remove error message from parent if no container found
                        const existingError = textarea.parentElement.querySelector('.error-message');
                        if (existingError) {
                            existingError.remove();
                        }
                    }
                }
            });
            
            if (hasErrors) {
                e.preventDefault();
                alert('Please fix HTML errors before saving.');
            }
        });
    });
}); 
