const {__, _x} = wp.i18n;

const ACCOUNT_PLAN_FREE = 1;
const ACCOUNT_PLAN_SMART = 2;
const MODE_EASY_CHAT = 0;
const MODE_GUIDED_CHAT = 1; // inactive
const MODE_EXPERT_CHAT = 2;
const MODE_NEW_CHAT = -1;
const TEMPLATES_MAX_PER_PAGE = 9;
const TEMPLATE_TYPE_CHAT = 'chat';
const TEMPLATE_TYPE_USER = 'user';


// SECTION: Variables
let guidedModeQuestions = {};
let chatSessions = [];
let chats = {};
let defaultSettings = {};
let chatSettings = {};
let chatTemplates = {};
let userTemplates = [];
let activeHeartbeats = [];
let clipboardActive = false;
let assHeartbeatInterval = 45;
let originalHeartbeatInterval = 0;
let userBlogPosts = [];
let progressInterval = null;

let liveData = {
    planId: (assi_plugin_data?.user_account?.plan?.plan_id != undefined && assi_plugin_data?.user_account?.plan?.plan_id > 0 ? assi_plugin_data.user_account.plan.plan_id : 0),
    creditsOpen: (assi_plugin_data?.user_account?.plan?.credits_open != undefined && assi_plugin_data?.user_account?.plan?.credits_open > 0 ? assi_plugin_data.user_account.plan.credits_open : 0),
    creditsTotal: (assi_plugin_data?.user_account?.plan?.credits_total != undefined && assi_plugin_data?.user_account?.plan?.credits_total > 0 ? assi_plugin_data.user_account.plan.credits_total : 0),
    promocreditsOpen: (assi_plugin_data?.user_account?.plan?.addons?.promotion?.credits_open != undefined && assi_plugin_data?.user_account?.plan?.addons?.promotion?.credits_open > 0 ? assi_plugin_data.user_account.plan.addons.promotion.credits_open : 0),
    promoCreditsTotal: (assi_plugin_data?.user_account?.plan?.addons?.promotion?.credits_total != undefined && assi_plugin_data?.user_account?.plan?.addons?.promotion?.credits_total > 0 ? assi_plugin_data.user_account.plan.addons.promotion.credits_total : 0),
    maxChats: (assi_plugin_data?.user_account?.plan?.max_chats != undefined && assi_plugin_data?.user_account?.plan?.max_chats >= 0 ? assi_plugin_data.user_account.plan.max_chats : null),
    maxTemplates: (assi_plugin_data?.user_account?.plan?.max_templates != undefined && assi_plugin_data?.user_account?.plan?.max_templates >= 0 ? assi_plugin_data.user_account.plan.max_templates : null),
    globalAlerts: (assi_plugin_data?.global_alerts != undefined ? assi_plugin_data.global_alerts : {}),
    chatsLeft: null,
    templatesLeft: null,
    showChatControls: true,
    showChatControlsTemplate: true,
    currentSessionId: null,
    notifications: 0,
    aiStatus: -1,
};
// !SECTION

// SECTION: Proxys
const liveDataHandler = {
    set(target, property, value) {
        if (property === 'chatsLeft' && target[property] !== value) {
            changeText('.ass-chat-header-add-count-open', value);
        }
        if (property === 'templatesLeft' && target[property] !== value) {
            changeText('.ass-templates-add-count-open', value);
        }
        if (property === 'showChatControls' && target[property] !== value) {
            if (!value) {
                jQuery('.ass-chat-control-tone-ctn').hide();
                jQuery('.ass-chat-control-pov-ctn').hide();
                jQuery('.ass-chat-control-length-ctn').hide();
            } else {
                jQuery('.ass-chat-control-tone-ctn').show();
                jQuery('.ass-chat-control-pov-ctn').show();
                jQuery('.ass-chat-control-length-ctn').show();
            }
        }
        if (property === 'showChatControlsTemplate' && target[property] !== value) {
            if (!value) {
                jQuery('.ass-chat-control-template-ctn').hide();
                jQuery('.ass-chat-template-btn').hide();
            } else {
                jQuery('.ass-chat-control-template-ctn').show();
                jQuery('.ass-chat-template-btn').show();
            }
        }
        if (property === 'creditsOpen' && target[property] !== value) {
            target[property] = value;
            displayCredits();
            updatecreditsOpen(value);
        }
        if (property === 'creditsTotal' && target[property] !== value) {
            target[property] = value;
            displayCredits();
            updateCreditsTotal(value);
        }
        if (property === 'maxChats' && target[property] !== value) {
            changeText('.ass-chat-header-add-count-total', value);
            updateMaxChats(value);
        }
        if (property === 'maxTemplates' && target[property] !== value) {
            changeText('.ass-templates-add-count-total', value);
            updateMaxTemplates(value);
        }
        if (property === 'currentSessionId' && target[property] !== value) {
            jQuery('.ass-chat-control-settings-save').hide();
            if (value == null || value == '') {
                jQuery('.ass-msg-head').hide();
                jQuery('.ass-chat-msg-list-placeholder').hide();
                jQuery('.ass-chat-control-btn-bottom').hide();
                jQuery('.ass-chat-msg-container-item').hide();
                jQuery('#ass-chat-send-textarea').val('').prop('disabled', true);
                jQuery('.ass-chat-template-btn').prop('disabled', true);
                jQuery('.ass-chat-send-btn').prop('disabled', true);
            } else {
                let chatSession = chatSessions.find(x => x.session_id == value);
                if (chatSession == undefined) {
                    jQuery('.ass-chat-header-edit').hide();
                } else {
                    jQuery('.ass-chat-header-edit').show();
                }
                jQuery('.ass-msg-head').show();
                jQuery('.ass-chat-control-btn-bottom').show();
                jQuery('#ass-chat-send-textarea').prop('disabled', false);
                jQuery('.ass-chat-template-btn').prop('disabled', false);
                jQuery('.ass-chat-send-btn').prop('disabled', false);

                changeText('.ass-chat-header-id', '#' + value);
                jQuery('.ass-chat-list-item').removeClass('ass-chat-list-item-active');
                jQuery('.ass-chat-list-item[data-session-id="' + value + '"]').addClass('ass-chat-list-item-active');

                let language = defaultSettings.content_creator.language;
                let tone = defaultSettings.content_creator.tone;
                let pointOfView = defaultSettings.content_creator.point_of_view;
                let contentLength = defaultSettings.content_creator.content_length;

                if (chatSettings[value] != undefined) {
                    language = (chatSettings[value].language != undefined) ? chatSettings[value].language : language;
                    tone = (chatSettings[value].tone != undefined) ? chatSettings[value].tone : tone;
                    pointOfView = (chatSettings[value].pointOfView != undefined) ? chatSettings[value].pointOfView : pointOfView;
                    contentLength = (chatSettings[value].contentLength != undefined) ? chatSettings[value].contentLength : contentLength;
                } else if (chats[value] != undefined && chats[value].length > 0) {
                    let length = chats[value].length;
                    language = chats[value][length - 1].prompt_language;
                    tone = chats[value][length - 1].tone;
                    pointOfView = chats[value][length - 1].point_of_view;
                    contentLength = chats[value][length - 1].content_length;

                    chatSettings[value] = {
                        language: language,
                        tone: tone,
                        pointOfView: pointOfView,
                        contentLength: contentLength
                    };
                }
                jQuery('.ass-chat-control-language').val(language);
                jQuery('.ass-chat-control-tone').val(tone);
                jQuery('.ass-chat-control-pov').val(pointOfView);
                jQuery('.ass-chat-control-length').val(contentLength);
            }
        }
        if (property === 'notifications' && target[property] !== value) {
            if (value > 0) {
                jQuery('.ass-sidebar-notification-badge').show();
                changeText('.ass-sidebar-notification-badge-count', value);
            } else {
                jQuery('.ass-sidebar-notification-badge').hide();
            }
        }
        if (property === 'planId' && target[property] !== value) {
            if (value == ACCOUNT_PLAN_FREE || value == ACCOUNT_PLAN_SMART) {
                jQuery('.ass-dashboard-review').show();
            } else {
                jQuery('.ass-dashboard-review').hide();
            }
            if (value == ACCOUNT_PLAN_SMART) {
                jQuery('.ass-dashboard-premium').hide();
                changeText('.ass-sidebar-licence-name', __('Smart', 'assistini'));
            } else {
                jQuery('.ass-dashboard-premium').show();
                changeText('.ass-sidebar-licence-name', __('Free', 'assistini'));
            }
            updatePlanId(value);
        }
        if (property === 'promocreditsOpen' && target[property] !== value) {
            target[property] = value;
            displayCredits();
        }
        if (property === 'promoCreditsTotal' && target[property] !== value) {
            target[property] = value;
            displayCredits();
        }
        if (property === 'globalAlerts' && target[property] !== value) {
            displayGlobalAlerts();
        }
        target[property] = value;
        return true;
    }
};
const proxyLiveData = new Proxy(liveData, liveDataHandler);

// !SECTION

// SECTION: Heartbeat
if (typeof wp.heartbeat !== "undefined" && wp.hasOwnProperty('heartbeat')) {
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_check_open_notifications',
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message != undefined ? data.error_message : '',
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true) {
                if (!activeHeartbeats.includes('ass_notifications')) {
                    activeHeartbeats.push('ass_notifications');
                }
                originalHeartbeatInterval = wp.heartbeat.interval();
                wp.heartbeat.interval(assHeartbeatInterval);
                wp.heartbeat.connectNow();
            } else {
                if (activeHeartbeats.includes('ass_notifications')) {
                    activeHeartbeats.splice(activeHeartbeats.indexOf('ass_notifications'), 1);
                    wp.heartbeat.interval(originalHeartbeatInterval);
                }
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
    jQuery(document).on('heartbeat-send', function (e, data) {
        data['ass_heartbeat_actions'] = activeHeartbeats;
    });
    jQuery(document).on('heartbeat-tick', function (event, data) {
        if (data.ass_notifications != undefined && data.ass_notifications.length > 0) {
            handleNotifications(data.ass_notifications);
            jQuery.ajax({
                url: ajaxurl,
                type: "POST",
                cache: false,
                data: {
                    'action': 'assi_check_open_notifications',
                    'assi_security_nonce': jQuery('#assi_security_nonce').val()
                },
                success: function (data) {
                    data = JSON.parse(data);
                    if (data.result != undefined && data.result == false && data.error != undefined) {
                        if (data.error == 'nonce') {
                            showNonceNotice();
                        } else {
                            showToast({
                                message: data.error_message != undefined ? data.error_message : '',
                                type: 'danger'
                            });
                        }
                    } else if (data.result == null || data.result == false) {
                        if (activeHeartbeats.includes('ass_notifications')) {
                            activeHeartbeats.splice(activeHeartbeats.indexOf('ass_notifications'), 1);
                            wp.heartbeat.interval(originalHeartbeatInterval);
                        }
                    }
                },
                error: function () {
                    showToast({ type: 'danger' });
                }
            });
        }
    });
} else {
    jQuery('.ass-notice-heartbeat').show();
}

// !SECTION

// SECTION: General
jQuery(document).ready(function () {
    defaultSettings = assi_plugin_data.settings;
    loadPage(window.location.href);
    if (navigator.clipboard && navigator.clipboard.writeText) {
        clipboardActive = true;
    }
    if (assi_plugin_data?.settings?.alert?.banner?.welcome == undefined || assi_plugin_data?.settings?.alert?.banner?.welcome != true) {
        jQuery('#ass-modal-onboarding').modal('show');
    }
    jQuery('.ass-sidebar-notification-badge').hide();
    configureAccountPage();
    jQuery('.ass-sidebar-license').show();
    if (assi_plugin_data?.custom_ai_connection?.active != undefined && assi_plugin_data.custom_ai_connection.active == 1) {
        jQuery('.ass-sidebar-licence-credits-ctn').hide();
    }
    jQuery('.ass-sidebar-license-no-auth').hide();
    jQuery('.ass-sidebar-sub-account-login').hide();
    let displayName = jQuery('#ass-oauth-display-name').val();
    changeText('.ass-sidebar-sub-account', displayName);

    loadPluginDataToProxy();
    displayCredits();
    displayGlobalAlerts();
    if (assi_plugin_data?.allow_server_connection == undefined || !assi_plugin_data?.allow_server_connection) {
        jQuery('.ass-sidebar-openai-status-ctn').hide();
    } else {
        checkOpenAiStatus();
    }
});

jQuery(window).on('hashchange', function () {
    loadPage(window.location.href);
});

function loadPluginDataToProxy() {
    if (assi_plugin_data?.user_account?.plan?.plan_id != undefined && assi_plugin_data?.user_account?.plan?.plan_id >= 0) {
        proxyLiveData.planId = assi_plugin_data.user_account.plan.plan_id;
    }
    if (assi_plugin_data?.user_account?.plan?.credits_open != undefined && assi_plugin_data?.user_account?.plan?.credits_open > 0) {
        proxyLiveData.creditsOpen = assi_plugin_data.user_account.plan.credits_open;
    }
    if (assi_plugin_data?.user_account?.plan?.credits_total != undefined && assi_plugin_data?.user_account?.plan?.credits_total > 0) {
        proxyLiveData.creditsTotal = assi_plugin_data.user_account.plan.credits_total;
    }
    if (assi_plugin_data?.user_account?.plan?.addons?.promotion?.credits_open != undefined && assi_plugin_data?.user_account?.plan?.addons?.promotion?.credits_open > 0) {
        proxyLiveData.promocreditsOpen = assi_plugin_data.user_account.plan.addons.promotion.credits_open;
    }
    if (assi_plugin_data?.user_account?.plan?.addons?.promotion?.credits_total != undefined && assi_plugin_data?.user_account?.plan?.addons?.promotion?.credits_total > 0) {
        proxyLiveData.promoCreditsTotal = assi_plugin_data.user_account.plan.addons.promotion.credits_total;
    }
    if (assi_plugin_data?.user_account?.plan?.max_chats != undefined && assi_plugin_data?.user_account?.plan?.max_chats > 0) {
        proxyLiveData.maxChats = assi_plugin_data.user_account.plan.max_chats;
    }
    if (assi_plugin_data?.user_account?.plan?.max_templates != undefined && assi_plugin_data?.user_account?.plan?.max_templates > 0) {
        proxyLiveData.maxTemplates = assi_plugin_data.user_account.plan.max_templates;

    }
}

function displayCredits() {
    let creditsOpen = proxyLiveData.creditsOpen;
    let creditsTotal = proxyLiveData.creditsTotal;
    changeText('.ass-sidebar-credits-open', creditsOpen);
    changeText('.ass-sidebar-credits-total', creditsTotal);
    changeText('.ass-sidebar-licence-credits', creditsTotal);
    let planCreditsMaxWidth = 100;
    let promoCreditsWidth = 0;
    let promoCreditsOpen = proxyLiveData.promocreditsOpen;
    let promoCreditsTotal = proxyLiveData.promoCreditsTotal;
    if (proxyLiveData.promoCreditsTotal > 0) {
        let promoCreditsMaxWidth = 0;
        changeText('.ass-sidebar-licence-credits', (creditsTotal - promoCreditsTotal));
        changeText('.ass-sidebar-license-promo-credits', promoCreditsTotal);
        jQuery('.ass-sidebar-license-promo').show();
        planCreditsMaxWidth = ((creditsTotal - promoCreditsTotal) / creditsTotal) * 100;
        promoCreditsMaxWidth = 100 - planCreditsMaxWidth;

        promoCreditsWidth = (promoCreditsOpen / promoCreditsTotal) * (promoCreditsMaxWidth / 100) * 100;
        if (promoCreditsWidth < 0) {
            promoCreditsWidth = 0;
        }
        if (promoCreditsWidth > promoCreditsMaxWidth) {
            promoCreditsWidth = promoCreditsMaxWidth;
        }
    }
    let planCreditsWidth = ((creditsOpen - promoCreditsOpen) / (creditsTotal - promoCreditsTotal)) * (planCreditsMaxWidth / 100) * 100;
    if (planCreditsWidth < 0) {
        planCreditsWidth = 0;
    }
    if (planCreditsWidth > planCreditsMaxWidth) {
        planCreditsWidth = planCreditsMaxWidth;
    }

    jQuery('.ass-sidebar-progress-bar').css('width', planCreditsWidth + '%');
    jQuery('.ass-sidebar-progress-bar-2').css('width', promoCreditsWidth + '%');
}

async function loadPage(href = '') {
    jQuery('.ass-page-content-loader').show();
    if (href == undefined || href == '') {
        return;
    }
    let index = href.indexOf('#/');
    if (index !== -1) {
        let substringUrl = href.substring(index + 2);
        let splitUrl = substringUrl.split('?');
        let queryParams = new URLSearchParams(splitUrl[1]);
        let urlParts = splitUrl[0].split('/').filter(Boolean);
        if (urlParts.length == undefined || urlParts.length == 0) {
            return;
        }
        let pageIdent = urlParts.join('.');
        if (pageIdent == '') {
            return;
        }
        let lastPage = jQuery('#ass-current-page').val();
        if (pageIdent == 'support') {
            jQuery('.ass-page-content-loader').hide();
            openSupportModal();

            if (lastPage != null && lastPage != '') {
                pageIdent = lastPage;
            } else {
                pageIdent = 'dashboard';
            }
            window.location.assign('#/' + pageIdent);
        } else if (pageIdent == 'account') {
        }
        jQuery('#ass-current-page').val(pageIdent);
        jQuery('.ass-page-item').hide();
        jQuery('.ass-sidebar-menu-item').removeClass('ass-sidebar-menu-item-selected');
        jQuery('.ass-sidebar-menu-item[data-content="' + pageIdent + '"]').addClass('ass-sidebar-menu-item-selected');

        if (typeof window['init_' + pageIdent] === 'function') {
            await window['init_' + pageIdent](queryParams, lastPage);
        }

        jQuery('.ass-page-content-loader').hide();
        jQuery('.ass-page-item[data-ident="' + pageIdent + '"]').show();

        if (typeof window['after_' + pageIdent] === 'function') {
            window['after_' + pageIdent](queryParams, lastPage);
        }
    } else {
        loadPage(window.location.href + '#/dashboard');
        return;
    }
}
function init_dashboard(queryParams, lastPage = '') {
    if (proxyLiveData.planId == 0) {
        proxyLiveData.planId = parseInt(jQuery('#ass-account-plan-id').val());
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_get_dashboard_activity',
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: (data.error_message != undefined ? data.error_message : ''),
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true && data.chat_sessions != null && data.chat_sessions != '') {
                jQuery('.ass-dashboard-last-chat-loader').hide();
                jQuery('.ass-dashboard-last-chat').html(data.chat_sessions);
                jQuery('.ass-dashboard-last-chat').show();
            } else {
                jQuery('.ass-dashboard-last-chat').html('');
                jQuery('.ass-dashboard-last-chat-loader').hide();
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
}

function init_chat(queryParams, lastPage = '') {
    jQuery('.ass-chat-area-blocked').hide();
    let queryTemplateId = (queryParams.get('template_id') != null && queryParams.get('template_id') > 0) ? queryParams.get('template_id') : 0;
    if (proxyLiveData.aiStatus > 1) {
        jQuery('.ass-chat-header-open-ai-status-item').hide();
        jQuery('.ass-chat-header-open-ai-status-item[data-status="' + proxyLiveData.aiStatus + '"]').show();
        jQuery('.ass-chat-header-open-ai-status').show();
    }
    loadSelectTemplates(queryTemplateId);
}

function after_template(queryParams, lastPage = '') {
    jQuery('.ass-templates-blocked').hide();
    reloadTemplates(jQuery('.ass-templates-nav-active').attr('data-type'), (queryParams.get('do') != undefined && queryParams.get('do') == 'click_add_template' ? true : false));
}

async function after_chat(queryParams, lastPage = '') {
    if (jQuery('.ass-chat-sidebar-toggle').is(':hidden')) {
        openChatSidebar();
    }
    if (lastPage == 'chat') {
        return;
    }
    let check = checkConnection();
    if (!check) {
        return;
    }
    const data = await jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_get_chat_list',
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-chat-list-items').html('');
            jQuery('.ass-chat-list-placeholder').show();
        },
    });
    const parsedData = JSON.parse(data);
    if (parsedData.result == false) {
        if (parsedData.error != undefined && parsedData.error == 'nonce') {
            showNonceNotice();
            return;
        }
        if (parsedData.error != undefined && (parsedData.error == 'client_blocked' || parsedData.error == 'server_blocked' || parsedData.error == 'server_auth_failed')) {
            jQuery('.ass-modal-connection-error-content').hide();
            jQuery('.ass-modal-connection-error-content[data-type="' + parsedData.error + '"]').show();
            jQuery('#ass-modal-connection-error').modal('show');
            return;
        }
        showToast({
            message: (parsedData.error_message != undefined ? parsedData.error_message : ''),
            type: 'danger'
        });
        return;
    }
    chatSessions = parsedData.chat_sessions;
    if (parsedData.chat_list_html != null) {
        jQuery('.ass-chat-list-placeholder').hide();
        jQuery('.ass-chat-list-items').html(parsedData.chat_list_html);
        initializeToolTips();
        if (jQuery('.ass-chat-header-close-btn').is(':hidden')) {
            jQuery('.ass-chat-sidebar-toggle').hide();
        }
    }
    if (parsedData.user_data != undefined && parsedData.user_data != null) {
        updateProxyUserData(parsedData.user_data);
    }
    if (parsedData.global_alerts != undefined) {
        if (typeof parsedData.global_alerts == 'object') {
            proxyLiveData.globalAlerts = parsedData.global_alerts;
        } else {
            proxyLiveData.globalAlerts = {};
        }
    }
    let chatsLeft = proxyLiveData.maxChats - parseInt(parsedData.count_chats != undefined && parsedData.count_chats != null ? parsedData.count_chats : 0);
    proxyLiveData.chatsLeft = (chatsLeft < 0 ? 0 : chatsLeft);
    if (chatSessions.length > 0 && queryParams.get('template_id') == undefined && queryParams.get('sys_template_id') == undefined) {
        let sessionId = chatSessions[0].session_id;
        let chatName = chatSessions[0].chat_name;
        let chatMode = chatSessions[0].mode;
        if (queryParams.get('chat_id') != undefined) {
            let filterEntry = chatSessions.find(item => item.session_id === queryParams.get('chat_id'));
            if (filterEntry != undefined) {
                sessionId = filterEntry.session_id;
                chatName = filterEntry.chat_name;
                chatMode = filterEntry.mode;
                loadChatHistory(sessionId, chatName, chatMode);
            }
        } else if (queryParams.get('do') != undefined && queryParams.get('do') == 'click_create_content') {
            displayNewChat();
        }
    } else {
        if (queryParams.get('sys_template_id') != undefined) {
            if (proxyLiveData.chatsLeft <= 0) {
                openUpgradeModal('chat');
                return;
            }
            displayGuidedChat(queryParams.get('sys_template_id'));
            return;
        } else if (queryParams.get('template_id') != undefined) {
            displayNewChat(parseInt(queryParams.get('template_id')));
            return;
        } else if (queryParams.get('do') != undefined && queryParams.get('do') == 'click_create_content') {
            displayNewChat();
            return;
        } else {
            jQuery('.ass-chat-header-add-btn').trigger('click');
        }
    }
    if (proxyLiveData.currentSessionId == null) {
        jQuery('.ass-msg-head').hide();
        jQuery('.ass-chat-msg-list-placeholder').hide();
        jQuery('.ass-chat-control-btn-bottom').hide();
        jQuery('#ass-chat-send-textarea').prop('disabled', true);
        jQuery('.ass-chat-template-btn').prop('disabled', true);
        jQuery('.ass-chat-send-btn').prop('disabled', true);
    }
}
function after_settings(queryParams, lastPage = '') {
    if (defaultSettings != undefined && defaultSettings.content_creator != undefined) {
        jQuery('.ass-settings-creator-language').val(defaultSettings?.content_creator?.language);
        jQuery('.ass-settings-creator-tone').val(defaultSettings?.content_creator?.tone);
        jQuery('.ass-settings-creator-pov').val(defaultSettings?.content_creator?.point_of_view);
        jQuery('.ass-settings-creator-length').val(defaultSettings?.content_creator?.content_length);
    }
    if (defaultSettings != undefined && defaultSettings.image_generator != undefined) {
        jQuery('.ass-settings-image-size').val(defaultSettings?.image_generator?.size);
        jQuery('.ass-settings-image-quality').val(defaultSettings?.image_generator?.quality);
        jQuery('.ass-settings-image-format').val(defaultSettings?.image_generator?.output_format);
    }
    if (assi_plugin_data?.custom_ai_connection?.active != undefined && assi_plugin_data.custom_ai_connection.active == 1) {
        jQuery('#ass-settings-custom-ai-toggle').prop('checked', true).trigger('change');
    }
}
function after_account(queryParams, lastPage = '') {
    if (queryParams.get('email') != undefined && queryParams.get('email') != '') {
        jQuery('#ass-account-email').val(queryParams.get('email'));
        jQuery('.ass-account-connect-btn').trigger('click');
    }
    if (queryParams.get('remove') != undefined && queryParams.get('remove') == '1') {
        jQuery('.ass-account-remove-btn').trigger('click');
    }
}
function changeText(selector, newText) {
    const $element = jQuery(selector);
    if ($element.text() === newText) {
        return;
    }
    $element.fadeOut(150, () => {
        $element.text(newText).fadeIn(150);
    });
}
function replaceNewLine(text) {
    text = text
        .split(/(<[^>]+>)/g) // In Tags und Nicht-Tags aufteilen
        .map(part => {
            if (!part.startsWith("<")) {
                // Newlines zu <br>
                part = part.replace(/(?:\r\n|\r|\n)/g, '<br>');
                // Maximal 2 <br> hintereinander
                part = part.replace(/(?:<br>\s*){3,}/g, '<br><br>');
            }
            return part;
        })
        .join("");

    if (text.endsWith('<br>')) {
        text = text.slice(0, -4);
    }

    text = text.replace(/(<\/?(ul|ol)[^>]*>)([\s\S]*?)(<\/\2>)/g,
        (match, openTag, listType, content, closeTag) => {
            content = content.replace(/<br\s*\/?>/gi, '');
            return `${openTag}${content}${closeTag}`;
        }
    );

    // <br> aus Tabellen entfernen
    text = text.replace(/(<table[^>]*>)([\s\S]*?)(<\/table>)/gi,
        (match, openTag, content, closeTag) => {
            content = content.replace(/<br\s*\/?>/gi, '');
            return `<br>${openTag}${content}${closeTag}<br>`;
        }
    );

    // remove <br> from lists
    text = text.replace(/(<\/?(ul|ol)[^>]*>)([\s\S]*?)(<\/\2>)/g, (match, openTag, listType, content, closeTag) => {
        content = content.replace(/<br>/g, '');
        return `${openTag}${content}${closeTag}`;
    });

    // remove <br> after paragraphs
    text = text.replace(/<\/p>\s*<br>/g, '</p>');

    // remove <br> after <h1-5> tags
    text = text.replace(/(<\/h[1-5]>)\s*<br\s*\/?>/gi, "$1");

    // remove <hr> at end of text
    text = text.replace(/<hr\s*\/?>\s*$/i, '');
    return text;
}

function updatecreditsOpen(remainingCredits) {
    if (remainingCredits === null || remainingCredits < 0) {
        return;
    }
    jQuery.post(ajaxurl, {
        action: 'assi_update_credits_left',
        credits_left: remainingCredits,
        assi_security_nonce: jQuery('#assi_security_nonce').val(),
    });
}
function updateCreditsTotal(totalCredits) {
    if (totalCredits === null || totalCredits < 0) {
        return;
    }
    jQuery.post(ajaxurl, {
        action: 'assi_update_credits_total',
        credits_total: totalCredits,
        assi_security_nonce: jQuery('#assi_security_nonce').val(),
    });
}
function updateMaxChats(maxChats) {
    if (maxChats === null || maxChats < 0) {
        return;
    }
    jQuery.post(ajaxurl, {
        action: 'assi_update_max_chats',
        max_chats: maxChats,
        assi_security_nonce: jQuery('#assi_security_nonce').val(),
    });
}
function updateMaxTemplates(maxTemplates) {
    if (maxTemplates === null || maxTemplates < 0) {
        return;
    }
    jQuery.post(ajaxurl, {
        action: 'assi_update_max_templates',
        max_templates: maxTemplates,
        assi_security_nonce: jQuery('#assi_security_nonce').val(),
    });
}
function updatePlanId(planId) {
    if (planId === null || planId < 0) {
        return;
    }
    jQuery.post(ajaxurl, {
        action: 'assi_update_plan_id',
        plan_id: planId,
        assi_security_nonce: jQuery('#assi_security_nonce').val(),
    });
}
function showNonceNotice() {
    jQuery('.ass-notice-nonce').show();
}
// !SECTION

// SECTION: Sidebar
jQuery(document).on('click', '.ass-sidebar-close-btn', function () {
    jQuery('.ass-sidebar').hide();
    jQuery('.ass-sidebar-island').show();
    return false;
});

jQuery(document).on('click', '.ass-sidebar-menu-item', function () {
    window.location.assign('#/' + jQuery(this).attr('data-content'));
    return false;
});
jQuery(document).on('click', '.ass-sidebar-licence-reload', function () {
    if (!activeHeartbeats.includes('ass_notifications')) {
        activeHeartbeats.push('ass_notifications');
        wp.heartbeat.connectNow();
        let index = activeHeartbeats.indexOf('ass_notifications');
        if (index > -1) { // only splice array when item is found
            activeHeartbeats.splice(index, 1); // 2nd parameter means remove one item only
        }
        showToast({
            message: __('Refreshing Licence...', 'assistini'),
            type: 'primary'
        });
    } else {
        wp.heartbeat.connectNow();
    }
});
jQuery(document).on('click', '.ass-sidebar-license-upgrade-btn', function() {
    window.open('https://app.assistini.com/?screen=Plan', '_blank');
});
jQuery(document).on('click', '.ass-sidebar-alert-connection-lost-more', function (e) {
    e.preventDefault();
    window.location.href = `#/account`;
});
// !SECTION

// SECTION: Sidebar Island
jQuery(document).on('click', '.ass-sidebar-island', function () {
    jQuery('.ass-sidebar-island').hide();
    jQuery('.ass-sidebar').show();
    return false;
});
// !SECTION

// SECTION: Dashboard
jQuery(document).on('click', '.ass-dashboard-activity-card', function () {
    const sessionId = jQuery(this).attr('data-session-id');
    if (sessionId === undefined || sessionId === null || sessionId === '') {
        showToast({
            message: __('Invalid session id!', 'assistini'),
            type: 'danger'
        });
        return;
    }
    window.location.href = `#/chat?chat_id=${sessionId}`;
});
// !SECTION

// SECTION: Chat
function scrollMessageWindow() {
    jQuery('.ass-chat-timeline').animate({scrollTop: jQuery('.ass-chat-timeline').prop('scrollHeight')}, {duration: 500, easing: 'swing'});
}
jQuery(document).on('click', '.ass-chat-header-close-btn', function () {
    closeChatSidebar();
});
jQuery(document).on('click', '.ass-chat-header-open-btn', function () {
    openChatSidebar();
});

jQuery(document).on('change', '.ass-chat-control-template', function () {
    const $selectedElement = jQuery(this).find(':selected');
    let templateId = parseInt($selectedElement.val());
    if (templateId == undefined || isNaN(templateId) || templateId <= 0) {
        if (chatTemplates[proxyLiveData.currentSessionId] != undefined && chatTemplates[proxyLiveData.currentSessionId] != null) {
            chatTemplates[proxyLiveData.currentSessionId].id = 0;
        } else {
            chatTemplates[proxyLiveData.currentSessionId] = {id: 0};
        }
        jQuery('.ass-chat-control-language').val(defaultSettings.content_creator.language);
        jQuery('.ass-chat-control-tone').val(defaultSettings.content_creator.tone);
        jQuery('.ass-chat-control-pov').val(defaultSettings.content_creator.point_of_view);
        jQuery('.ass-chat-control-length').val(defaultSettings.content_creator.content_length);
        return;
    }
    let templateEntry = userTemplates.find(x => x.id == templateId && x.is_system == 0);
    if (templateEntry == undefined || templateEntry == null) {
        return;
    }
    if (chatTemplates[proxyLiveData.currentSessionId] != undefined && chatTemplates[proxyLiveData.currentSessionId] != null) {
        chatTemplates[proxyLiveData.currentSessionId].id = templateId;
    } else {
        chatTemplates[proxyLiveData.currentSessionId] = {id: templateId};
    }
    jQuery('.ass-chat-control-language').val(templateEntry.language);
    jQuery('.ass-chat-control-tone').val(templateEntry.tone);
    jQuery('.ass-chat-control-pov').val(templateEntry.point_of_view);
    jQuery('.ass-chat-control-length').val(templateEntry.content_length);
});

jQuery(document).on('click', '.ass-chat-header-id', function () {
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(jQuery(this).text()).then(function () {
            showToast({
                message: __('Copied to Clipboard', 'assistini'),
                type: 'primary'
            });
        });
    }
});

function closeChatSidebar() {
    jQuery('.ass-chat-header-close-btn').hide();
    jQuery('.ass-chat-header-open-btn').show();

    jQuery('.ass-chat-sidebar-toggle').hide();
    let $chatList = jQuery('.ass-chat-list');
    $chatList.css('width', 'auto');
    let targetWidth = ($chatList[0].scrollWidth >= 62 ? $chatList[0].scrollWidth : 62);
    $chatList.css('width', '300px');
    jQuery('.ass-chat-sidebar-toggle').show();
    jQuery('.ass-chat-sidebar-toggle').fadeOut(100);
    setTimeout(() => {
        $chatList.css("width", targetWidth + "px");
    }, 40);
}

function openChatSidebar() {
    jQuery('.ass-chat-header-open-btn').hide();
    jQuery('.ass-chat-header-close-btn').show();

    let $chatList = jQuery('.ass-chat-list');
    $chatList.css('width', '300px');
    setTimeout(() => {
        jQuery('.ass-chat-sidebar-toggle').fadeIn(150);
    }, 150);
}

jQuery(document).on('click', '.ass-chat-template-btn', function () {
    if (proxyLiveData.templatesLeft <= 0) {
        openUpgradeModal('template');
        return;
    }
    jQuery('#ass-templates-add-prompt').val(jQuery('#ass-chat-send-textarea').val());
    jQuery('.ass-templates-add-language').val(jQuery('.ass-chat-control-language').find(':selected').val());
    jQuery('.ass-templates-add-tone').val(jQuery('.ass-chat-control-tone').find(':selected').val());
    jQuery('.ass-templates-add-view').val(jQuery('.ass-chat-control-pov').find(':selected').val());
    jQuery('.ass-templates-add-length').val(jQuery('.ass-chat-control-length').find(':selected').val());
    jQuery('#ass-templates-add-blog-access').prop('checked', false);
    if (proxyLiveData.planId <= ACCOUNT_PLAN_FREE) {
        jQuery('.ass-templates-add-blog-access-ctn').addClass('ass-templates-disabled-checkbox');
        jQuery('#ass-templates-add-blog-access').prop('disabled', true);
        jQuery('.ass-templates-add-blog-access-badge').show();
        jQuery('.ass-modal-templates-add-prompt-action[data-action="analyze"]').prop('disabled', true);
        jQuery('.ass-modal-templates-add-prompt-action-analyze-badge').show();
    } else {
        jQuery('.ass-templates-add-blog-access-ctn').removeClass('ass-templates-disabled-checkbox');
        jQuery('#ass-templates-add-blog-access').prop('disabled', false);
        jQuery('.ass-templates-add-blog-access-badge').hide();
        jQuery('.ass-modal-templates-add-prompt-action[data-action="analyze"]').prop('disabled', false);
        jQuery('.ass-modal-templates-add-prompt-action-analyze-badge').hide();
    }
    resetModalAddSidebar();
    jQuery('#ass-modal-templates-add').modal('show');
});

jQuery(document).on('click', '.ass-chat-control-template-save-btn', function () {
    let userInput = jQuery('#ass-chat-send-textarea').val();
    let templateName = jQuery('#ass-chat-control-template-save-name').val();
    if (userInput == undefined || userInput == '') {
        showToast({
            message: __('The Prompt can not be empty.', 'assistini'),
            type: 'secondary'
        });
    }
    if (templateName == undefined || templateName == '') {
        showToast({
            message: __('The Template name can not be empty.', 'assistini'),
            type: 'secondary'
        });
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_save_template',
            'name': templateName,
            'prompt': userInput,
            'reference_text': '',
            'language': jQuery('.ass-chat-control-language').find(':selected').val(),
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-chat-control-template-save-btn').prop('disabled', true);
            jQuery('.ass-chat-control-template-save-icon').hide();
            jQuery('.ass-chat-control-template-save-loader').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == true) {
                showToast({
                    message: __('Your template has been saved.', 'assistini')
                });
                loadSelectTemplates();
            } else if (data.error != undefined && data.error_message != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message,
                        type: 'danger'
                    });
                }
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-chat-control-template-save-icon').show();
            jQuery('.ass-chat-control-template-save-loader').hide();
            jQuery('.ass-chat-control-template-save-btn').prop('disabled', false);
            jQuery('#ass-chat-control-template-save-name').val('');
            jQuery('.ass-chat-control-template-save').fadeOut(150);
        },
    });
});
jQuery(document).on('click', '.ass-chat-sidebar-clickable', function () {
    const sessionId = jQuery(this).parent().attr('data-session-id');
    let entry = chatSessions.find(x => x.session_id == sessionId && x.mode == 2);
    let tempShowChatControls = true;
    let tempShowChatControlsTemplate = true;
    if (entry != undefined && entry.template_id != undefined && entry.template_id > 0) {
        tempShowChatControlsTemplate = false;
        let template = userTemplates.find(x => x.id == entry.template_id && x.is_system == 1);
        if (template.show_controls != undefined) {
            tempShowChatControls = (template.show_controls == 1 ? true : false);
        }
    }
    proxyLiveData.showChatControls = tempShowChatControls;
    proxyLiveData.showChatControlsTemplate = tempShowChatControlsTemplate;
    if (sessionId == jQuery('#ass-current-session-id').val()) {
        return;
    }
    jQuery('.ass-chat-control-template').val('');
    jQuery('#ass-chat-send-textarea').val('');
    const chatName = jQuery(this).parent().attr('data-chat-name');
    const chatMode = parseInt(jQuery(this).parent().attr('data-mode'));
    loadChatHistory(sessionId, chatName, chatMode);
});
jQuery(document).on('click', '.ass-chat-header-report', function () {
    openSupportModal({
        sessionId: jQuery('#ass-current-session-id').val(),
        templateId: parseInt(jQuery('.ass-chat-control-template').find(':selected').val()),
        language: jQuery('.ass-chat-control-language').find(':selected').val(),
        tone: jQuery('.ass-chat-control-tone').find(':selected').val(),
        pointOfView: jQuery('.ass-chat-control-pov').find(':selected').val(),
        contentLength: jQuery('.ass-chat-control-length').find(':selected').val(),
    });
    return;
});
jQuery(document).on('click', '.ass-chat-sidebar-delete', function () {
    const $chatListItem = jQuery(this).parent();
    const sessionId = $chatListItem.attr('data-session-id');
    const chatMode = parseInt($chatListItem.attr('data-mode'));
    const $modalElement = jQuery('#ass-modal-chat-delete');
    $modalElement.modal('show');
    $modalElement.on('click', function (event) {
        const $deleteButton = jQuery(event.target).closest('.ass-modal-chat-delete-btn');
        if ($deleteButton.length > 0) {
            if (chatMode == MODE_NEW_CHAT) {
                if (!$chatListItem.hasClass('ass-chat-list-item-disabled')) {
                    proxyLiveData.chatsLeft++;
                }
                $chatListItem.animate({marginLeft: '-290px', marginRight: '290px'}, {duration: 150, easing: 'swing', complete: function () {
                        $chatListItem.animate({height: '0px', padding: '0px'}, {duration: 150, easing: 'swing', complete: function () {
                                $chatListItem.remove();
                            }});
                    }});
                if (sessionId == jQuery('#ass-current-session-id').val()) {
                    jQuery('#ass-current-session-id').val('');
                    proxyLiveData.currentSessionId = null;
                }
                $modalElement.modal('hide');
                showToast({
                    message: __('The chat has been deleted.', 'assistini')
                });

            } else {
                jQuery.ajax({
                    url: ajaxurl,
                    type: "POST",
                    cache: false,
                    data: {
                        'action': 'assi_chat_delete',
                        'session_id': sessionId,
                        'assi_security_nonce': jQuery('#assi_security_nonce').val()
                    },
                    beforeSend: function () {
                        jQuery('.ass-modal-chat-delete-btn').prop('disabled', true);
                        jQuery('.ass-modal-chat-delete-text').hide();
                        jQuery('.ass-modal-chat-delete-loader').show();
                    },
                    success: function (data) {
                        data = JSON.parse(data);
                        if (data.result != undefined && data.result == false && data.error != undefined) {
                            if (data.error == 'nonce') {
                                showNonceNotice();
                            } else {
                                showToast({
                                    message: (data.error_message != undefined ? data.error_message : ''),
                                    type: 'danger'
                                });
                            }
                        } else if (data.result != undefined && data.result == true) {
                            if (!$chatListItem.hasClass('ass-chat-list-item-disabled')) {
                                proxyLiveData.chatsLeft++;
                                let $firstDisabled = jQuery('.ass-chat-list-item .ass-chat-list-item-disabled:first');
                                if ($firstDisabled.length > 0) {
                                    $firstDisabled.removeClass('ass-chat-list-item-disabled');
                                    $firstDisabled.find('.ass-chat-sidebar-clickable-disabled').removeClass('ass-chat-sidebar-clickable-disabled').addClass('ass-chat-sidebar-clickable');
                                }
                            }
                            $chatListItem.animate({marginLeft: '-290px', marginRight: '290px'}, {duration: 150, easing: 'swing', complete: function () {
                                    $chatListItem.animate({height: '0px', padding: '0px'}, {duration: 150, easing: 'swing', complete: function () {
                                            $chatListItem.remove();
                                        }});
                                }});
                            if (sessionId == jQuery('#ass-current-session-id').val()) {
                                jQuery('#ass-current-session-id').val('');
                                proxyLiveData.currentSessionId = null;
                            }
                            showToast({
                                message: __('The chat has been deleted.', 'assistini')
                            });
                        } else {
                            showToast({ type: 'danger' });
                        }
                        $modalElement.modal('hide');
                    },
                    error: function () {
                        showToast({ type: 'danger' });
                    },
                    complete: function () {
                        jQuery('.ass-modal-chat-delete-loader').hide();
                        jQuery('.ass-modal-chat-delete-text').show();
                        jQuery('.ass-modal-chat-delete-btn').prop('disabled', false);
                        init_dashboard();
                    }
                });
            }
        }
    });
});
jQuery(document).on('click', '.ass-chat-header-delete', function () {
    let sessionId = jQuery('#ass-current-session-id').val();
    let $chatListItem = jQuery('.ass-chat-list-item[data-session-id="' + sessionId + '"]');
    let chatMode = parseInt($chatListItem.attr('data-mode'));
    const $modalElement = jQuery('#ass-modal-chat-delete');
    $modalElement.modal('show');
    $modalElement.on('click', function (event) {
        let $deleteButton = jQuery(event.target).closest('.ass-modal-chat-delete-btn');
        if ($deleteButton.length > 0) {
            if (chatMode == MODE_NEW_CHAT) {
                $chatListItem.animate({marginLeft: '-290px', marginRight: '290px'}, {duration: 150, easing: 'swing', complete: function () {
                        $chatListItem.animate({height: '0px', padding: '0px'}, {duration: 150, easing: 'swing', complete: function () {
                                $chatListItem.remove();
                            }});
                    }});
                jQuery('#ass-current-session-id').val('');
                proxyLiveData.currentSessionId = null;
                $modalElement.modal('hide');
                showToast({
                    message: __('The chat has been deleted.', 'assistini')
                });
            } else {
                jQuery.ajax({
                    url: ajaxurl,
                    type: "POST",
                    cache: false,
                    data: {
                        'action': 'assi_chat_delete',
                        'session_id': sessionId,
                        'assi_security_nonce': jQuery('#assi_security_nonce').val()
                    },
                    beforeSend: function () {
                        jQuery('.ass-modal-chat-delete-btn').prop('disabled', true);
                        jQuery('.ass-modal-chat-delete-text').hide();
                        jQuery('.ass-modal-chat-delete-loader').show();
                    },
                    success: function (data) {
                        data = JSON.parse(data);
                        if (data.result != undefined && data.result == false && data.error != undefined) {
                            if (data.error == 'nonce') {
                                showNonceNotice();
                            } else {
                                showToast({
                                    message: (data.error_message != undefined ? data.error_message : ''),
                                    type: 'danger'
                                });
                            }
                        } else if (data.result != undefined && data.result == true) {
                            $chatListItem.animate({marginLeft: '-290px', marginRight: '290px'}, {duration: 150, easing: 'swing', complete: function () {
                                    $chatListItem.animate({height: '0px', padding: '0px'}, {duration: 150, easing: 'swing', complete: function () {
                                            $chatListItem.remove();
                                        }});
                                }});
                            proxyLiveData.chatsLeft += 1;
                            showToast({
                                message: __('The chat has been deleted.', 'assistini')
                            });
                            jQuery('#ass-current-session-id').val('');
                            proxyLiveData.currentSessionId = null;
                        } else {
                            showToast({ type: 'danger' });
                        }
                        $modalElement.modal('hide');
                    },
                    error: function () {
                        showToast({ type: 'danger' });
                    },
                    complete: function () {
                        jQuery('.ass-modal-chat-delete-loader').hide();
                        jQuery('.ass-modal-chat-delete-text').show();
                        jQuery('.ass-modal-chat-delete-btn').prop('disabled', false);
                    }
                });
            }
        }
    });
    return;
});
jQuery(document).on('click', '.ass-chat-header-edit', function () {
    let chatName = jQuery('.ass-chat-header-name').text();
    jQuery('#ass-chat-header-edit-input').show();
    jQuery('#ass-chat-header-edit-input').val(chatName);
    jQuery('#ass-chat-header-edit-input').focus();
    jQuery('.ass-chat-header-name').hide();
    jQuery('.ass-chat-header-edit').hide();
});
jQuery('#ass-chat-header-edit-input').on('blur', function () {
    let chatName = (jQuery(this).val()).trim();
    if (chatName != undefined && chatName != '' && chatName != jQuery('.ass-chat-header-name').text()) {
        let sessionId = proxyLiveData.currentSessionId;
        jQuery('#ass-chat-header-edit-input').hide();
        jQuery('.ass-chat-header-name').show();
        changeText(jQuery('.ass-chat-header-name'), chatName);
        jQuery('.ass-chat-header-edit').show();
        changeText(jQuery('.ass-chat-list-item[data-session-id="' + sessionId + '"] .ass-chat-list-item-name'), chatName);
        jQuery('.ass-chat-list-item[data-session-id="' + sessionId + '"]').attr('data-chat-name', chatName);
        jQuery('.ass-chat-list-item[data-session-id="' + sessionId + '"]').attr('data-bs-title', chatName);
        let chatSession = chatSessions.find(x => x.session_id == sessionId);
        if (chatSession) {
            chatSession.chat_name = chatName;
        }
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            data: {
                'action': 'assi_chat_change_name',
                'session_id': sessionId,
                'chat_name': chatName,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            }
        });
    } else {
        jQuery('#ass-chat-header-edit-input').hide();
        jQuery('.ass-chat-header-name').show();
        jQuery('.ass-chat-header-edit').show();
    }
    initializeToolTips();
});
document.getElementById('ass-modal-chat-delete').addEventListener('hidden.bs.modal', function () {
    jQuery('#ass-modal-chat-delete').off();
});

async function loadChatHistory(session_id, chat_name, chatMode = 0, forceReload = false) {
    if ((chatMode == MODE_EASY_CHAT || chatMode == MODE_NEW_CHAT) && (chat_name == '' || chat_name == undefined)) {
        chat_name = __('Chat', 'assistini');
    }
    changeText('.ass-chat-header-name', chat_name);
    let $chatItemElement = jQuery('.ass-chat-msg-container-item[data-session-id="' + session_id + '"]');
    if ($chatItemElement.length > 0) {
        if (forceReload) {
            $chatItemElement.remove();
        } else {
            jQuery('#ass-current-session-id').val(session_id);
            proxyLiveData.currentSessionId = session_id;
            jQuery('.ass-chat-msg-container-item').hide();
            $chatItemElement.show();
            scrollMessageWindow();
            if (chatTemplates[session_id] != undefined && chatTemplates[session_id].id != undefined && chatTemplates[session_id].id > 0) {
                jQuery('#ass-chat-control-template').val(chatTemplates[session_id].id);
                jQuery('.ass-chat-control-template').trigger('change');
            }
            return;
        }
    }
    $chatItemElement = jQuery('<ul>', {
        class: "ass-chat-msg-container-item",
        'data-session-id': session_id,
        'data-mode': chatMode,
        'style': 'display:none;'
    });
    jQuery('.ass-chat-msg-list-container').append($chatItemElement);
    jQuery('.ass-chat-msg-container-item').hide();
    jQuery('.ass-chat-msg-list-placeholder').show();


    jQuery('.ass-chat-header-placeholder').hide();
    jQuery('.ass-chat-header').show();
    const lastChatHistory = await jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_get_chat_history',
            'session_id': session_id,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        }
    });
    const parsedLastChatHistory = JSON.parse(lastChatHistory);

    if (parsedLastChatHistory.chat_content == undefined || parsedLastChatHistory.chat_content == null || parsedLastChatHistory.chat_content.length < 1) {
        if (parsedLastChatHistory.error != undefined && parsedLastChatHistory.error == 'nonce') {
            showNonceNotice();
        } else {
            showToast({
                message: (parsedLastChatHistory.error_message != undefined ? parsedLastChatHistory.error_message : ''),
                type: 'danger'
            });
        }
        return;
    }
    jQuery('.ass-chat-msg-list-placeholder').hide();
    $chatItemElement.show();
    $chatItemElement.html('');
    chats[session_id] = parsedLastChatHistory.chat_content;
    jQuery('#ass-current-session-id').val(session_id);
    proxyLiveData.currentSessionId = session_id;
    let chatDateEntry = null;
    for (let i = 0; i < parsedLastChatHistory.chat_content.length; i++) {
        let dateTime = new Date(parsedLastChatHistory.chat_content[i].date.replace(' ', 'T') + 'Z');
        let dateDay = dateTime.toLocaleDateString('de-DE', {day: '2-digit', month: '2-digit', year: 'numeric'});
        dateTime = dateTime.getHours().toString().padStart(2, '0') + ':' + dateTime.getMinutes().toString().padStart(2, '0');

        let html = '';
        if (chatDateEntry != dateDay) {
            chatDateEntry = dateDay;
            html += '<li class="ass-chat-msg-date text-center"><span class="ass-chat-msg-time badge rounded-pill text-dark">' + dateDay + '</span></li>';
        }
        if (parsedLastChatHistory.chat_content[i].sort != null && parsedLastChatHistory.chat_content[i].sort == 1) {
            if (parsedLastChatHistory.chat_content[i].ai_output.content != null && parsedLastChatHistory.chat_content[i].ai_output.content != '') {
                insertMessage({
                    sessionId: session_id,
                    title: (parsedLastChatHistory.chat_content[i].ai_output.title != undefined ? parsedLastChatHistory.chat_content[i].ai_output.title : ''),
                    text: parsedLastChatHistory.chat_content[i].ai_output.content,
                    focusKeyphrase: (parsedLastChatHistory.chat_content[i].ai_output.focus_keyword != undefined ? parsedLastChatHistory.chat_content[i].ai_output.focus_keyword : ''),
                    keywords: (parsedLastChatHistory.chat_content[i].ai_output.keywords != undefined ? parsedLastChatHistory.chat_content[i].ai_output.keywords : ''),
                    metaDescription: (parsedLastChatHistory.chat_content[i].ai_output.meta_description != undefined ? parsedLastChatHistory.chat_content[i].ai_output.meta_description : ''),
                    dateTime: dateTime,
                    dateDay: dateDay,
                    autoScroll: false,
                    msgId: parsedLastChatHistory.chat_content[i].c_id,
                    controls: (parsedLastChatHistory.chat_content[i].show_copy_save != undefined && parsedLastChatHistory.chat_content[i].show_copy_save == 1 ? true : false),
                    isSystem: (parsedLastChatHistory.chat_content[i].is_system_prompt != undefined && parsedLastChatHistory.chat_content[i].is_system_prompt == 1 ? true : false),
                });
            }
            if (parsedLastChatHistory.chat_content[i].user_input != null && parsedLastChatHistory.chat_content[i].user_input != '') {
                insertMessage({
                    sessionId: session_id,
                    text: parsedLastChatHistory.chat_content[i].user_input,
                    isUser: true,
                    dateTime: dateTime,
                    dateDay: dateDay,
                    autoScroll: false
                });
            }
        } else {
            if (parsedLastChatHistory.chat_content[i].user_input != null && parsedLastChatHistory.chat_content[i].user_input != '') {
                insertMessage({
                    sessionId: session_id,
                    text: parsedLastChatHistory.chat_content[i].user_input,
                    isUser: true,
                    dateTime: dateTime,
                    dateDay: dateDay,
                    autoScroll: false
                });
            }
            if (parsedLastChatHistory.chat_content[i].ai_output.content != null && parsedLastChatHistory.chat_content[i].ai_output.content != '') {
                insertMessage({
                    sessionId: session_id,
                    title: (parsedLastChatHistory.chat_content[i].ai_output.title != undefined ? parsedLastChatHistory.chat_content[i].ai_output.title : ''),
                    text: parsedLastChatHistory.chat_content[i].ai_output.content,
                    focusKeyphrase: (parsedLastChatHistory.chat_content[i].ai_output.focus_keyword != undefined ? parsedLastChatHistory.chat_content[i].ai_output.focus_keyword : ''),
                    keywords: (parsedLastChatHistory.chat_content[i].ai_output.keywords != undefined ? parsedLastChatHistory.chat_content[i].ai_output.keywords : ''),
                    metaDescription: (parsedLastChatHistory.chat_content[i].ai_output.meta_description != undefined ? parsedLastChatHistory.chat_content[i].ai_output.meta_description : ''),
                    dateTime: dateTime,
                    dateDay: dateDay,
                    autoScroll: false,
                    msgId: parsedLastChatHistory.chat_content[i].c_id,
                    controls: (parsedLastChatHistory.chat_content[i].show_copy_save != undefined && parsedLastChatHistory.chat_content[i].show_copy_save == 1 ? true : false),
                    isSystem: (parsedLastChatHistory.chat_content[i].is_system_prompt != undefined && parsedLastChatHistory.chat_content[i].is_system_prompt == 1 ? true : false),
                });
            }
        }

        if (i == parsedLastChatHistory.chat_content.length - 1) {
            jQuery('.ass-chat-control-language').val(parsedLastChatHistory.chat_content[i].prompt_language);
            $chatItemElement.attr('data-last-msg-date', dateDay);
        }
    }
    scrollMessageWindow();
}
jQuery(document).on('keydown', '#ass-chat-send-textarea', function (e) {
    if (e.shiftKey == false && (e.key === 'Enter' || e.keyCode === 13)) {
        e.preventDefault();
        jQuery('.ass-chat-send-btn').trigger('click');
    }
});
jQuery(document).on('click', '.ass-chat-send-btn', function (e) {
    e.preventDefault();
    if (assi_plugin_data?.allow_server_connection == undefined || !assi_plugin_data?.allow_server_connection) {
        showToast({
            message: __('Assistini API not reachable.', 'assistini'),
            type: 'danger'
        });
        return;
    }

    if (assi_plugin_data?.custom_ai_connection?.active == undefined || assi_plugin_data.custom_ai_connection.active == 0) {
        if (proxyLiveData.creditsOpen <= 0) {
            openUpgradeModal('credits');
            return;
        }
    }

    let $chatItem = jQuery('.ass-chat-msg-list-container').find('.ass-chat-msg-container-item:visible');
    const sessionId = jQuery('#ass-current-session-id').val();
    const chatMode = parseInt($chatItem.attr('data-mode'));
    if (sessionId == null || sessionId == '') {
        showToast({
            message: __('Assistini API not reachable.', 'assistini'),
            type: 'danger'
        });
        return;
    }

    const userPrompt = jQuery('#ass-chat-send-textarea').val();
    jQuery('#ass-chat-send-textarea').val('');
    if (userPrompt == '') {
        showToast({
            message: __('The Prompt can not be empty.', 'assistini'),
            type: 'secondary'
        });
        return;
    }
 
    let userTemplateId = 0;
    if (chatMode == MODE_NEW_CHAT || chatMode == MODE_EASY_CHAT) {
        let selectTemplateId = jQuery('.ass-chat-control-template').find(':selected').val();
        if (selectTemplateId != undefined && selectTemplateId > 0) {
            userTemplateId = selectTemplateId;
        }
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_chat_send_prompt',
            'session_id': (chatMode == MODE_NEW_CHAT ? '' : sessionId),
            'local_session_id': (chatMode == MODE_NEW_CHAT ? sessionId : ''),
            'mode': chatMode,
            'user_prompt': userPrompt,
            'user_template_id': userTemplateId,
            'user_lang': jQuery('.ass-chat-control-language').find(':selected').val(),
            'user_tone': jQuery('.ass-chat-control-tone').find(':selected').val(),
            'user_point_of_view': jQuery('.ass-chat-control-pov').find(':selected').val(),
            'user_content_length': jQuery('.ass-chat-control-length').find(':selected').val(),
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            insertMessage({
                sessionId: sessionId,
                isUser: true,
                text: userPrompt
            });
            setTimeout(function () {
                jQuery('.ass-chat-msg-response-loader').show();
                scrollMessageWindow();
            }, 750);
        },
        success: function (data) {
            jQuery('.ass-chat-msg-response-loader').hide();
            data = JSON.parse(data);
            if (data.result == true && data.answer != null) {
                saveChatSettings(data.session_id);
                const $sidebarChatItem = jQuery('.ass-chat-list-item[data-session-id="' + sessionId + '"]');
                moveElementToFirst($sidebarChatItem);
                if (chatMode == MODE_NEW_CHAT) {
                    jQuery('#ass-current-session-id').val(data.session_id);
                    let chatName = (data.chat_name == '' ? __('Chat', 'assistini') : data.chat_name);
                    chatSessions.push({chat_name: chatName, session_id: data.session_id, create_date: data.answer_date, last_mod_date: data.answer_date, mode: MODE_EASY_CHAT, disabled: 0, template_id: userTemplateId});
                    proxyLiveData.currentSessionId = data.session_id;
                    changeText('.ass-chat-header-name', chatName);
                    $chatItem.attr('data-mode', MODE_EASY_CHAT);
                    $sidebarChatItem.attr('data-chat-name', chatName);
                    $sidebarChatItem.attr('data-session-id', data.session_id);
                    $sidebarChatItem.attr('data-mode', MODE_EASY_CHAT);
                    changeText($sidebarChatItem.find('.ass-chat-list-item-name'), chatName);
                    $sidebarChatItem.attr('data-bs-title', chatName);
                    initializeToolTips();
                    const $chatElement = jQuery('.ass-chat-msg-container-item[data-session-id="' + sessionId + '"]');
                    $chatElement.attr('data-session-id', data.session_id);
                }
                if (chatMode == MODE_EXPERT_CHAT) {
                    $sidebarChatItem.attr('data-chat-name', data.chat_name);
                    changeText($sidebarChatItem.find('.ass-chat-list-item-name'), data.chat_name);
                    changeText('.ass-chat-header-name', data.chat_name);
                    $sidebarChatItem.attr('data-bs-title', data.chatName);
                    initializeToolTips();
                }
                if (chats[data.session_id] != undefined && chats[data.session_id] != null) {
                    chats[data.session_id].push(data.chat_content);
                    init_dashboard();
                } else {
                    chats[data.session_id] = [data.chat_content];
                }
                if (data.user_data != undefined) {
                    updateProxyUserData(data.user_data);
                }
                if (data.global_alerts != undefined) {
                    if (typeof data.global_alerts == 'object') {
                        proxyLiveData.globalAlerts = data.global_alerts;
                    } else {
                        proxyLiveData.globalAlerts = {};
                    }
                }
                insertMessage({
                    sessionId: data.session_id,
                    title: (data.chat_content.ai_output.title != undefined ? data.chat_content.ai_output.title : ''),
                    text: (data.answer == '' ? data.chat_content.ai_output.content : data.answer),
                    focusKeyphrase: (data.chat_content.ai_output.focus_keyword != undefined ? data.chat_content.ai_output.focus_keyword : ''),
                    keywords: (data.chat_content.ai_output.keywords != undefined ? data.chat_content.ai_output.keywords : ''),
                    metaDescription: (data.chat_content.ai_output.meta_description != undefined ? data.chat_content.ai_output.meta_description : ''),
                    msgId: data.chat_content.c_id,
                    controls: (data.chat_content.show_copy_save != undefined && data.chat_content.show_copy_save == 1 ? true : false),
                    isSystem: (data.chat_content.is_system_prompt != undefined && data.chat_content.is_system_prompt == 1 ? true : false)
                });
            } else if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else if (data.error == 'client_timeout') {
                    if (!activeHeartbeats.includes('ass_notifications')) {
                        activeHeartbeats.push('ass_notifications');
                        wp.heartbeat.interval(assHeartbeatInterval);
                    }
                    insertMessage({
                        sessionId: sessionId,
                        isError: true,
                        errorType: 'client_timeout'
                    });
                } else if (data.error_message != undefined) {
                    showToast({
                        message: data.error_message,
                        type: 'danger'
                    });
                } else {
                    showToast({ type: 'danger' });
                }
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
});


function displayNewChat(userTemplateId = 0) {
    const $chatSidebarElement = jQuery('.ass-chat-list-items');
    proxyLiveData.showChatControls = true;
    proxyLiveData.showChatControlsTemplate = true;
    let tempSessionId;
    if ($chatSidebarElement.find('.ass-chat-list-item[data-mode="' + MODE_NEW_CHAT + '"]').length > 0) {
        tempSessionId = $chatSidebarElement.find('.ass-chat-list-item[data-mode="' + MODE_NEW_CHAT + '"]').attr('data-session-id');
        jQuery('.ass-chat-msg-list-placeholder').hide();
        changeText('.ass-chat-header-name', __('Chat', 'assistini'));
        jQuery('.ass-chat-header-placeholder').hide();
        jQuery('.ass-chat-header').show();
        jQuery('#ass-current-session-id').val(tempSessionId);
        proxyLiveData.currentSessionId = tempSessionId;

        jQuery('.ass-chat-msg-container-item').hide();
        jQuery('.ass-chat-msg-container-item[data-session-id="' + tempSessionId + '"]').show();
        return;
    }
    tempSessionId = Date.now();
    let html = '';
    html += '<div class="ass-chat-list-item ass-chat-list-item-new d-flex align-items-center overflow-hidden mb-1" data-session-id="' + tempSessionId + '" data-mode="' + MODE_NEW_CHAT + '" style="height: auto; visibility: hidden; position: absolute;" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="' + __('Chat', 'assistini') + '">';
    html += '<div class="ass-chat-sidebar-clickable flex-shrink-0">';
    html += '<i class="bi bi-chat ass-size-32"></i>';
    html += '</div>';
    html += '<div class="ass-chat-sidebar-clickable ass-chat-sidebar-toggle flex-grow-1 text-truncate px-3">';
    html += '<h3 class="ass-chat-list-item-name mb-0 text-truncate">' + __('Chat', 'assistini') + '</h3>';
    html += '</div>';
    html += '<div class="ass-chat-sidebar-delete ass-chat-sidebar-toggle flex-shrink-0">';
    html += ' <button type="button" class="btn p-0 border-0 bg-transparent">';
    html += '<i class="bi bi-trash"></i>';
    html += '</button>';
    html += '</div>';
    html += '</div>';
    
    $chatSidebarElement.prepend(html);
    initializeToolTips();
    const autoHeight = jQuery('.ass-chat-list-item-new').outerHeight();
    jQuery('.ass-chat-list-item-new').css({
        height: '0',
        visibility: 'visible',
        position: 'relative'
    });
    jQuery('.ass-chat-list-item-new').animate({height: autoHeight + 'px'}, {duration: 100, easing: 'swing', complete: function () {
            jQuery(this).css('height', 'auto').removeClass('ass-chat-list-item-new');
        }});

    jQuery('.ass-chat-msg-list-placeholder').hide();
    jQuery('.ass-chat-header-name').text(__('Chat', 'assistini'));
    jQuery('.ass-chat-header-placeholder').hide();
    jQuery('.ass-chat-header').show();
    jQuery('#ass-current-session-id').val(tempSessionId);
    proxyLiveData.currentSessionId = tempSessionId;
    if (userTemplateId > 0) {
        jQuery('.ass-chat-control-template').val(userTemplateId);
        jQuery('.ass-chat-control-template').trigger('change');
    }

    let $chatListElement = jQuery('<ul>', {
        class: 'ass-chat-msg-container-item',
        'data-session-id': tempSessionId,
        'data-mode': MODE_NEW_CHAT,
        'data-last-msg-date': ''
    });
    jQuery('.ass-chat-msg-list-container').append($chatListElement);
    jQuery('.ass-chat-msg-container-item').hide();
    jQuery('.ass-chat-msg-container-item[data-session-id="' + tempSessionId + '"]').show();

    const now = new Date();
    const dateTime = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0');

    insertMessage({
        sessionId: tempSessionId,
        text: __('What do you want to write about?', 'assistini'),
    });

    if (proxyLiveData.chatsLeft > 0) {
        proxyLiveData.chatsLeft--;
    }
}

async function displayGuidedChat(templateId = 1) {
    jQuery('ass-chat-control-language').val(defaultSettings.content_creator.language);
    jQuery('ass-chat-control-tone').val(defaultSettings.content_creator.tone);
    jQuery('ass-chat-control-pov').val(defaultSettings.content_creator.point_of_view);
    jQuery('ass-chat-control-length').val(defaultSettings.content_creator.content_length);

    const tempSessionId = Date.now();
    jQuery('.ass-chat-msg-list-placeholder').hide();
    let chatName = __('Expert Chat', 'assistini');
    if (userTemplates.length > 0) {
        let entry = userTemplates.find(x => x.id == templateId && x.is_system == 1);
        if (entry.header != undefined && entry.header != '') {
            chatName = entry.header;
        }
        if (!entry.show_controls) {
            proxyLiveData.showChatControls = false;
        } else {
            proxyLiveData.showChatControls = true;
        }
    }
    proxyLiveData.showChatControlsTemplate = false;
    jQuery('.ass-chat-header-placeholder').hide();
    jQuery('.ass-chat-header').show();
    changeText('.ass-chat-header-name', chatName);
    jQuery('#ass-current-session-id').val(tempSessionId);
    proxyLiveData.currentSessionId = tempSessionId;
    const defaultLanguage = defaultSettings.content_creator.language;

    jQuery('.ass-chat-msg-list-placeholder').hide();

    let $chatListElement = jQuery('<ul>', {
        class: 'ass-chat-msg-container-item',
        'data-session-id': tempSessionId,
        'data-mode': MODE_EXPERT_CHAT,
        'data-last-msg-date': '',
        'data-guided-language': defaultLanguage
    });
    jQuery('.ass-chat-msg-list-container').append($chatListElement);
    jQuery('.ass-chat-msg-container-item').hide();
    jQuery('.ass-chat-msg-container-item[data-session-id="' + tempSessionId + '"]').show();

    const $chatSidebarElement = jQuery('.ass-chat-list-items');
    let html = '';
    html += '<div class="ass-chat-list-item ass-chat-list-item-new d-flex align-items-center overflow-hidden mb-1" data-chat-name="' + chatName + '" data-session-id="' + tempSessionId + '" data-mode="' + MODE_EXPERT_CHAT + '" style="height: auto; visibility: hidden; position: absolute;" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="' + chatName + '">';
    html += '<div class="ass-chat-sidebar-clickable flex-shrink-0">';
    html += '<i class="bi bi-chat ass-size-32"></i>';
    html += '</div>';
    html += '<div class="ass-chat-sidebar-clickable ass-chat-sidebar-toggle flex-grow-1 text-truncate px-3">';
    html += '<h3 class="ass-chat-list-item-name mb-0 text-truncate">' + chatName + '</h3>';
    html += '</div>';
    html += '<div class="ass-chat-sidebar-delete ass-chat-sidebar-toggle flex-shrink-0">';
    html += ' <button type="button" class="btn p-0 border-0 bg-transparent">';
    html += '<i class="bi bi-trash"></i>';
    html += '</button>';
    html += '</div>';
    html += '</div>';

    $chatSidebarElement.prepend(html);
    initializeToolTips();
    const autoHeight = jQuery('.ass-chat-list-item-new').outerHeight();
    jQuery('.ass-chat-list-item-new').css({
        height: '0',
        visibility: 'visible',
        position: 'relative'
    });
    jQuery('.ass-chat-list-item-new').animate({height: autoHeight + 'px'}, {duration: 100, easing: 'swing', complete: function () {
            jQuery(this).css('height', 'auto').removeClass('ass-chat-list-item-new');
        }});

    const now = new Date();
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_chat_start_expert_mode',
            'template_id': templateId,
            'language': defaultLanguage,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-chat-msg-response-loader').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: (data.error_message != undefined ? data.error_message : ''),
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true) {
                chatSessions.push({
                    chat_name: '',
                    session_id: data.session_id,
                    create_date: data.chat_content.ai_output.date,
                    last_mod_date: data.chat_content.ai_output.date,
                    mode: 2,
                    template_id: templateId
                });
                let $sidebarChatItem = jQuery('.ass-chat-list-item[data-session-id="' + tempSessionId + '"]');
                $sidebarChatItem.attr('data-session-id', data.session_id);

                $chatListElement.attr('data-session-id', data.session_id);
                jQuery('#ass-current-session-id').val(data.session_id);
                chatSettings[data.session_id] = {defaultLanguage};
                proxyLiveData.currentSessionId = data.session_id;
                jQuery('.ass-chat-msg-response-loader').hide();
                insertMessage({
                    sessionId: data.session_id,
                    title: (data.chat_content.ai_output.title != undefined ? data.chat_content.ai_output.title : ''),
                    text: data.chat_content.ai_output.content
                });
                if (proxyLiveData.chatsLeft > 0) {
                    proxyLiveData.chatsLeft--;
                }
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
}

function insertMessage( { sessionId = '', title = '', text = '', isUser = false, dateDay = '', dateTime = '', controls = false, autoScroll = true, msgId = 0, isSystem = false, isError = false, errorType = 'client_timeout', focusKeyphrase = '', keywords = '', metaDescription = '' }) {
    const $chatListElement = jQuery('.ass-chat-msg-container-item[data-session-id="' + sessionId + '"]');
    if ($chatListElement.length < 1) {
        showToast({
            message: __('No chat for session id', 'assistini'),
            type: 'danger'
        });
        return;
    }

    const now = new Date();
    if (dateTime == '') {
        dateTime = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0');
    }

    if (dateDay == '') {
        dateDay = now.toLocaleDateString('de-DE', {day: '2-digit', month: '2-digit', year: 'numeric'});
    }

    let html = '';
    if ($chatListElement.attr('data-last-msg-date') != dateDay) {
        html += '<li class="ass-chat-msg-date text-center"><span class="ass-chat-msg-time badge rounded-pill text-dark">' + dateDay + '</span></li>';
        $chatListElement.attr('data-last-msg-date', dateDay);
    }
    if (isError == true) {
        if (errorType == 'client_timeout') {
            html += '<li class="ass-chat-msg-sender">';
            html += '<div>';
            html += '<div class="ass-chat-msg-bubble">';
            html += '<div class="d-flex align-items-center"><img class="ass-chat-error-logo me-2" src="' + (assi_plugin_data.plugin_path + '/assets/images/ass_notification_icon.png') + '" /><h5 class="m-0 mt-1">' + __('Heads up: Your content is taking a bit longer to generate.', 'assistini') + '</h5></div><br>';
            html += '<p>' + __('We’ll notify you automatically within the next minute once it’s ready. To avoid this delay in the future, we recommend increasing the “max_execution_time” in your WordPress settings to at least 45 seconds.', 'assistini') + '</p>';
            html += '</div>';
            html += '</div>';
            html += '</li>';
            $chatListElement.append(html);
            if (autoScroll == true) {
                scrollMessageWindow();
            }
        }
        return;
    }
    if (typeof text != 'string') {
        html += '<li class="ass-chat-msg-' + (isUser == true ? 'reply' : 'sender') + '">';
        html += '<div>';
        if (isUser) {
            html += '<i class="bi-exclamation-circle-fill text-danger me-2"></i>';
        }
        html += '<div class="ass-chat-msg-bubble">';
        html += '<p>' + __('Unable to load message!', 'assistini') + '</p>';
        html += '</div>';
        if (!isUser) {
            html += '<i class="bi-exclamation-circle-fill text-danger ms-2"></i>';
        }
        html += '</div>';
        html += '</li>';
        $chatListElement.append(html);
        if (autoScroll == true) {
            scrollMessageWindow();
        }
        return;
    }

    if (title != undefined && title != '') {
        title = '<h1>' + title + '</h1>';
    } else {
        title = '';
    }
    html += '<li class="ass-chat-msg-' + (isUser == true ? 'reply' : 'sender') + '" data-msg-id="' + msgId + '">';
    html += '<div>';
    html += '<div class="ass-chat-msg-bubble">';
    if (isSystem == true && controls == true && isUser == false) {
        html += '<div class="ass-chat-action-btn-ctn-top float-end position-relative">';
        if (clipboardActive) {
            html += '<button class="ass-chat-action-btn ass-size-11 btn btn-outline-primary btn-sm" data-action="copy">' + __('Copy to Clipboard', 'assistini');
            +'</button>';
        }
        html += '<button class="ass-chat-action-btn ass-size-11 ms-1 btn btn-secondary btn-sm" data-action="save">' + __('Insert to Editor', 'assistini');
        +'</button>';
        html += '</div>';
    }
    html += title + replaceNewLine(marked.parse(text));
    if (!isUser && (focusKeyphrase != '' || keywords != '' || metaDescription != '')) {
        html += '<br><hr><br>';
        html += '<h3>' + __('Seo Information (are transferred with "Insert to Editor")', 'assistini') + '</h3><br>';
        if (focusKeyphrase != '') {
            html += '<p class="mb-0"><b>' + __('Focus Keyphrase', 'assistini') + ':</b></p>';
            html += '<p>' + focusKeyphrase + '</p>';
        }
        if (keywords != '') {
            html += '<p class="mb-0"><b>' + __('Keywords', 'assistini') + ':</b></p>';
            html += '<p>' + keywords + '</p>';
        }
        if (metaDescription != '') {
            html += '<p class="mb-0"><b>' + __('SEO Meta-Description', 'assistini') + ':</b></p>';
            html += '<p>' + metaDescription + '</p>';
        }
    }
    if (controls == true && isUser == false) {
        html += '<div class="ms-5 ass-chat-action-btn-ctn-btm float-end position-relative">';
        if (clipboardActive) {
            html += '<button class="ass-chat-action-btn ass-size-11 btn btn-outline-primary btn-sm" data-action="copy">' + __('Copy to Clipboard', 'assistini');
            +'</button>';
        }
        html += '<button class="ass-chat-action-btn ass-size-11 ms-1 btn btn-secondary btn-sm" data-action="save">' + __('Insert to Editor', 'assistini');
        +'</button>';
        html += '</div>';
    }
    html += '</div>';
    html += '<div class="position-absolute ' + (isUser == true ? 'end' : 'start') + '-0 translate-middle-y mt-1 px-2">';
    if (isUser == true) {
        html += '<span class="ass-chat-msg-function-btn badge rounded-pill bg-white text-dark ms-2" data-action="copy"><i class="ass-size-11 bi bi-pencil-fill m-0 me-1"></i>' + __('Copy', 'assistini') + '</span>';
        html += '<span class="ass-chat-msg-time badge rounded-pill bg-white text-dark ms-2">' + dateTime + '</span>';
    } else {
        html += '<span class="ass-chat-msg-time badge rounded-pill bg-white text-dark me-2">' + dateTime + '</span>';
    }
    html += '</div>';
    html += '</div>';
    html += '</li>';
    $chatListElement.append(html);
    if (autoScroll == true) {
        scrollMessageWindow();
}
}

jQuery(document).on('click', '.ass-chat-header-add-btn', function () {
    if (proxyLiveData.chatsLeft <= 0) {
        openUpgradeModal('chat');
        return;
    }
    const $modalElement = jQuery('#ass-modal-chat-new');
    $modalElement.modal('show');
    $modalElement.on('click', async function (event) {
        if (jQuery(event.target).closest('.ass-modal-chat-new-easy-btn').length < 1 && jQuery(event.target).closest('.ass-modal-chat-new-guided-btn').length < 1) {
            return;
        }
        $modalElement.modal('hide');
        jQuery('.ass-chat-control-template').val('');
        jQuery('#ass-chat-send-textarea').val('');
        if (jQuery(event.target).closest('.ass-modal-chat-new-easy-btn').length > 0) {
            displayNewChat();
        } else {
            let templateId = parseInt(jQuery(event.target).closest('.ass-modal-chat-new-guided-btn').data('id'));
            displayGuidedChat(templateId);
        }
    });
});
document.getElementById('ass-modal-chat-new').addEventListener('hidden.bs.modal', function () {
    jQuery('#ass-modal-chat-new').off();
});

jQuery(document).on('click', '.ass-chat-msg-function-btn', function () {
    const action = jQuery(this).attr('data-action');
    if (action == 'copy') {
        const msg = jQuery(this).closest('li').find('p').text().trim();
        jQuery('#ass-chat-send-textarea').val(msg);
        return;
    }
    if (action == 'save') {
        const $msgElement = jQuery(this).closest('.ass-chat-msg-sender');
        const msgId = parseInt($msgElement.attr('data-msg-id'));
        const sessionId = jQuery('#ass-current-session-id').val();

        if (msgId == undefined || msgId == null || msgId < 1 || sessionId == undefined || sessionId == null || sessionId == '') {
            showToast({
                message: __('Unable to save Message', 'assistini'),
                type: 'danger'
            });
            return;
        }
        let msgEntry = chats[sessionId].find(obj => obj.c_id === msgId);
        let title = msgEntry.ai_output.title;
        let markdownText = msgEntry.ai_output.content;
        let focusKeyword = msgEntry.ai_output.focus_keyword;
        let keywords = msgEntry.ai_output.keywords;
        let metaDescription = msgEntry.ai_output.meta_description;

        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            async: false,
            data: {
                'action': 'assi_chat_save_msg_as_draft',
                'title': title,
                'message': markdownText,
                'focus_keyword': focusKeyword,
                'keywords': keywords,
                'meta_description': metaDescription,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.result != undefined && data.result == false && data.error != undefined) {
                    if (data.error == 'nonce') {
                        showNonceNotice();
                    } else {
                        showToast({
                            message: data.error_message != undefined ? data.error_message : '',
                            type: 'danger'
                        });
                    }
                } else if (data.result != undefined && data.result == true && data.edit != null && data.edit != '') {
                    let sessionId = jQuery('#ass-current-session-id').val();
                    insertMessage({
                        sessionId: sessionId,
                        text: '<i class="bi bi-check-lg ass-size-14 me-1 text-success"></i>' + __('Your Content is saved as draft in your WordPress Blog.', 'assistini') + '<br><a target="_blank" rel="noopener noreferrer" href="' + data.edit + '">' + __('Click here to edit and publish the content') + '</a>',
                    });
                    return;
                }
                showToast({ type: 'danger' });
            },
            error: function () {
                showToast({ type: 'danger' });
            }
        });
        return;
    }
});
jQuery(document).on('click', '.ass-chat-action-btn', function () {
    const action = jQuery(this).attr('data-action');
    if (action == 'copy') {
        let $parent = jQuery(this).closest('.ass-chat-msg-sender');
        let msgId = parseInt($parent.attr('data-msg-id'));
        let sessionId = jQuery('#ass-current-session-id').val();
        let msgEntry = chats[sessionId].find(obj => obj.c_id === msgId);
        if (navigator.clipboard && navigator.clipboard.writeText) {
            if (msgEntry != undefined && msgEntry != null) {
                let text = (msgEntry.ai_output.title != undefined && msgEntry.ai_output.title != null ? '# ' + msgEntry.ai_output.title + '\n\n' : '') + (msgEntry.ai_output.content != undefined && msgEntry.ai_output.content != null ? msgEntry.ai_output.content : '');
                jQuery(this).removeClass('btn-outline-primary').addClass('btn-success');
                changeText(jQuery(this), __('Copied', 'assistini'));
                navigator.clipboard.writeText(text).then(function () {
                    showToast({
                        message: __('Copied to Clipboard', 'assistini'),
                        type: 'primary'
                    });
                });
            }

        }
    }
    if (action == 'save') {
        const $msgElement = jQuery(this).closest('.ass-chat-msg-sender');
        const msgId = parseInt($msgElement.attr('data-msg-id'));
        const sessionId = jQuery('#ass-current-session-id').val();

        if (msgId == undefined || msgId == null || msgId < 1 || sessionId == undefined || sessionId == null || sessionId == '') {
            showToast({
                message: __('Unable to save Message', 'assistini'),
                type: 'danger'
            });
            return;
        }
        let msgEntry = chats[sessionId].find(obj => obj.c_id === msgId);
        let title = msgEntry.ai_output.title;
        let markdownText = msgEntry.ai_output.content;
        let focusKeyword = msgEntry.ai_output.focus_keyword;
        let keywords = msgEntry.ai_output.keywords;
        let metaDescription = msgEntry.ai_output.meta_description;

        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            async: false,
            data: {
                'action': 'assi_chat_save_msg_as_draft',
                'title': title,
                'message': markdownText,
                'focus_keyword': focusKeyword,
                'keywords': keywords,
                'meta_description': metaDescription,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.result != undefined && data.result == false && data.error != undefined) {
                    if (data.error == 'nonce') {
                        showNonceNotice();
                    } else {
                        showToast({
                            message: data.error_message != undefined ? data.error_message : '',
                            type: 'danger'
                        });
                    }
                } else if (data.result != undefined && data.result == true && data.edit != null && data.edit != '') {
                    let sessionId = jQuery('#ass-current-session-id').val();
                    insertMessage({
                        sessionId: sessionId,
                        text: '<i class="bi bi-check-lg ass-size-14 me-1 text-success"></i>' + __('Your Blogpost is saved as draft in your WordPress Blog.', 'assistini') + '<br><a target="_blank" rel="noopener noreferrer" href="' + data.edit + '">' + __('Click here to edit and publish the blog post') + '</a>',
                    });
                    return;
                }
                showToast({ type: 'danger' });
            },
            error: function () {
                showToast({ type: 'danger' });
            }
        });
        return;
    }
});

function loadSelectTemplates(templateId = 0) {
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_get_templates',
            'type': 'select',
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == true && data.html != null) {
                jQuery('.ass-chat-control-template').html(data.html);
                if (data.template_data != undefined && data.template_data != null) {
                    userTemplates = data.template_data;
                    if (data.count_templates != undefined && data.user_data.max_templates != undefined) {
                        proxyLiveData.maxTemplates = data.user_data.max_templates;
                        proxyLiveData.templatesLeft = data.user_data.max_templates - parseInt(data.count_templates);
                    } else if (assi_plugin_data != undefined && data.count_templates != undefined) {
                        proxyLiveData.templatesLeft = assi_plugin_data.user_account.plan.max_templates - parseInt(data.count_templates);
                    }
                }
                if (data.global_alerts != undefined) {
                    if (typeof data.global_alerts == 'object') {
                        proxyLiveData.globalAlerts = data.global_alerts;
                    } else {
                        proxyLiveData.globalAlerts = {};
                    }
                }
            } else if (data.error != undefined && data.error_message != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message,
                        type: 'danger'
                    });
                }
            } else {
                showToast({ type: 'danger' });
            }
            if (templateId > 0) {
                jQuery('.ass-chat-control-template').val(templateId);
                let selectedTemplate = userTemplates.find(x => x.id == templateId && x.is_system == 0);
                if (selectedTemplate != undefined && selectedTemplate != null) {
                    jQuery('#ass-chat-control-language').val(selectedTemplate.language);
                    jQuery('#ass-chat-control-tone').val(selectedTemplate.tone);
                    jQuery('#ass-chat-control-pov').val(selectedTemplate.point_of_view);
                    jQuery('#ass-chat-control-length').val(selectedTemplate.content_length);
                }
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
}

jQuery(document).on('click', '.ass-option-pov-info', function () {
    jQuery('#ass-modal-chat-pov-info').modal('show');
});
jQuery(document).on('click', '.ass-option-length-info', function () {
    jQuery('#ass-modal-chat-length-info').modal('show');
});
jQuery(document).on('click', '.ass-ai-editor-selection', function () {
    jQuery('#ass-modal-ai-editor-selection').modal('show');
});
jQuery(document).on('click', '.ass-chat-sidebar-clickable-disabled', function () {
    openUpgradeModal('chat');
});
jQuery(document).on('click', '.ass-option-info', function () {
    let action = jQuery(this).attr('data-action');
    jQuery('#ass-modal-general-info > .modal-dialog').hide();
    jQuery('#ass-modal-general-info > .modal-dialog[data-id="' + action + '"]').show();
    jQuery('#ass-modal-general-info').modal('show');
});

function moveElementToFirst($element) {
    const $container = jQuery('.ass-chat-list-items');
    const $items = $container.children('.ass-chat-list-item');
    const currentIndex = $items.index($element);

    if (currentIndex === 0)
        return;

    const elementHeight = $element.outerHeight(true);
    const $clone = $element.clone();
    $clone.css('margin-top', `-${elementHeight}px`);
    $container.prepend($clone);
    $element.css('z-index', '19');
    $element.animate(
            {opacity: '0', marginTop: `-${elementHeight}px`},
            200,
            () => {
        $element.remove();
        $clone.animate({marginTop: '0px'}, 200);
    }
    );
}
jQuery('.ass-chat-control-language, .ass-chat-control-tone, .ass-chat-control-pov, .ass-chat-control-length').on('change', function () {
    let selectedLanguage = jQuery('.ass-chat-control-language').find(':selected').val();
    let selectedTone = jQuery('.ass-chat-control-tone').find(':selected').val();
    let selectedView = jQuery('.ass-chat-control-pov').find(':selected').val();
    let selectedLength = jQuery('.ass-chat-control-length').find(':selected').val();
    if (selectedLanguage != defaultSettings.content_creator.language || selectedTone != defaultSettings.content_creator.tone || selectedView != defaultSettings.content_creator.point_of_view || selectedLength != defaultSettings.content_creator.content_length) {
        jQuery('.ass-chat-control-settings-save').show();
    } else {
        jQuery('.ass-chat-control-settings-save').hide();
    }
});
jQuery('.ass-chat-control-settings-save').on('click', function () {
    let selectedLanguage = jQuery('.ass-chat-control-language').find(':selected').val();
    let selectedTone = jQuery('.ass-chat-control-tone').find(':selected').val();
    let selectedView = jQuery('.ass-chat-control-pov').find(':selected').val();
    let selectedLength = jQuery('.ass-chat-control-length').find(':selected').val();

    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_settings_save',
            'type': 'content_creator',
            'language': selectedLanguage,
            'tone': selectedTone,
            'point_of_view': selectedView,
            'content_length': selectedLength,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message != undefined ? data.error_message : '',
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true) {
                jQuery('.ass-chat-control-settings-save').hide();
                defaultSettings.content_creator.language = selectedLanguage;
                defaultSettings.content_creator.tone = selectedTone;
                defaultSettings.content_creator.point_of_view = selectedView;
                defaultSettings.content_creator.content_length = selectedLength;
                showToast({
                    message: __('Your settings have been saved.', 'assistini'),
                    type: 'success'
                });
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
});
// !SECTION

// SECTION: Templates
document.addEventListener("DOMContentLoaded", function () {
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.forEach(function (popoverTriggerEl) {
        new bootstrap.Popover(popoverTriggerEl);
    });
    initializeToolTips();
});

function initializeToolTips() {
    let tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.forEach(function (tooltipTriggerEl) {
        new bootstrap.Tooltip(tooltipTriggerEl, {customClass: 'ass-tooltip'});
    });
}

jQuery(document).on('click', '.ass-templates-pagination a', function (e) {
    e.preventDefault();
    const newPage = parseInt(jQuery(this).attr('data-page'));
    let type = jQuery('.ass-templates-nav-active').attr('data-type');
    loadPagination(type, newPage);
    showTemplates(type, newPage);
});

function loadPagination(type = 'all', currentPage = 1) {
    let maxItems = 0;
    let chatTemplates = userTemplates.filter(obj => obj.type == TEMPLATE_TYPE_CHAT || obj.type == TEMPLATE_TYPE_USER);
    if (type == 'all') {
        maxItems = chatTemplates.length;
    } else if (type == 'my') {
        maxItems = chatTemplates.filter(obj => obj.is_system === 0).length;
    } else if (type == 'system') {
        maxItems = chatTemplates.filter(obj => obj.is_system === 1).length;
    } else {
        return;
    }
    if (maxItems <= 0 || TEMPLATES_MAX_PER_PAGE <= 0 || currentPage <= 0) {
        return;
    }
    let maxPages = 1;
    if (maxItems > TEMPLATES_MAX_PER_PAGE) {
        maxPages = Math.ceil(maxItems / TEMPLATES_MAX_PER_PAGE);
    }
    let pagination = '';
    if (currentPage > 1) {
        pagination += '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage - 1) + '"><i class="bi bi-caret-left-fill"></i></a></li>';
    } else {
        pagination += '<li class="page-item disabled"><a class="page-link" href="#" data-page="' + (currentPage - 1) + '"><i class="bi bi-caret-left-fill"></i></a></li>';
    }
    for (let i = 1; i <= maxPages; i++) {
        if (i == currentPage) {
            pagination += '<li class="page-item active"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>';
        } else {
            pagination += '<li class="page-item"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>';
        }
    }
    if (currentPage < maxPages) {
        pagination += '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage + 1) + '"><i class="bi bi-caret-right-fill"></i></a></li>';
    } else {
        pagination += '<li class="page-item disabled"><a class="page-link" href="#" data-page="' + (currentPage + 1) + '"><i class="bi bi-caret-right-fill"></i></a></li>';
    }
    jQuery('.ass-templates-pagination').html(pagination);
}
function showTemplates(type = 'all', page = 1) {
    let entrys = {};
    if (type == 'all') {
        entrys = userTemplates.filter(obj => obj.type === TEMPLATE_TYPE_CHAT || obj.type === TEMPLATE_TYPE_USER);
    }
    if (type == 'my') {
        entrys = userTemplates.filter(obj => (obj.type === TEMPLATE_TYPE_CHAT || obj.type === TEMPLATE_TYPE_USER) && obj.is_system === 0);
    }
    if (type == 'system') {
        entrys = userTemplates.filter(obj => (obj.type === TEMPLATE_TYPE_CHAT || obj.type === TEMPLATE_TYPE_USER) && obj.is_system === 1);
    }
    let startIndex = (TEMPLATES_MAX_PER_PAGE * (page - 1));
    if (startIndex < entrys.length) {
        let nextEntries = entrys.slice(startIndex, startIndex + TEMPLATES_MAX_PER_PAGE);
        let html = '';
        for (let i = 0; i < nextEntries.length; i++) {
            html += '<div class="col-12 col-md-6 col-lg-4 mt-3 ass-templates-item" data-id="' + nextEntries[i].id + '" data-reference="' + nextEntries[i].reference + '" data-language="' + nextEntries[i].language + '" data-tone="' + nextEntries[i].tone + '" data-pov="' + nextEntries[i].point_of_view + '" data-length="' + nextEntries[i].content_length + '">';
            html += '<div class="card ass-templates-card-shadow m-0 w-100 h-100' + (nextEntries[i].disabled == true ? ' ass-template-disabled-bg' : '') + '">';
            html += '<div class="row">';
            html += '<div class="col-12 p-0">';
            html += '<div class="d-flex" style="font-weight: 500;">';
            html += '<div class="ass-templates-item-name text-truncate flex-grow-1 me-2">' + nextEntries[i].header + '</div>';
            if (nextEntries[i].is_system != 1 && !(nextEntries[i].blog_access != undefined && nextEntries[i].blog_access == true && nextEntries[i].blog_access_owner_id != undefined && nextEntries[i].blog_access_owner_id > 0)) {
                html += '<div class="dropdown-center">';
                html += '<i class="bi bi-three-dots-vertical ass-templates-options-single" data-bs-toggle="dropdown"></i>';
                html += '<ul class="dropdown-menu ass-size-13 py-0 px-1" style="min-width: 0 !important;">';
                if (nextEntries[i].disabled == false) {
                    html += '<li class="m-0"><span class="dropdown-item ass-size-13 ass-templates-quickmenu-btn" data-action="edit" style="cursor: pointer;">' + __('Edit', 'assistini') + '</span></li>';
                    html += '<hr class="m-0">';
                }
                html += '<li class="m-0"><span class="dropdown-item ass-size-13 ass-templates-quickmenu-btn" data-action="delete" style="cursor: pointer;">' + __('Delete', 'assistini') + '</span></li>';
                html += '</ul>';
                html += '</div>';
            }
            html += '</div>';
            html += '</div>';
            html += '<div class="ass-templates-item-prompt col-12 my-3 ass-size-13 ass-truncate-lines-2">' + nextEntries[i].text + '</div>';
            html += '</div>';
            html += '<div class="row justify-content-between mt-auto align-items-center ass-size-13">';
            if (nextEntries[i].is_system == 1) {
                html += '<div class="ass-template-badge badge bg-secondary col-auto align-items-center d-flex">' + __('by Assistini', 'assistini') + '</div>';
                html += '<a href="#/chat?sys_template_id=' + nextEntries[i].id + '" class="ass-templates-start-chat col-auto btn btn-sm btn-outline-primary">' + __('Create Content', 'assistini') + '</a>';
            } else {
                if (nextEntries[i].blog_access != undefined && nextEntries[i].blog_access == true && nextEntries[i].blog_access_owner_id != undefined) {
                    if (nextEntries[i].blog_access_owner_id > 0) {
                        html += '<div class="ass-template-badge badge bg-primary col-auto align-items-center d-flex">' + __('Shared by', 'assistini') + ' ' + (nextEntries[i].blog_access_owner_display_name != undefined ? nextEntries[i].blog_access_owner_display_name : '-') + '</div>';
                    } else {
                        html += '<div class="ass-template-badge badge bg-primary col-auto align-items-center d-flex">' + __('Shared by You', 'assistini') + '</div>';
                    }
                }
                html += '<div class="col-auto"></div>';
                html += '<a href="#/chat?template_id=' + nextEntries[i].id + '" class="ass-templates-start-chat col-auto btn btn-sm btn-outline-primary' + (nextEntries[i].disabled == true ? ' disabled ass-template-disabled-btn' : '') + '">' + __('Create Content', 'assistini') + '</a>';
            }
            html += '</div>';
            html += '</div>';
            html += '</div>';
        }
        if (html != '') {
            jQuery('.ass-templates-list').html(html);
            jQuery('.ass-templates-list-placeholder').hide();
            jQuery('.ass-templates-list-empty').hide();
            jQuery('.ass-templates-list').show();
            return;
        }
    }
    jQuery('.ass-templates-list-placeholder').hide();
    jQuery('.ass-templates-list').hide();
    jQuery('.ass-templates-list-empty').show();
}
jQuery(document).on('click', '.ass-oauth-start-btn', function (e) {
    e.preventDefault();
    let url = 'https://apiwp.assistini.com/auth/';
    url = url + '?blog_user_token=' + jQuery('#ass-plugin-token').val();
    let location = window.location.protocol + '//' + window.location.hostname;

    let language = 'en';
    if (assi_plugin_data?.blog_language != undefined && assi_plugin_data.blog_language == 'de_DE') {
        language = 'de';
    }

    url = encodeURI(url + '&location=' + location);
    url = encodeURI(url + '&lang=' + language);
    window.open(url, 'Assistini OAuth', "width=650,height=800,scrollbars=yes,toolbar=no,status=no,resizable=no,menubar=no,location=no,directories=no,top=20,left=20");
});

window.addEventListener('message', function (e) {
    let data = JSON.parse(e.data);
    if (data.action == 'assAuth') {
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            async: false,
            data: {
                'action': 'assi_auth_save',
                'plan_id': (data?.user_data?.ass_plan_id != undefined ? data.user_data.ass_plan_id : 0),
                'access_token': data.ass_access_token,
                'display_name': (data.ass_display_name != undefined ? data.ass_display_name : ''),
                'credits_open': (data?.user_data?.ass_words_open != undefined ? data.user_data.ass_words_open : 0),
                'credits_total': (data?.user_data?.ass_words_total != undefined ? data.user_data.ass_words_total : 0),
                'first_name': (data.ass_first_name != undefined ? data.ass_first_name : ''),
                'last_name': (data.ass_last_name != undefined ? data.ass_last_name : ''),
                'max_chats': (data?.user_data?.ass_plan_max_count_chats != undefined ? data.user_data.ass_plan_max_count_chats : 0),
                'max_templates': (data?.user_data?.ass_plan_max_count_template != undefined ? data.user_data.ass_plan_max_count_template : 0),
                'user_data': data.user_data,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.result != undefined && data.result == false && data.error != undefined) {
                    if (data.error == 'nonce') {
                        showNonceNotice();
                    } else {
                        showToast({
                            message: data.error_message != undefined ? data.error_message : '',
                            type: 'danger'
                        });
                    }
                } else if (data.result != undefined && data.result == true) {
                    showToast({
                        message: __('Authorization was successful', 'assistini')
                    });
                    window.location.href = `#/account`;
                    window.location.reload();
                } else {
                    showToast({ type: 'danger' });
                }
            },
            error: function () {
                showToast({ type: 'danger' });
            }
        });
    }
});

jQuery(document).on('click', '.ass-templates-add', function () {
    if (proxyLiveData.templatesLeft <= 0) {
        openUpgradeModal('template');
        return;
    }
    jQuery('#ass-templates-add-blog-access').prop('checked', false);
    if (proxyLiveData.planId <= ACCOUNT_PLAN_FREE) {
        jQuery('.ass-templates-add-blog-access-ctn').addClass('ass-templates-disabled-checkbox');
        jQuery('#ass-templates-add-blog-access').prop('disabled', true);
        jQuery('.ass-templates-add-blog-access-badge').show();
        jQuery('.ass-modal-templates-add-prompt-action[data-action="analyze"]').prop('disabled', true);
        jQuery('.ass-modal-templates-add-prompt-action-analyze-badge').show();   
    } else {
        jQuery('.ass-templates-add-blog-access-ctn').removeClass('ass-templates-disabled-checkbox');
        jQuery('#ass-templates-add-blog-access').prop('disabled', false);
        jQuery('.ass-templates-add-blog-access-badge').hide();
        jQuery('.ass-modal-templates-add-prompt-action[data-action="analyze"]').prop('disabled', false);
        jQuery('.ass-modal-templates-add-prompt-action-analyze-badge').hide();
    }
    resetModalAddSidebar();
    jQuery('#ass-modal-templates-add').modal('show');
});

jQuery(document).on('click', '.ass-templates-list-empty-card', function () {
    jQuery('#ass-templates-add-blog-access').prop('checked', false);
    if (proxyLiveData.planId <= ACCOUNT_PLAN_FREE) {
        jQuery('.ass-templates-add-blog-access-ctn').addClass('ass-templates-disabled-checkbox');
        jQuery('#ass-templates-add-blog-access').prop('disabled', true);
        jQuery('.ass-templates-add-blog-access-badge').show();
        jQuery('.ass-modal-templates-add-prompt-action[data-action="analyze"]').prop('disabled', true);
        jQuery('.ass-modal-templates-add-prompt-action-analyze-badge').show();   
    } else {
        jQuery('.ass-templates-add-blog-access-ctn').removeClass('ass-templates-disabled-checkbox');
        jQuery('#ass-templates-add-blog-access').prop('disabled', false);
        jQuery('.ass-templates-add-blog-access-badge').hide();
        jQuery('.ass-modal-templates-add-prompt-action[data-action="analyze"]').prop('disabled', false);
        jQuery('.ass-modal-templates-add-prompt-action-analyze-badge').hide();
    }
    resetModalAddSidebar();
    jQuery('#ass-modal-templates-add').modal('show');
})

jQuery(document).on('click', '.ass-templates-quickmenu-btn', function () {
    let $templateItem = jQuery(this).closest('.ass-templates-item');
    switch (jQuery(this).attr('data-action')) {
        case 'edit':
            let id = parseInt($templateItem.attr('data-id'));
            let entry = userTemplates.find(x => x.id == id && x.is_system == 0);
            if (entry != undefined && entry != null) {
                let name = entry.header;
                let prompt = entry.text;
                let reference = entry.reference;
                let language = entry.language;
                let tone = entry.tone;
                let pointOfView = entry.point_of_view;
                let contentLength = entry.content_length;

                jQuery('#ass-modal-templates-edit-id').val(id);
                jQuery('#ass-templates-edit-name').val(name);
                jQuery('#ass-templates-edit-prompt').val(prompt);
                jQuery('.ass-templates-edit-prompt-length').text(prompt.length);
                jQuery('#ass-templates-edit-reference').val(reference);
                jQuery('.ass-templates-edit-reference-length').text(reference.length);
                jQuery('.ass-templates-edit-language').val(language);
                jQuery('.ass-templates-edit-tone').val(tone);
                jQuery('.ass-templates-edit-view').val(pointOfView);
                jQuery('.ass-templates-edit-length').val(contentLength);
                if (entry?.blog_access != undefined && entry.blog_access == true) {
                    jQuery('#ass-templates-edit-blog-access').prop('checked', true);
                } else {
                    jQuery('#ass-templates-edit-blog-access').prop('checked', false);
                }
                
                if (proxyLiveData.planId <= ACCOUNT_PLAN_FREE) {
                    jQuery('#ass-templates-edit-blog-access').prop('checked', false);
                    jQuery('.ass-templates-edit-blog-access-ctn').addClass('ass-templates-disabled-checkbox');
                    jQuery('#ass-templates-edit-blog-access').prop('disabled', true);
                    jQuery('.ass-templates-edit-blog-access-badge').show();
                    jQuery('.ass-modal-templates-add-prompt-action[data-action="analyze"]').prop('disabled', true);
                    jQuery('.ass-modal-templates-add-prompt-action-analyze-badge').show();
                } else {
                    jQuery('.ass-templates-edit-blog-access-ctn').removeClass('ass-templates-disabled-checkbox');
                    jQuery('#ass-templates-edit-blog-access').prop('disabled', false);
                    jQuery('.ass-templates-edit-blog-access-badge').hide();
                    jQuery('.ass-modal-templates-add-prompt-action[data-action="analyze"]').prop('disabled', false);
                    jQuery('.ass-modal-templates-add-prompt-action-analyze-badge').hide();
                }

                jQuery('#ass-modal-templates-edit').modal('show');
                break;
            } else {
                showToast({ type: 'danger' });
                break;
            }
        case 'delete':
            jQuery.ajax({
                url: ajaxurl,
                type: "POST",
                cache: false,
                data: {
                    'action': 'assi_delete_template',
                    'template_id': parseInt($templateItem.attr('data-id')),
                    'assi_security_nonce': jQuery('#assi_security_nonce').val(),
                },
                beforeSend: function () {
                    showToast({
                        message: __('Deleting your template...', 'assistini'),
                    });
                },
                success: function (data) {
                    data = JSON.parse(data);
                    if (data.result != undefined && data.result == true) {
                        showToast({
                            message: __('Your template has been deleted.', 'assistini')
                        });
                        reloadTemplates(jQuery('.ass-templates-nav-active').attr('data-type'));
                    } else if (data.error != undefined && data.error_message != undefined) {
                        if (data.error == 'nonce') {
                            showNonceNotice();
                        } else {
                            showToast({
                                message: data.error_message,
                                type: 'danger'
                            });
                        }
                    } else {
                        showToast({ type: 'danger' });
                    }
                },
                error: function () {
                    showToast({ type: 'danger' });
                }
            });
            break;
    }
});

function reloadTemplates(type = 'all', openAddModal = false) {
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_get_templates',
            'type': type,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-templates-list').html('');
            jQuery('.ass-templates-list-empty').hide();
            jQuery('.ass-templates-list-placeholder').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == true) {
                if (data.user_template_count != undefined && data.user_template_count != null && data.user_data.max_templates != undefined && data.user_data.max_templates != null) {
                    proxyLiveData.maxTemplates = data.user_data.max_templates;
                    let templatesLeft = (parseInt(data.user_data.max_templates) - parseInt(data.user_template_count));
                    if (templatesLeft < 0) {
                        templatesLeft = 0;
                    }
                    proxyLiveData.templatesLeft = templatesLeft;
                } else if (data.user_template_count != undefined && data.user_template_count != null) {
                    let templatesLeft = (assi_plugin_data?.user_account?.plan?.max_templates - parseInt(data.user_template_count));
                    if (templatesLeft < 0) {
                        templatesLeft = 0;
                    }
                    proxyLiveData.templatesLeft = templatesLeft;
                }
                if (data.global_alerts != undefined) {
                    if (typeof data.global_alerts == 'object') {
                        proxyLiveData.globalAlerts = data.global_alerts;
                    } else {
                        proxyLiveData.globalAlerts = {};
                    }
                }
                if (data.template_data != undefined && data.template_data != null && typeof data.template_data == 'object') {
                    userTemplates = data.template_data;
                    loadPagination(type, 1);
                    showTemplates(type, 1);
                }
                if (openAddModal) {
                    jQuery('.ass-templates-add').trigger('click');
                }
            } else if (data.error != undefined && data.error_message != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message,
                        type: 'danger'
                    });
                }
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-templates-list-placeholder').hide();
        }
    })
}

jQuery(document).on('click', '.ass-templates-add-save-btn', function () {
    if (proxyLiveData.templatesLeft <= 0) {
        openUpgradeModal('template');
        return;
    }
    let emptyFields = false;
    let name = jQuery('#ass-templates-add-name').val();
    if (name == undefined || name == '') {
        emptyFields = true;
        jQuery('#ass-templates-add-name').addClass('ass-red-border');
        setTimeout(() => {
            jQuery('#ass-templates-add-name').removeClass('ass-red-border');
        }, 2500);
    }
    let prompt = jQuery('#ass-templates-add-prompt').val();
    if (prompt == undefined || prompt == '') {
        emptyFields = true;
        jQuery('#ass-templates-add-prompt').addClass('ass-red-border');
        setTimeout(() => {
            jQuery('#ass-templates-add-prompt').removeClass('ass-red-border');
        }, 2500);
    }
    if (emptyFields) {
        showToast({
            message: __('Not all Fields filled!', 'assistini'),
            type: 'danger'
        });
        return;
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_save_template',
            'name': jQuery('#ass-templates-add-name').val(),
            'prompt': jQuery('#ass-templates-add-prompt').val(),
            'reference_text': jQuery('#ass-templates-add-reference').val(),
            'language': jQuery('.ass-templates-add-language').find(':selected').val(),
            'tone': jQuery('.ass-templates-add-tone').find(':selected').val(),
            'view': jQuery('.ass-templates-add-view').find(':selected').val(),
            'content_length': jQuery('.ass-templates-add-length').find(':selected').val(),
            'blog_access': (jQuery('#ass-templates-add-blog-access').is(':checked') ? 1 : 0),
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-templates-add-save-btn').prop('disabled', true);
            jQuery('.ass-templates-add-save-text').hide();
            jQuery('.ass-templates-add-save-loader').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == true) {
                jQuery('#ass-modal-templates-add').modal('hide');
                showToast({
                    message: __('Your template has been saved.', 'assistini')
                });
                reloadTemplates(jQuery('.ass-templates-nav-active').attr('data-type'));
                loadSelectTemplates();
            } else if (data.error != undefined && data.error_message != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message,
                        type: 'danger'
                    });
                }
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-templates-add-save-text').show();
            jQuery('.ass-templates-add-save-loader').hide();
            jQuery('.ass-templates-add-save-btn').prop('disabled', false);
        },
    });
});

jQuery(document).on('click', '.ass-templates-edit-save-btn', function () {
    let emptyFields = false;
    let name = jQuery('#ass-templates-edit-name').val();
    if (name == undefined || name == '') {
        emptyFields = true;
        jQuery('#ass-templates-edit-name').addClass('ass-red-border');
        setTimeout(() => {
            jQuery('#ass-templates-edit-name').removeClass('ass-red-border');
        }, 2500);
    }
    let prompt = jQuery('#ass-templates-edit-prompt').val();
    if (prompt == undefined || prompt == '') {
        emptyFields = true;
        jQuery('#ass-templates-edit-prompt').addClass('ass-red-border');
        setTimeout(() => {
            jQuery('#ass-templates-edit-prompt').removeClass('ass-red-border');
        }, 2500);
    }
    if (emptyFields) {
        showToast({
            message: __('Not all Fields filled!', 'assistini'),
            type: 'danger'
        });
        return;
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_edit_template',
            'id': jQuery('#ass-modal-templates-edit-id').val(),
            'name': jQuery('#ass-templates-edit-name').val(),
            'prompt': jQuery('#ass-templates-edit-prompt').val(),
            'reference_text': jQuery('#ass-templates-edit-reference').val(),
            'language': jQuery('.ass-templates-edit-language').find(':selected').val(),
            'tone': jQuery('.ass-templates-edit-tone').find(':selected').val(),
            'view': jQuery('.ass-templates-edit-view').find(':selected').val(),
            'content_length': jQuery('.ass-templates-edit-length').find(':selected').val(),
            'blog_access': (jQuery('#ass-templates-edit-blog-access').is(':checked') ? 1 : 0),
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-templates-edit-save-btn').prop('disabled', true);
            jQuery('.ass-templates-edit-save-text').hide();
            jQuery('.ass-templates-edit-save-loader').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == true) {
                jQuery('#ass-modal-templates-edit').modal('hide');
                showToast({
                    message: __('Your template has been saved.', 'assistini')
                });
                reloadTemplates(jQuery('.ass-templates-nav-active').attr('data-type'));
            } else if (data.error != undefined && data.error_message != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message,
                        type: 'danger'
                    });
                }
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-templates-edit-save-text').show();
            jQuery('.ass-templates-edit-save-loader').hide();
            jQuery('.ass-templates-edit-save-btn').prop('disabled', false);
        },
    });
});

jQuery('#ass-templates-edit-prompt').on('input propertychange', function () {
    jQuery('.ass-templates-edit-prompt-length').text(jQuery(this).val().length);
});
jQuery('#ass-templates-edit-reference').on('input propertychange', function () {
    jQuery('.ass-templates-edit-reference-length').text(jQuery(this).val().length);
});
jQuery('#ass-templates-add-prompt').on('input propertychange', function () {
    jQuery('.ass-templates-add-prompt-length').text(jQuery(this).val().length);
});
jQuery('#ass-templates-add-reference').on('input propertychange', function () {
    jQuery('.ass-templates-add-reference-length').text(jQuery(this).val().length);
});
jQuery('#ass-templates-add-assistant-content').on('input propertychange', function () {
    jQuery('.ass-templates-add-assistant-content-length').text(jQuery(this).val().length);
});
jQuery('#ass-templates-add-structure-content').on('input propertychange', function () {
    jQuery('.ass-templates-add-structure-content-length').text(jQuery(this).val().length);
});
jQuery(document).on('click', '.ass-template-disabled-bg', function (event) {
    if (jQuery(event.target).closest('.ass-templates-options-single, .dropdown-menu').length === 0) {
        openUpgradeModal('template');
    }
});
// !SECTION

// SECTION: Modals
jQuery(document).on('hidden.bs.modal', '.modal', function () {
    const form = jQuery(this).find('form');
    if (form.length > 0) {
        form[0].reset();
    }
});
jQuery(document).on('hidden.bs.modal', '#ass-modal-connection-consent', function () {
    jQuery('#ass-modal-connection-consent-dismissed').modal('show');
});

jQuery(document).on('click', '.ass-templates-nav-btn', function () {
    let type = jQuery(this).attr('data-type');
    if (jQuery(this).hasClass('ass-templates-nav-active')) {
        return;
    }
    jQuery('.ass-templates-nav-btn').removeClass('ass-templates-nav-active');
    jQuery(this).addClass('ass-templates-nav-active');
    loadPagination(type, 1);
    showTemplates(type, 1);
});
jQuery(document).on('click', '.ass-modal-onboarding-confirm', function () {
    jQuery('#ass-modal-onboarding').modal('hide');
    jQuery.post(ajaxurl, {
        action: 'assi_modal_onboarding_close',
        assi_security_nonce: jQuery('#assi_security_nonce').val(),
    });
});
jQuery(document).on('change', '#ass-modal-consent-checkbox', function (e) {
    if (jQuery(this).is(':checked')) {
        jQuery('.ass-modal-connection-consent-save-btn').prop('disabled', false);
    } else {
        jQuery('.ass-modal-connection-consent-save-btn').prop('disabled', true);
    }
});
jQuery(document).on('click', '.ass-modal-connection-consent-save-btn', function () {
    let email = jQuery('#ass-modal-connection-consent-email').val();
    let remove = jQuery('#ass-modal-connection-consent-remove').val();
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_settings_consent_save',
            'consent': 'true',
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message != undefined ? data.error_message : '',
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true) {
                showToast({
                    message: __('Your settings have been saved.', 'assistini'),
                    type: 'success'
                });
                if (email != '') {
                    window.location.href = window.location.href + '?email=' + email;
                }
                if (remove == '1') {
                    window.location.href = window.location.href + '?remove=1';
                }
                window.location.reload();
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
});
jQuery(document).on('click', '.ass-modal-upgrade-bonus-btn', function () {
    window.location.href = '#/account';
});
jQuery(document).on('click', '.ass-modal-templates-add-prompt-action', function (e) {
    e.preventDefault();
    jQuery('.ass-modal-templates-add-sidebar').removeClass('ass-modal-templates-add-sidebar-open');
    jQuery('.ass-modal-templates-add-sidebar').hide();
    let action = jQuery(this).attr('data-action');
    let origin = jQuery(this).attr('data-origin');
    if (action == 'assistant') {
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            data: {
                'action': 'assi_get_blog_posts',
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            },
            beforeSend: function () {
                jQuery('.ass-modal-templates-assistant-posts-list > .ass-modal-templates-assistant-post-item').remove();
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.result == true && data.posts != undefined) {
                    if (data.posts.length > 0) {
                        data.posts.forEach(post => {
                            jQuery('.ass-modal-templates-assistant-posts-list').append(
                                '<li class="ass-modal-templates-assistant-post-item ass-max-w-inherit"><a class="ass-size-14 dropdown-item text-truncate" data-id="' + post.ID + '">' + post.post_title + '</a></li>'
                            );
                        });
                    }
                } else {
                    if (data.error != undefined && data.error == 'nonce') {
                        showNonceNotice();
                    } else {
                        showToast({
                            message: data.error_message != undefined ? data.error_message : '',
                            type: 'danger' 
                        });
                    }
                }
            },
            error: function () {
                showToast({ type: 'danger' });
            }
        });
    }
    if (action == 'structure') {
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            data: {
                'action': 'assi_get_blog_posts',
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            },
            beforeSend: function () {
                jQuery('.ass-modal-templates-structure-posts-list > .ass-modal-templates-structure-post-item').remove();
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.result == true && data.posts != undefined) {
                    if (data.posts.length > 0) {
                        data.posts.forEach(post => {
                            jQuery('.ass-modal-templates-structure-posts-list').append(
                                '<li class="ass-modal-templates-structure-post-item ass-max-w-inherit"><a class="ass-size-14 dropdown-item text-truncate" data-id="' + post.ID + '">' + post.post_title + '</a></li>'
                            );
                        });
                    }
                } else {
                    if (data.error != undefined && data.error == 'nonce') {
                        showNonceNotice();
                    } else {
                        showToast({
                            message: data.error_message != undefined ? data.error_message : '',
                            type: 'danger' 
                        });
                    }
                }
            },
            error: function () {
                showToast({ type: 'danger' });
            }
        });
    }
    if (action == 'analyze') {
        let prompt = jQuery('#ass-templates-' + origin + '-prompt').val();
        if (prompt == undefined || prompt == '' || prompt.length < 150) {
            jQuery('#ass-templates-' + origin + '-prompt').addClass('ass-red-border');
            setTimeout(() => {
                jQuery('#ass-templates-' + origin + '-prompt').removeClass('ass-red-border');
            }, 2500);
            return;
        }
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            data: {
                'action': 'assi_template_analyze_prompt',
                'prompt': prompt,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            },
            beforeSend: function () {
                jQuery('.ass-modal-templates-add-analyze-ctn').hide();
                jQuery('.ass-modal-templates-add-analyze-reload').hide();
                jQuery('.ass-modal-templates-add-analyze-loader').show();
                jQuery('.ass-modal-templates-add-analyze-results').html('');
                startProgressCircle('.ass-modal-templates-add-analyze-loader-circle', '.ass-modal-templates-add-analyze-loader-circle-text', 15);
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.result == true && data.content != undefined) {
                    if (data.content?.improvements != undefined) {
                        let iteration = 1;
                        data.content.improvements = sortArrayWithFixedFirst(data.content.improvements);
                        data.content.improvements.forEach(imp => {
                            jQuery('.ass-modal-templates-add-analyze-results').append(`
                                <div class="ass-modal-templates-add-analyze-result-item d-flex flex-column border rounded px-2 pt-2 pb-2">
                                    <div class="d-flex gap-3">
                                        <div class="ass-modal-templates-add-analyze-result-item-rating-ctn d-flex justify-content-center align-items-center">
                                            <span class="ass-modal-templates-add-analyze-result-item-rating-text">${imp.rating}</span>
                                            <span class="ass-modal-templates-add-analyze-result-item-rating-text-info">/100</span>
                                            <div class="ass-modal-templates-add-analyze-result-item-rating" data-name="${imp.type}"></div>
                                        </div>
                                        <div class="ass-modal-templates-add-analyze-result-item-text d-flex flex-column gap-1 justify-content-center">
                                            <span class="ass-fw-500">${imp.type}</span>
                                            <span class="ass-size-13">${imp.title}</span>
                                        </div>
                                    </div>
                                    ${data.content?.revised_prompt != undefined && iteration == 1 ? `
                                        <hr>
                                        <div class="d-flex flex-column">
                                            <div class="d-flex justify-content-between">
                                                <span class="ass-fw-500 ass-size-14">${__('Optimized prompt', 'assistini')}:</span>
                                                <div class="d-flex align-items-center gap-1">
                                                    <span class="ass-modal-templates-add-analyze-revised-action ass-size-14 px-1" data-type="${origin}" data-action="copy"><i class="bi bi-copy"></i></span>
                                                    <span class="ass-modal-templates-add-analyze-revised-action ass-size-14 px-1" data-type="${origin}" data-action="insert"><i class="bi bi-box-arrow-in-left"></i></span>
                                                    <div class="ass-modal-templates-add-analyze-revised-toggle px-1">
                                                        <div class="ass-transition-all">
                                                            <i class="bi bi-sm bi-caret-down-fill ass-size-14"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <span class="ass-size-13 ass-modal-templates-add-analyze-revised-truncated ass-text-truncate-3">${data.content.revised_prompt}</span>
                                            <span class="ass-size-13 ass-modal-templates-add-analyze-revised-full" style="display:none;">${data.content.revised_prompt}</span>
                                        </div>
                                    ` : ''}
                                    ${imp.improvement =! undefined && imp.improvement != '' ? `
                                        <hr>
                                        <div class="d-flex flex-column">
                                            <span class="ass-size-13">${imp.improvement}</span>
                                        </div>
                                    ` : ''}
                                </div>    
                            `);
                            jQuery('.ass-modal-templates-add-analyze-result-item-rating[data-name="' + imp.type + '"]').circleProgress({
                                value: imp.rating / 100,
                                size: 65,
                                startAngle: -Math.PI / 2,
                                lineCap: 'round',
                                fill: {
                                    color: (imp.rating >= 80 ? '#198754' : (imp.rating >= 40 ? '#ffc107' : '#dc3545'))
                                }
                            });
                            iteration++;
                        });
                    }
                } else {
                    if (data.error != undefined && data.error == 'nonce') {
                        showNonceNotice();
                    } else {
                        showToast({ type: 'danger' });
                    }
                }
            },
            error: function () {
                showToast({ type: 'danger' });
            },
            complete: function () {
                finishProgressCircle('.ass-modal-templates-add-analyze-loader-circle', '.ass-modal-templates-add-analyze-loader-circle-text');
                setTimeout(() => {
                    jQuery('.ass-modal-templates-add-analyze-loader').hide();
                    jQuery('.ass-modal-templates-add-analyze-ctn').show();
                    jQuery('.ass-modal-templates-add-analyze-reload').show();    
                }, 1000);   
            }
        });
    }
    setTimeout(() => {
        jQuery('.ass-modal-templates-add-sidebar[data-id="' + action + '"]').show().addClass('ass-modal-templates-add-sidebar-open');
    }, 50);
});

jQuery(document).on('click', '.ass-modal-templates-add-sidebar-close', function () {
    jQuery('.ass-modal-templates-add-sidebar').removeClass('ass-modal-templates-add-sidebar-open');
    setTimeout(() => {
        jQuery('.ass-modal-templates-add-sidebar').hide();
    }, 300);
});
jQuery(document).on('click', '.ass-templates-add-assistant-start-btn', function () {
    let type = jQuery(this).attr('data-type');
    let toggle = jQuery('#ass-modal-templates-add-assistant-toggle[data-type="' + type + '"]').is(':checked');
    let postId = 0;
    let content = '';
    if (!toggle) {
        postId = parseInt(jQuery('#ass-modal-templates-add-assistant-post-dropdown[data-type="' + type + '"]').attr('data-selected-id'));
        if (isNaN(postId) || postId <= 0) {
            jQuery('#ass-modal-templates-add-assistant-post-dropdown[data-type="' + type + '"] > .dropdown-toggle').addClass('ass-red-border');
            setTimeout(() => {
                jQuery('#ass-modal-templates-add-assistant-post-dropdown[data-type="' + type + '"] > .dropdown-toggle').removeClass('ass-red-border');
            }, 2500);
            return;
        }
    } else {
        content = jQuery('#ass-templates-add-assistant-content[data-type="' + type + '"]').val();
        if (content == undefined || content == '') {
            jQuery('#ass-templates-add-assistant-content[data-type="' + type + '"]').addClass('ass-red-border');
            setTimeout(() => {
                jQuery('#ass-templates-add-assistant-content[data-type="' + type + '"]').removeClass('ass-red-border');
            }, 2500);
            return;
        }
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_template_assistant_create',
            'post_id': postId,
            'content': content,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-templates-add-assistant-start-btn[data-type="' + type + '"]').prop('disabled', true);
            jQuery('.ass-templates-add-assistant-start-text[data-type="' + type + '"]').hide();
            jQuery('.ass-templates-add-assistant-start-loader[data-type="' + type + '"]').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result == true && data.content != undefined) {
                if (data.content.prompt_template != undefined && data.content.prompt_template != '') {
                    jQuery('#ass-templates-' + type + '-prompt').val(data.content.prompt_template);
                }
                if (data.content.text_structure != undefined && data.content.text_structure != '') {
                    jQuery('#ass-templates-' + type + '-reference').val(data.content.text_structure);
                }
                if (data.content.language != undefined && data.content.language != '' && jQuery('.ass-templates-' + type + '-language option[value="' + data.content.language + '"]').length > 0) {
                    jQuery('.ass-templates-' + type + '-language').val(data.content.language);
                } else {
                    jQuery('.ass-templates-' + type + '-language').val('');
                }
                if (data.content.tone != undefined && data.content.tone != '' && jQuery('.ass-templates-' + type + '-tone option[value="' + data.content.tone + '"]').length > 0) {
                    jQuery('.ass-templates-' + type + '-tone').val(data.content.tone);
                } else {
                    jQuery('.ass-templates-' + type + '-tone').val('');
                }
                if (data.content.point_of_view != undefined && data.content.point_of_view != '' && jQuery('.ass-templates-' + type + '-view option[value="' + data.content.point_of_view + '"]').length > 0) {
                    jQuery('.ass-templates-' + type + '-view').val(data.content.point_of_view);
                } else {
                    jQuery('.ass-templates-' + type + '-view').val('');
                }
                if (data.content.content_length != undefined && data.content.content_length != '' && jQuery('.ass-templates-' + type + '-length option[value="' + data.content.content_length + '"]').length > 0) {
                    jQuery('.ass-templates-' + type + '-length').val(data.content.content_length);
                } else {
                    jQuery('.ass-templates-' + type + '-length').val('');
                }
                jQuery('.ass-modal-templates-add-sidebar[data-id="assistant"]').removeClass('ass-modal-templates-add-sidebar-open');
                setTimeout(() => {
                    jQuery('.ass-modal-templates-add-sidebar').hide();
                }, 300);
            } else if (data.error != undefined && data.error == 'nonce') {
                showNonceNotice();
            } else {
                showToast({
                    message: (data.error_message != undefined ? data.error_message : ''),
                    type: 'danger'
                });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-templates-add-assistant-start-loader[data-type="' + type + '"]').hide();
            jQuery('.ass-templates-add-assistant-start-text[data-type="' + type + '"]').show();
            jQuery('.ass-templates-add-assistant-start-btn[data-type="' + type + '"]').prop('disabled', false);
        }
    });
});
jQuery(document).on('click', '.ass-templates-add-structure-start-btn', function () {
    let type = jQuery(this).attr('data-type');
    let toggle = jQuery('#ass-modal-templates-add-structure-toggle[data-type="' + type + '"]').is(':checked');
    let postId = 0;
    let content = '';
    let origin = jQuery(this).attr('data-origin');
    if (!toggle) {
        postId = parseInt(jQuery('#ass-modal-templates-add-structure-post-dropdown[data-type="' + type + '"]').attr('data-selected-id'));
        if (isNaN(postId) || postId <= 0) {
            jQuery('#ass-modal-templates-add-structure-post-dropdown[data-type="' + type + '"] > .dropdown-toggle').addClass('ass-red-border');
            setTimeout(() => {
                jQuery('#ass-modal-templates-add-structure-post-dropdown[data-type="' + type + '"] > .dropdown-toggle').removeClass('ass-red-border');
            }, 2500);
            return;
        }
    } else {
        content = jQuery('#ass-templates-add-structure-content[data-type="' + type + '"]').val();
        if (content == undefined || content == '') {
            jQuery('#ass-templates-add-structure-content[data-type="' + type + '"]').addClass('ass-red-border');
            setTimeout(() => {
                jQuery('#ass-templates-add-structure-content[data-type="' + type + '"]').removeClass('ass-red-border');
            }, 2500);
            return;
        }
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_template_assistant_create_structure',
            'post_id': postId,
            'content': content,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-templates-add-structure-start-btn[data-type="' + type + '"]').prop('disabled', true);
            jQuery('.ass-templates-add-structure-start-text[data-type="' + type + '"]').hide();
            jQuery('.ass-templates-add-structure-start-loader[data-type="' + type + '"]').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result == true && data.content != undefined) {
                jQuery('#ass-templates-' + type + '-reference').val(data.content);
                jQuery('.ass-modal-templates-add-sidebar[data-id="structure"]').removeClass('ass-modal-templates-add-sidebar-open');
                setTimeout(() => {
                    jQuery('.ass-modal-templates-add-sidebar').hide();
                }, 300);
            } else if (data.error != undefined && data.error == 'nonce') {
                showNonceNotice();
            } else {
                showToast({
                    message: (data.error_message != undefined ? data.error_message : ''),
                    type: 'danger'
                });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-templates-add-structure-start-loader[data-type="' + type + '"]').hide();
            jQuery('.ass-templates-add-structure-start-text[data-type="' + type + '"]').show();
            jQuery('.ass-templates-add-structure-start-btn[data-type="' + type + '"]').prop('disabled', false);
        }
    });
});
jQuery(document).on('click', '.ass-modal-templates-add-analyze-result-item-toggle', function () {
    let $element = jQuery(this);
    let $textElement = $element.closest('.d-flex.flex-column').find('span.ass-size-13');
    $textElement.slideToggle(150, function () {
        if ($textElement.is(':visible')) {
            $element.find('div').addClass('ass-transform-rotate-180');
        } else {
            $element.find('div').removeClass('ass-transform-rotate-180');
        }
    });
});
jQuery(document).on('change', '#ass-modal-templates-add-assistant-toggle', function () {
    let checked = jQuery(this).is(':checked');
    let type = jQuery(this).attr('data-type');
    if (checked) {
        jQuery('.ass-modal-templates-add-assistant-toggle-ctn').hide();
        jQuery('.ass-modal-templates-add-assistant-toggle-ctn[data-id="blog"]').show();
        jQuery('.ass-modal-templates-add-assistant-blog').hide();
        jQuery('.ass-modal-templates-add-assistant-custom').show();
        jQuery('#ass-templates-add-assistant-post').val('0');
        jQuery('.ass-modal-templates-add-assistant-toggle-label-off[data-type="' + type + '"]').hide();
        jQuery('.ass-modal-templates-add-assistant-toggle-label-on[data-type="' + type + '"]').show();
    } else {
        jQuery('.ass-modal-templates-add-assistant-toggle-ctn').hide();
        jQuery('.ass-modal-templates-add-assistant-toggle-ctn[data-id="custom"]').show();
        jQuery('.ass-modal-templates-add-assistant-custom').hide();
        jQuery('.ass-modal-templates-add-assistant-blog').show();
        jQuery('.ass-modal-templates-add-assistant-toggle-label-on[data-type="' + type + '"]').hide();
        jQuery('.ass-modal-templates-add-assistant-toggle-label-off[data-type="' + type + '"]').show();
    }
});
jQuery(document).on('change', '#ass-modal-templates-add-structure-toggle', function () {
    let checked = jQuery(this).is(':checked');
    let type = jQuery(this).attr('data-type');
    if (checked) {
        jQuery('.ass-modal-templates-add-structure-toggle-ctn').hide();
        jQuery('.ass-modal-templates-add-structure-toggle-ctn[data-id="blog"]').show();
        jQuery('.ass-modal-templates-add-structure-blog').hide();
        jQuery('.ass-modal-templates-add-structure-custom').show();
        jQuery('#ass-templates-add-structure-post').val('0');
        jQuery('.ass-modal-templates-add-structure-toggle-label-off[data-type="' + type + '"]').hide();
        jQuery('.ass-modal-templates-add-structure-toggle-label-on[data-type="' + type + '"]').show();
    } else {
        jQuery('.ass-modal-templates-add-structure-toggle-ctn').hide();
        jQuery('.ass-modal-templates-add-structure-toggle-ctn[data-id="custom"]').show();
        jQuery('.ass-modal-templates-add-structure-custom').hide();
        jQuery('.ass-modal-templates-add-structure-blog').show();
        jQuery('.ass-modal-templates-add-structure-toggle-label-on[data-type="' + type + '"]').hide();
        jQuery('.ass-modal-templates-add-structure-toggle-label-off[data-type="' + type + '"]').show();
    }
});

jQuery(document).on('click', '.ass-modal-templates-add-analyze-reload', function () {
    let type = jQuery(this).attr('data-type');
    jQuery('.ass-modal-templates-add-prompt-action[data-origin="' + type + '"][data-action="analyze"]').trigger('click');
});

function resetModalAddSidebar() {
    jQuery('.ass-modal-templates-add-sidebar').removeClass('ass-modal-templates-add-sidebar-open');
    jQuery('.ass-modal-templates-add-sidebar').hide();
    jQuery('#ass-templates-add-assistant-content').val('');
}

jQuery(document).on('click', '.ass-modal-templates-add-analyze-revised-action', function () {
    let type = jQuery(this).attr('data-type');
    let action = jQuery(this).attr('data-action');
    if (action == 'copy') {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            let prompt = jQuery('.ass-modal-templates-add-analyze-revised-full').html();
            if (prompt != undefined && prompt != null) {
                navigator.clipboard.writeText(prompt).then(function () {
                    showToast({
                        message: __('Copied to Clipboard', 'assistini'),
                        type: 'primary'
                    });
                });
            }
        }
    } else if (action == 'insert') {
        jQuery('#ass-templates-' + type + '-prompt').val(jQuery('.ass-modal-templates-add-analyze-revised-full').html());
        showToast({
            message: __('Copied to Prompt', 'assistini'),
            type: 'primary'
        });
    }
});

function sortArrayWithFixedFirst(arr) {
  if (!Array.isArray(arr) || arr.length === 0) return arr;
  const first = arr[0];
  const rest = arr.slice(1).sort((a, b) => b.rating + a.rating);
  return [first, ...rest];
}

jQuery(document).on('input propertychange', '#ass-modal-templates-assistant-posts-search', function () {
    let value = jQuery(this).val().toLowerCase();
    jQuery('.ass-modal-templates-assistant-posts-list > .ass-modal-templates-assistant-post-item').hide();
    let entrys = jQuery('.ass-modal-templates-assistant-posts-list > .ass-modal-templates-assistant-post-item');
    entrys.each(function (index, $entry) {
        let text = jQuery($entry).find('a').text().toLowerCase();
        if (text.includes(value)) {
            jQuery($entry).show();
        }
    });
});
jQuery('#ass-modal-templates-add-assistant-post-dropdown').on('hidden.bs.dropdown', function () {
    jQuery('#ass-modal-templates-assistant-posts-search').val('');
    jQuery('.ass-modal-templates-assistant-posts-list > .ass-modal-templates-assistant-post-item').show();
});
jQuery(document).on('click', '.ass-modal-templates-assistant-post-item', function () {
    let type = jQuery(this).closest('#ass-modal-templates-add-assistant-post-dropdown').attr('data-type');
    jQuery('#ass-modal-templates-add-assistant-post-dropdown[data-type="' + type + '"]').attr('data-selected-id', jQuery(this).find('a').attr('data-id'));
    jQuery('#ass-modal-templates-add-assistant-post-dropdown[data-type="' + type + '"]').find('.dropdown-toggle').find('span').text(jQuery(this).find('a').text());
});
jQuery(document).on('input propertychange', '#ass-modal-templates-structure-posts-search', function () {
    let value = jQuery(this).val().toLowerCase();
    jQuery('.ass-modal-templates-structure-posts-list > .ass-modal-templates-structure-post-item').hide();
    let entrys = jQuery('.ass-modal-templates-structure-posts-list > .ass-modal-templates-structure-post-item');
    entrys.each(function (index, $entry) {
        let text = jQuery($entry).find('a').text().toLowerCase();
        if (text.includes(value)) {
            jQuery($entry).show();
        }
    });
});
jQuery('#ass-modal-templates-add-structure-post-dropdown').on('hidden.bs.dropdown', function () {
    jQuery('#ass-modal-templates-structure-posts-search').val('');
    jQuery('.ass-modal-templates-structure-posts-list > .ass-modal-templates-structure-post-item').show();
});
jQuery(document).on('click', '.ass-modal-templates-structure-post-item', function () {
    let type = jQuery(this).closest('#ass-modal-templates-add-structure-post-dropdown').attr('data-type');
    jQuery('#ass-modal-templates-add-structure-post-dropdown[data-type="' + type + '"]').attr('data-selected-id', jQuery(this).find('a').attr('data-id'));
    jQuery('#ass-modal-templates-add-structure-post-dropdown[data-type="' + type + '"]').find('.dropdown-toggle').find('span').text(jQuery(this).find('a').text());
});

// !SECTION

// SECTION: Support
function openSupportModal( { sessionId = '', templateId = 0, language = '', tone = '', pointOfView = '', contentLength = '' } = {}) {
    const $modalElement = jQuery('#ass-modal-support');
    let name = '';
    if (assi_plugin_data?.blog_user_first_name != undefined && assi_plugin_data?.blog_user_first_name != '') {
        name += assi_plugin_data.blog_user_first_name;
    }
    if (assi_plugin_data?.blog_user_last_name != undefined && assi_plugin_data?.blog_user_last_name != '') {
        name += (name != '' ? ' ' : '') + assi_plugin_data.blog_user_last_name;
    }
    if (name == '' && assi_plugin_data?.blog_user_display_name != undefined && assi_plugin_data?.blog_user_display_name != '') {
        name = assi_plugin_data.blog_user_display_name;
    }
    let email = '';
    if (assi_plugin_data?.blog_user_email != undefined && assi_plugin_data?.blog_user_email != '') {
        email = assi_plugin_data.blog_user_email;
    }
    
    jQuery('#ass-modal-support-name').val(name);
    jQuery('#ass-modal-support-email').val(email);
    jQuery('#ass-modal-support-session-id').val(sessionId);
    jQuery('.ass-modal-support-save-btn').show();
    $modalElement.modal('show');
    $modalElement.on('click', function (event) {
        const $saveBtn = jQuery(event.target).closest('.ass-modal-support-save-btn');
        if ($saveBtn.length > 0) {
            let chatId = jQuery('#ass-modal-support-session-id').val();
            let name = jQuery('#ass-modal-support-name').val();
            let email = jQuery('#ass-modal-support-email').val();
            let message = jQuery('#ass-modal-support-message').val();
            if (name == undefined || name == '' || email == undefined || email == '' || message == undefined || message == '') {
                showToast({
                    message: __('Not all Fields filled!', 'assistini'),
                    type: 'danger'
                });
                return;
            }
            jQuery.ajax({
                url: ajaxurl,
                type: "POST",
                cache: false,
                data: {
                    'action': 'assi_submit_support_ticket',
                    'session_id': chatId,
                    'name': name,
                    'email': email,
                    'message': message,
                    'template_id': (templateId > 0 ? templateId : 0),
                    'language': language,
                    'tone': tone,
                    'point_of_view': pointOfView,
                    'content_length': contentLength,
                    'assi_security_nonce': jQuery('#assi_security_nonce').val()
                },
                beforeSend: function () {
                    jQuery('.ass-modal-support-save-btn').prop('disabled', true);
                    jQuery('.ass-modal-support-save-text').hide();
                    jQuery('.ass-modal-support-save-loader').show();
                },
                success: function (data) {
                    data = JSON.parse(data);
                    if (data.result != undefined && data.result == false && data.error != undefined) {
                        if (data.error == 'nonce') {
                            showNonceNotice();
                        } else {
                            showToast({
                                message: (data.error_message != undefined ? data.error_message : ''),
                                type: 'danger'
                            });
                        }
                    } else if (data.result != undefined && data.result == true) {
                        showToast({
                            message: __('Your support ticket has been successfully submitted.', 'assistini')
                        });
                        jQuery('.ass-modal-support-confirmation').show();
                        jQuery('#ass-modal-support-form').hide();
                        jQuery('.ass-modal-support-save-btn').hide();
                    } else {
                        showToast({ type: 'danger' });
                        jQuery('.ass-modal-support-save-btn').prop('disabled', false);
                        jQuery('.ass-modal-support-save-btn').show();
                    }
                },
                error: function () {
                    showToast({ type: 'danger' });
                    jQuery('.ass-modal-support-save-btn').prop('disabled', false);
                    jQuery('.ass-modal-support-save-btn').show();
                },
                complete: function () {
                    jQuery('.ass-modal-support-save-loader').hide();
                    jQuery('.ass-modal-support-save-text').show();
                }
            });
        }
    });
}
document.getElementById('ass-modal-support').addEventListener('hidden.bs.modal', function () {
    jQuery('#ass-modal-support').off();
    jQuery('.ass-modal-support-confirmation').hide();
    jQuery('#ass-modal-support-form').show();
    jQuery('.ass-modal-support-save-btn').prop('disabled', false);
    jQuery('.ass-modal-support-save-btn').show();
    jQuery('#ass-modal-support-name').val('');
    jQuery('#ass-modal-support-message').val('');
});

function openUpgradeModal(type = '') {
    if (type != 'credits' && type != 'chat' && type != 'template') {
        return false;
    }
    if (type == 'credits' && assi_plugin_data.user_account.plan.registered == false && assi_plugin_data.user_account.plan.bonus_available == true) {
        jQuery('#ass-modal-upgrade-bonus').modal('show');
        return;
    }
    let planId = jQuery('#ass-account-plan-id').val();
    jQuery('.ass-modal-upgrade-content').hide();
    jQuery('.ass-modal-upgrade-content[data-type="' + type + '"][data-plan="' + planId + '"]').show();
    jQuery('#ass-modal-upgrade').modal('show');
}
jQuery(document).on('click', '.ass-modal-upgrade-contact-btn', function () {
    jQuery('#ass-modal-upgrade').modal('hide');
    openSupportModal();
});
// !SECTION

// SECTION: Settings
jQuery(document).on('click', '.ass-settings-creator-save', function () {
    let language = jQuery('.ass-settings-creator-language').find(':selected').val();
    let tone = jQuery('.ass-settings-creator-tone').find(':selected').val();
    let pointOfView = jQuery('.ass-settings-creator-pov').find(':selected').val();
    let contentLength = jQuery('.ass-settings-creator-length').find(':selected').val();

    if (language == undefined || tone == undefined || pointOfView == undefined || contentLength == undefined) {
        return;
    }
    if (defaultSettings?.content_creator == undefined) {
        defaultSettings.content_creator = {};
    }
    defaultSettings.content_creator.language = language;
    defaultSettings.content_creator.tone = tone;
    defaultSettings.content_creator.point_of_view = pointOfView;
    defaultSettings.content_creator.content_length = contentLength;

    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_settings_save',
            'type': 'content_creator',
            'language': language,
            'tone': tone,
            'point_of_view': pointOfView,
            'content_length': contentLength,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-settings-creator-save').prop('disabled', true);
            jQuery('.ass-settings-creator-save-text').hide();
            jQuery('.ass-settings-creator-save-loader').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message != undefined ? data.error_message : '',
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true) {
                showToast({
                    message: __('Your settings have been saved.', 'assistini'),
                    type: 'success'
                });
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-settings-creator-save').prop('disabled', false);
            jQuery('.ass-settings-creator-save-text').show();
            jQuery('.ass-settings-creator-save-loader').hide();
        }
    });
});
jQuery(document).on('click', '.ass-settings-image-save', function () {
    let size = jQuery('.ass-settings-image-size').find(':selected').val();
    let quality = jQuery('.ass-settings-image-quality').find(':selected').val();
    let outputFormat = jQuery('.ass-settings-image-format').find(':selected').val();

    if (size == undefined || quality == undefined || outputFormat == undefined) {
        return;
    }
    if (defaultSettings?.image_generator == undefined) {
        defaultSettings.image_generator = {};
    }
    defaultSettings.image_generator.size = size;
    defaultSettings.image_generator.quality = quality;
    defaultSettings.image_generator.output_format = outputFormat;

    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_settings_save',
            'type': 'image_generator',
            'size': size,
            'quality': quality,
            'output_format': outputFormat,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-settings-image-save').prop('disabled', true);
            jQuery('.ass-settings-image-save-loader').show();
            jQuery('.ass-settings-image-save-text').hide();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message != undefined ? data.error_message : '',
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true) {
                showToast({
                    message: __('Your settings have been saved.', 'assistini'),
                    type: 'success'
                });
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-settings-image-save').prop('disabled', false);
            jQuery('.ass-settings-image-save-loader').hide();
            jQuery('.ass-settings-image-save-text').show();
        }
    });
});
function saveChatSettings(sessionId = '') {
    if (sessionId == undefined || sessionId == '') {
        return;
    }
    chatSettings[sessionId] = {
        language: jQuery('.ass-chat-control-language').find(':selected').val(),
        tone: jQuery('.ass-chat-control-tone').find(':selected').val(),
        pointOfView: jQuery('.ass-chat-control-pov').find(':selected').val(),
        contentLength: jQuery('.ass-chat-control-length').find(':selected').val()
    };
}
jQuery('#ass-settings-consent-checkbox').on('change', function () {
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_settings_consent_save',
            'consent': jQuery('#ass-settings-consent-checkbox').is(':checked'),
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message != undefined ? data.error_message : '',
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true) {
                showToast({
                    message: __('Your settings have been saved.', 'assistini'),
                    type: 'success'
                });
                window.location.reload();
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
});
jQuery(document).on('click', '.ass-settings-custom-ai-verify', function () {
    let key = jQuery('#ass-settings-custom-ai-key').val();

    if (key == undefined || key == '') {
        return;
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_settings_custom_ai_verify',
            'key': key,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-settings-custom-ai-verify-text').hide();
            jQuery('.ass-settings-custom-ai-verify-loader').show();
            jQuery('.ass-settings-custom-ai-verify').prop('disabled', true);
            jQuery('#ass-settings-custom-ai-key').prop('disabled', true);
            jQuery('.ass-settings-custom-ai-key-invalid').fadeOut(200);
            jQuery('.ass-settings-custom-ai-key-valid').fadeOut(200);
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message != undefined ? data.error_message : '',
                        type: 'danger'
                    });
                }
                jQuery('#ass-settings-custom-ai-key').prop('disabled', false);
                jQuery('.ass-settings-custom-ai-verify').prop('disabled', false);
            } else if (data.result != undefined && data.result == true && data.models != undefined) {
                let textModelOptions = '';
                let imageModelOptions = '';

                data.models.forEach((entry) => {
                    if (entry.type != undefined && entry.type == 'text' && entry.id != undefined) {
                        textModelOptions += '<option value="' + entry.id + '">' + entry.id + '</option>';
                    }
                    if (entry.type != undefined && entry.type == 'image') {
                        imageModelOptions += '<option value="' + entry.id + '">' + entry.id + '</option>';
                    }
                });
                jQuery('#ass-settings-custom-ai-text-form-model').html(textModelOptions);
                jQuery('#ass-settings-custom-ai-image-form-model').html(imageModelOptions);

                if (data.default_options != undefined && data.default_options.text != undefined && data.default_options.text.openai != undefined) {
                    if (data.default_options.text.openai.top_p != undefined) {
                        jQuery('#ass-settings-custom-ai-text-form-topp').val(data.default_options.text.openai.top_p);
                        jQuery('.ass-settings-custom-ai-controls-badge[data-id="topp"]').html(data.default_options.text.openai.top_p);
                    }
                    if (data.default_options.text.openai.temperature != undefined) {
                        jQuery('#ass-settings-custom-ai-text-form-temp').val(data.default_options.text.openai.temperature);
                        jQuery('.ass-settings-custom-ai-controls-badge[data-id="temp"]').html(data.default_options.text.openai.temperature);
                    }
                    if (data.default_options.text.openai.presence_penalty != undefined) {
                        jQuery('#ass-settings-custom-ai-text-form-pres').val(data.default_options.text.openai.presence_penalty);
                        jQuery('.ass-settings-custom-ai-controls-badge[data-id="pres"]').html(data.default_options.text.openai.presence_penalty);
                    }
                    if (data.default_options.text.openai.frequency_penalty != undefined) {
                        jQuery('#ass-settings-custom-ai-text-form-freq').val(data.default_options.text.openai.frequency_penalty);
                        jQuery('.ass-settings-custom-ai-controls-badge[data-id="freq"]').html(data.default_options.text.openai.frequency_penalty);
                    }
                }
                jQuery('.ass-settings-custom-ai-key-valid').fadeIn();
                jQuery('.ass-settings-custom-ai-form-controls').slideDown(150);
            } else {
                jQuery('#ass-settings-custom-ai-key').prop('disabled', false).addClass('ass-red-border');
                setTimeout(() => {
                    jQuery('#ass-settings-custom-ai-key').removeClass('ass-red-border');
                }, 2500);
                jQuery('.ass-settings-custom-ai-key-invalid').fadeIn(200);
                jQuery('.ass-settings-custom-ai-verify').prop('disabled', false);
            }
        },
        error: function () {
            showToast({ type: 'danger' });
            jQuery('#ass-settings-custom-ai-key').prop('disabled', false);
            jQuery('.ass-settings-custom-ai-verify').prop('disabled', false);
        },
        complete: function () {
            jQuery('.ass-settings-custom-ai-verify-loader').hide();
            jQuery('.ass-settings-custom-ai-verify-text').show();
        }
    });
});
jQuery('#ass-settings-custom-ai-toggle-off').on('click', function () {
    if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            data: {
                'action': 'assi_settings_custom_ai_change_status',
                'connection_id': assi_plugin_data.custom_ai_connection.id,
                'active': 0,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            }
        });
        assi_plugin_data.custom_ai_connection.active = 0;
        jQuery('.ass-sidebar-licence-credits-ctn');
    }

    let $form = jQuery('.ass-settings-custom-ai-form');
    $form.animate({height: '0px'}, {duration: 150, easing: 'swing'});
});
jQuery('#ass-settings-custom-ai-toggle-on').on('click', function () {
    if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            data: {
                'action': 'assi_settings_custom_ai_change_status',
                'connection_id': assi_plugin_data.custom_ai_connection.id,
                'active': 1,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            }
        });
        assi_plugin_data.custom_ai_connection.active = 1;
        jQuery('.ass-sidebar-licence-credits-ctn').show();
    }

    let $form = jQuery('.ass-settings-custom-ai-form');
    let startingHeight = $form.outerHeight();
    jQuery('.ass-settings-custom-ai-form-model').hide();
    $form.css('height', 'auto');
    let height = $form.outerHeight();
    jQuery('.ass-settings-custom-ai-form-model').show();
    $form.css('height', startingHeight);
    $form.animate({height: height}, {duration: 150, easing: 'swing'});

    if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
        let name = (assi_plugin_data.custom_ai_connection.name != undefined ? assi_plugin_data.custom_ai_connection.name : '');
        let key = (assi_plugin_data.custom_ai_connection.key != undefined ? assi_plugin_data.custom_ai_connection.key : '');

        jQuery('#ass-settings-custom-ai-name').val(name).prop('disabled', true);
        jQuery('#ass-settings-custom-ai-key').val(key).prop('disabled', true);
        jQuery('.ass-settings-custom-ai-verify').hide();
        jQuery('.ass-settings-custom-ai-edit').show();
        jQuery('.ass-settings-custom-ai-remove').show();
    } else {
        jQuery('#ass-settings-custom-ai-name').prop('disabled', false);
        jQuery('#ass-settings-custom-ai-key').prop('disabled', false);
        jQuery('.ass-settings-custom-ai-verify').prop('disabled', false).show();
        jQuery('.ass-settings-custom-ai-edit').hide();
        jQuery('.ass-settings-custom-ai-remove').hide();
    }
});
jQuery('.ass-settings-custom-ai-form-dismiss-btn').on('click', function () {
    let $form = jQuery('.ass-settings-custom-ai-form');
    let startingHeight = $form.outerHeight();
    jQuery('.ass-settings-custom-ai-form-model').hide();
    $form.css('height', 'auto');
    let height = $form.outerHeight();
    jQuery('.ass-settings-custom-ai-form-model').show();
    $form.css('height', startingHeight + 'px');
    $form.animate({height: height + 'px'}, {duration: 150, easing: 'swing'});
    if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
        jQuery('#ass-settings-custom-ai-name').prop('disabled', true);
    } else {
        jQuery('#ass-settings-custom-ai-key').prop('disabled', false);
        jQuery('.ass-settings-custom-ai-verify').prop('disabled', false);
    }
});

jQuery('.ass-settings-custom-ai-form-save-btn').on('click', function () {
    let name = jQuery('#ass-settings-custom-ai-name').val();
    let key = jQuery('#ass-settings-custom-ai-key').val();
    let textModel = jQuery('#ass-settings-custom-ai-text-form-model').val();
    let textTopP = jQuery('#ass-settings-custom-ai-text-form-topp').val();
    let textTemperature = jQuery('#ass-settings-custom-ai-text-form-temp').val();
    let textPresencePenalty = jQuery('#ass-settings-custom-ai-text-form-pres').val();
    let textFrequencyPenalty = jQuery('#ass-settings-custom-ai-text-form-freq').val();
    let imageModel = jQuery('#ass-settings-custom-ai-image-form-model').val();

    let data = {
        'action': 'assi_settings_custom_ai_save',
        'name': name,
        'text_model': textModel,
        'text_top_p': textTopP,
        'text_temperature': textTemperature,
        'text_presence_penalty': textPresencePenalty,
        'text_frequency_penalty': textFrequencyPenalty,
        'image_model': imageModel,
        'assi_security_nonce': jQuery('#assi_security_nonce').val()
    };
    if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
        data['mode'] = 1;
        data['connection_id'] = assi_plugin_data.custom_ai_connection.id;
    } else {
        data['key'] = key;
    }

    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: data,
        beforeSend: function () {
            jQuery('.ass-settings-custom-ai-form-save-btn').prop('disabled', true);
            jQuery('.ass-settings-custom-ai-form-save-text').hide();
            jQuery('.ass-settings-custom-ai-form-save-loader').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: (data.error_message != undefined ? data.error_message : ''),
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true && data.id != undefined && data.id > 0) {
                jQuery('.ass-settings-custom-ai-form-controls').slideUp(150, function () {
                    jQuery('#ass-settings-custom-ai-toggle').trigger('change');
                });
                assi_plugin_data.custom_ai_connection = {
                    id: data.id,
                    name: data.name,
                    key: data.key,
                    engine_options: data.engine_options,
                    active: 1
                };
                showToast({
                    message: __('Settings saved successfully.', 'assistini'),
                    type: 'success'
                });
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-settings-custom-ai-form-save-loader').hide();
            jQuery('.ass-settings-custom-ai-form-save-text').show();
            jQuery('.ass-settings-custom-ai-form-save-btn').prop('disabled', false);
        }
    });
});

jQuery(document).on('click', '.ass-settings-custom-ai-edit', function () {
    if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data?.custom_ai_connection?.engine_options != undefined) {
        let connectionId = assi_plugin_data.custom_ai_connection.id;
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            data: {
                'action': 'assi_settings_custom_ai_verify',
                'mode': 1,
                'connection_id': connectionId,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            },
            beforeSend: function () {
                jQuery('.ass-settings-custom-ai-edit').prop('disabled', true);
                jQuery('.ass-settings-custom-ai-edit-text').hide();
                jQuery('.ass-settings-custom-ai-edit-loader').show();
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.result != undefined && data.result == false && data.error != undefined) {
                    if (data.error == 'nonce') {
                        showNonceNotice();
                    } else {
                        showToast({
                            message: data.error_message != undefined ? data.error_message : '',
                            type: 'danger'
                        });
                    }
                } else if (data.result != undefined && data.result == true && data.models != undefined) {
                    let textModelOptions = '';
                    let imageModelOptions = '';

                    data.models.forEach((entry) => {
                        if (entry.type != undefined && entry.type == 'text' && entry.id != undefined) {
                            if (assi_plugin_data?.custom_ai_connection?.engine_options?.text?.model != undefined && assi_plugin_data.custom_ai_connection.engine_options.text.model == entry.id) {
                                textModelOptions += '<option value="' + entry.id + '" selected>' + entry.id + '</option>';
                            } else {
                                textModelOptions += '<option value="' + entry.id + '">' + entry.id + '</option>';
                            }
                        }
                        if (entry.type != undefined && entry.type == 'image') {
                            if (assi_plugin_data?.custom_ai_connection?.engine_options?.image?.model != undefined && assi_plugin_data.custom_ai_connection.engine_options.image.model == entry.id) {
                                imageModelOptions += '<option value="' + entry.id + '" selected>' + entry.id + '</option>';
                            } else {
                                imageModelOptions += '<option value="' + entry.id + '">' + entry.id + '</option>';
                            }
                        }
                    });
                    jQuery('#ass-settings-custom-ai-text-form-model').html(textModelOptions);
                    jQuery('#ass-settings-custom-ai-image-form-model').html(imageModelOptions);

                    if (assi_plugin_data?.custom_ai_connection?.engine_options != undefined) {
                        if (assi_plugin_data.custom_ai_connection.engine_options.text.top_p != undefined) {
                            jQuery('#ass-settings-custom-ai-text-form-topp').val(assi_plugin_data.custom_ai_connection.engine_options.text.top_p);
                            jQuery('.ass-settings-custom-ai-controls-badge[data-id="topp"]').html(assi_plugin_data.custom_ai_connection.engine_options.text.top_p);
                        }
                        if (assi_plugin_data.custom_ai_connection.engine_options.text.temperature != undefined) {
                            jQuery('#ass-settings-custom-ai-text-form-temp').val(assi_plugin_data.custom_ai_connection.engine_options.text.temperature);
                            jQuery('.ass-settings-custom-ai-controls-badge[data-id="temp"]').html(assi_plugin_data.custom_ai_connection.engine_options.text.temperature);
                        }
                        if (assi_plugin_data.custom_ai_connection.engine_options.text.presence_penalty != undefined) {
                            jQuery('#ass-settings-custom-ai-text-form-pres').val(assi_plugin_data.custom_ai_connection.engine_options.text.presence_penalty);
                            jQuery('.ass-settings-custom-ai-controls-badge[data-id="pres"]').html(assi_plugin_data.custom_ai_connection.engine_options.text.presence_penalty);
                        }
                        if (assi_plugin_data.custom_ai_connection.engine_options.text.frequency_penalty != undefined) {
                            jQuery('#ass-settings-custom-ai-text-form-freq').val(assi_plugin_data.custom_ai_connection.engine_options.text.frequency_penalty);
                            jQuery('.ass-settings-custom-ai-controls-badge[data-id="freq"]').html(assi_plugin_data.custom_ai_connection.engine_options.text.frequency_penalty);
                        }
                    }
                    jQuery('.ass-settings-custom-ai-form-controls').slideDown(150);
                    jQuery('#ass-settings-custom-ai-name').prop('disabled', false);
                } else {
                    showToast({ type: 'danger' });
                }
            },
            error: function () {
                showToast({ type: 'danger' });
            },
            complete: function () {
                jQuery('.ass-settings-custom-ai-edit-loader').hide();
                jQuery('.ass-settings-custom-ai-edit-text').show();
                jQuery('.ass-settings-custom-ai-edit').prop('disabled', false);
            }
        });
    }
});

jQuery(document).on('click', '.ass-settings-custom-ai-remove', function () {
    if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            cache: false,
            data: {
                'action': 'assi_settings_custom_ai_remove',
                'connection_id': assi_plugin_data.custom_ai_connection.id,
                'assi_security_nonce': jQuery('#assi_security_nonce').val()
            },
            beforeSend: function () {
                jQuery('.ass-settings-custom-ai-remove').prop('disabled', true);
                jQuery('.ass-settings-custom-ai-remove-text').hide();
                jQuery('.ass-settings-custom-ai-remove-loader').show();
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.result != undefined && data.result == false && data.error != undefined) {
                    if (data.error == 'nonce') {
                        showNonceNotice();
                    } else {
                        showToast({
                            message: data.error_message != undefined ? data.error_message : '',
                            type: 'danger'
                        });
                    }
                } else if (data.result != undefined && data.result == true) {
                    assi_plugin_data.custom_ai_connection = '';
                    jQuery('#ass-settings-custom-ai-name').val('');
                    jQuery('#ass-settings-custom-ai-key').val('');
                    jQuery('#ass-settings-custom-ai-text-form-model').html('');
                    jQuery('#ass-settings-custom-ai-image-form-model').html('');
                    jQuery('#ass-settings-custom-ai-text-form-topp').val(0);
                    jQuery('#ass-settings-custom-ai-text-form-temp').val(0);
                    jQuery('#ass-settings-custom-ai-text-form-pres').val(0);
                    jQuery('#ass-settings-custom-ai-text-form-freq').val(0);
                    jQuery('#ass-settings-custom-ai-toggle').trigger('change');
                } else {
                    showToast({ type: 'danger' });
                }
            },
            error: function () {
                showToast({ type: 'danger' });
            },
            complete: function () {
                jQuery('.ass-settings-custom-ai-remove-loader').hide();
                jQuery('.ass-settings-custom-ai-remove-text').show();
                jQuery('.ass-settings-custom-ai-remove').prop('disabled', false);
            }
        });
    }
});
jQuery('#ass-settings-custom-ai-toggle').on('change', function () {
    jQuery('.ass-settings-custom-ai-key-valid').hide();
    jQuery('.ass-settings-custom-ai-key-invalid').hide();
    if (jQuery(this).is(':checked')) {
        jQuery('.ass-settings-custom-ai-toggle-label-off').hide();
        jQuery('.ass-settings-custom-ai-toggle-label-on').show();
        jQuery('.ass-settings-custom-ai-form').slideDown(150);
        jQuery('.ass-settings-custom-ai-form-controls').hide();

        if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
            if (assi_plugin_data.custom_ai_connection.name != undefined) {
                jQuery('#ass-settings-custom-ai-name').val(assi_plugin_data.custom_ai_connection.name);
            }
            if (assi_plugin_data.custom_ai_connection.key != undefined) {
                jQuery('#ass-settings-custom-ai-key').val(assi_plugin_data.custom_ai_connection.key);
            }
            jQuery('#ass-settings-custom-ai-name').prop('disabled', true);
            jQuery('#ass-settings-custom-ai-key').prop('disabled', true);
            jQuery('.ass-settings-custom-ai-verify').remove();
            if (jQuery('.ass-settings-custom-ai-edit').length < 1) {
                jQuery('.ass-settings-custom-ai-key-input-group').append(`
                    <button type="button" class="btn btn-sm btn-primary ass-settings-custom-ai-edit">
                        <span class="ass-settings-custom-ai-edit-text">` + __('Settings', 'assistini') + `</span>
                        <span class="ass-settings-custom-ai-edit-loader spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display:none;"></span>
                    </button>
                `);
            }
            if (jQuery('.ass-settings-custom-ai-remove').length < 1) {
                jQuery('.ass-settings-custom-ai-key-input-group').append(`
                    <button type="button" class="btn btn-sm btn-secondary ass-settings-custom-ai-remove">
                        <span class="ass-settings-custom-ai-remove-text">` + __('Remove', 'assistini') + `</span>
                        <span class="ass-settings-custom-ai-remove-loader spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display:none;"></span>
                    </button>    
                `);
            }
            jQuery.ajax({
                url: ajaxurl,
                type: "POST",
                cache: false,
                data: {
                    'action': 'assi_settings_custom_ai_change_status',
                    'connection_id': assi_plugin_data.custom_ai_connection.id,
                    'active': 1,
                    'assi_security_nonce': jQuery('#assi_security_nonce').val()
                }
            });
            assi_plugin_data.custom_ai_connection.active = 1;
            jQuery('.ass-sidebar-licence-credits-ctn').slideUp(150);
        } else {
            jQuery('#ass-settings-custom-ai-name').prop('disabled', false);
            jQuery('#ass-settings-custom-ai-key').prop('disabled', false);
            jQuery('.ass-settings-custom-ai-edit').remove();
            jQuery('.ass-settings-custom-ai-remove').remove();
            if (jQuery('.ass-settings-custom-ai-verify').length < 1) {
                jQuery('.ass-settings-custom-ai-key-input-group').append(`
                    <button class="btn btn-sm btn-primary ass-settings-custom-ai-verify" type="button">
                        <span class="ass-settings-custom-ai-verify-text">` + __('Verify', 'assistini') + `</span>
                        <span class="ass-settings-custom-ai-verify-loader spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display:none;"></span>
                    </button>
                `);
            }
            jQuery('.ass-settings-custom-ai-verify').prop('disabled', false);
        }
    } else {
        jQuery('.ass-settings-custom-ai-form').slideUp(150);
        jQuery('.ass-settings-custom-ai-toggle-label-on').hide();
        jQuery('.ass-settings-custom-ai-toggle-label-off').show();

        if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
            jQuery.ajax({
                url: ajaxurl,
                type: "POST",
                cache: false,
                data: {
                    'action': 'assi_settings_custom_ai_change_status',
                    'connection_id': assi_plugin_data.custom_ai_connection.id,
                    'active': 0,
                    'assi_security_nonce': jQuery('#assi_security_nonce').val()
                }
            });
            assi_plugin_data.custom_ai_connection.active = 0;
            jQuery('.ass-sidebar-licence-credits-ctn').slideDown(150);
        }
    }
});
jQuery('.ass-settings-custom-ai-text-form-range').on('input propertychange', function () {
    let $elm = jQuery(this);
    let id = $elm.attr('data-id');
    let value = $elm.val();
    jQuery('.ass-settings-custom-ai-controls-badge[data-id="' + id + '"]').html(value);
});
jQuery('.ass-settings-custom-ai-form-reset-btn').on('click', function () {
    jQuery('.ass-settings-custom-ai-form-controls').slideUp(150);
    jQuery('.ass-settings-custom-ai-key-valid').fadeOut(200);
    jQuery('.ass-settings-custom-ai-key-invalid').fadeOut(200);
    if (assi_plugin_data?.custom_ai_connection?.id != undefined && assi_plugin_data.custom_ai_connection.id > 0) {
        jQuery('#ass-settings-custom-ai-name').prop('disabled', true);
    } else {
        jQuery('#ass-settings-custom-ai-key').prop('disabled', false);
        jQuery('.ass-settings-custom-ai-verify').prop('disabled', false);
    }
});
jQuery('.ass-settings-custom-ai-control-info').on('click', function () {
    let id = jQuery(this).attr('data-id');
    jQuery('.ass-modal-settings-custom-ai-info-content').hide();
    jQuery('.ass-modal-settings-custom-ai-info-content[data-id="' + id + '"]').show();
    jQuery('#ass-modal-settings-custom-ai-info').modal('show');
});
// !SECTION

// SECTION: Toasts
function showToast( { message = '', type = 'success', delay = 5000 }) {
    if (message == undefined || message == '') {
        message = __('Something went wrong with the AI server request - please retry.', 'assistini');
    }
    const toastTemplate = `
        <div class="toast align-items-center border-0 bg-${type} text-white" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="${delay}">
            <div class="toast-body d-flex">
                <span class="me-auto">${message}</span>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>`;

    const $toast = jQuery(toastTemplate).appendTo('#ass-toast-container');

    const toastInstance = new bootstrap.Toast($toast[0]);
    toastInstance.show();

    $toast.on('hidden.bs.toast', function () {
        jQuery(this).remove();
    });
}
// !SECTION

// SECTION: Notifications
function handleNotifications(notifications) {
    notifications.forEach((notification) => {
        if (typeof window[notification.type + 'Notification'] === 'function') {
            proxyLiveData.notifications++;
            window[notification.type + 'Notification'](notification);
        }
    });
}

function paymentNotification(notification) {
    proxyLiveData.chatsLeft = notification.notification_data.ass_plan_max_count_chats;
    proxyLiveData.templatesLeft = notification.notification_data.ass_plan_max_count_template;
    proxyLiveData.creditsOpen = notification.notification_data.ass_words_open;
    proxyLiveData.creditsTotal = notification.notification_data.ass_words_total;

    let planId = notification.notification_data.ass_plan_id;
    changeText('.ass-sidebar-licence-name', (planId == 2 ? __('Smart') : __('Free')));
    showToast({
        message: __('Your version has changed!', 'assistini'),
    });
    if (jQuery('.ass-notification-item[data-id="' + notification.notification_id + '"]').length > 0) {
        jQuery('.ass-notification-item[data-id="' + notification.notification_id + '"]').remove();
    }
    let $notificationList = jQuery('.ass-notification-area');
    let text = __('Your plan has upgraded', 'assistini');
    let item = jQuery(`
        <div class="ass-notification-item ass-notification-item-new" data-id="${notification.notification_id}">
            <img class="ass-notification-avatar ass-notification-item-clickable mx-4" src="${assi_plugin_data.plugin_path + '/assets/images/ass_notification_icon.png'}" />
            <div class="ass-notification-content ass-notification-item-clickable py-4">
                ${text}
                <div class="d-flex flex-column">
                    <small class="text-muted">${notification.create_date}</small>
                </div>
            </div>
            <i class="ass-notification-delete bi bi-trash ass-size-18 me-4"></i>
        </div>
    `);
    $notificationList.prepend(item);
}
function chatNotification(notification) {
    let localSessionId = '';
    showToast({
        message: __('Your generated content is now ready!', 'assistini'),
    });
    if (notification.notification_data.ass_words_open != undefined && notification.notification_data.ass_words_open >= 0) {
        proxyLiveData.creditsOpen = notification.notification_data.ass_words_open;
    }
    let sessionId = notification.notification_data.session_id;
    if (notification?.notification_data?.local_session_id != undefined && notification.notification_data.local_session_id != '') {
        localSessionId = notification.notification_data.local_session_id;
    }

    if (localSessionId != '') {
        let $sidebarItem = jQuery('.ass-chat-list-item[data-session-id="' + localSessionId + '"]');
        proxyLiveData.currentSessionId = sessionId;
        let chatName = notification?.notification_data?.title;
        changeText('.ass-chat-header-name', chatName);
        let $siebarListItem = jQuery('.ass-chat-list-item[data-session-id="' + localSessionId + '"]');
        $siebarListItem.attr('data-chat-name', chatName);
        $sidebarItem.attr('data-session-id', sessionId);
        $sidebarItem.attr('data-mode', MODE_EASY_CHAT);
        changeText($siebarListItem.find('.ass-chat-list-item-name'), chatName);
        $siebarListItem.attr('data-bs-title', chatName);
        initializeToolTips();
        let $chatItem = jQuery('.ass-chat-msg-container-item[data-session-id="' + localSessionId + '"]');
        $chatItem.attr('data-session-id', sessionId);
        proxyLiveData.showChatControls = true;
        loadChatHistory(sessionId, 'Chat', MODE_EASY_CHAT, true);
    } else {
        jQuery('#ass-current-session-id').val();
        jQuery('.ass-chat-list-item[data-session-id="' + notification.notification_data.session_id + '"] .ass-chat-sidebar-clickable').first().trigger('click');
        if (jQuery('.ass-notification-item[data-id="' + notification.notification_id + '"]').length > 0) {
            jQuery('.ass-notification-item[data-id="' + notification.notification_id + '"]').remove();
        }
        let $sidebarElm = jQuery('.ass-chat-list-item[data-session-id="' + notification.notification_data.session_id + '"]');
        if ($sidebarElm.length > 0) {
            let chatName = $sidebarElm.attr('data-chat-name');
            let chatMode = parseInt($sidebarElm.attr('data-mode'));
            proxyLiveData.showChatControls = (chatMode == MODE_EXPERT_CHAT ? false : true);
            loadChatHistory(notification.notification_data.session_id, chatName, chatMode, true);
        }
    }

    let $notificationList = jQuery('.ass-notification-area');
    let text = __('Your generated content is ready!', 'assistini');
    let item = jQuery(`
        <div class="ass-notification-item ass-notification-item-new" data-type="${notification.type}" data-session-id="${notification.notification_data.session_id}" data-id="${notification.notification_id}">
            <img class="ass-notification-avatar ass-notification-item-clickable mx-4" src="${assi_plugin_data.plugin_path + '/assets/images/ass_notification_icon.png'}" />
            <div class="ass-notification-content ass-notification-item-clickable py-4">
                ${text}
                <div class="d-flex flex-column">
                    <small class="text-muted">${notification.create_date}</small>
                </div>
            </div>
            <i class="ass-notification-item-delete bi bi-trash ass-size-18 me-4"></i>
        </div>
    `);
    $notificationList.prepend(item);
}
jQuery(document).on('click', '.ass-notification-item-clickable', function () {
    if (jQuery(this).parent().hasClass('ass-notification-item-new')) {
        jQuery(this).parent().removeClass('ass-notification-item-new');
        proxyLiveData.notifications--;
    }
    let type = jQuery(this).parent().attr('data-type');
    if (type != undefined && type == 'chat') {
        let sessionId = jQuery(this).parent().attr('data-session-id');
        window.location.href = '#/chat?chat_id=' + sessionId;
    }
});
jQuery(document).on('click', '.ass-notification-item-delete', function () {
    if (jQuery(this).parent().hasClass('ass-notification-item-new')) {
        jQuery(this).parent().removeClass('ass-notification-item-new');
    }
    let notificationId = jQuery(this).parent().attr('data-id');
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_notification_delete',
            'notification_id': notificationId,
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            showToast({
                message: __('Deleting notification...', 'assistini'),
                type: 'primary'
            });
            jQuery('.ass-notification-item-delete').prop('disabled', true);
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == false && data.error != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message != undefined ? data.error_message : '',
                        type: 'danger'
                    });
                }
            } else if (data.result != undefined && data.result == true) {
                showToast({
                    message: __('Notification deleted.', 'assistini'),
                    type: 'success'
                });
                if (notificationId == 'all') {
                    jQuery('.ass-notification-item').animate({height: '0px'}, {duration: 150, easing: 'swing', complete: function () {
                        jQuery('.ass-notification-item').remove();
                    }});
                    proxyLiveData.notifications = 0;
                } else {
                    jQuery('.ass-notification-item[data-id="' + notificationId + '"]').animate({height: '0px'}, {duration: 150, easing: 'swing', complete: function () {
                        jQuery('.ass-notification-item[data-id="' + notificationId + '"]').remove();
                    }});
                    proxyLiveData.notifications--;
                }
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        },
        complete: function () {
            jQuery('.ass-notification-item-delete').prop('disabled', false);
        }
    });
});
// !SECTION

// SECTION: Account
jQuery(document).on('click', '.ass-account-connect-btn', function (e) {
    e.preventDefault();
    let check = checkConnection(jQuery('#ass-account-email').val());
    if (!check) {
        return;
    }
    let email = jQuery('#ass-account-email').val();
    let url = 'https://apiwp.assistini.com/auth/';
    url = url + '?blog_user_token=' + jQuery('#ass-plugin-token').val();
    url = url + '&access_token=' + assi_plugin_data.blog_access_token;
    let location = window.location.protocol + '//' + window.location.hostname;
    let language = 'en';
    if (assi_plugin_data?.blog_language != undefined && assi_plugin_data.blog_language == 'de_DE') {
        language = 'de';
    }
    url = encodeURI(url + '&location=' + location);
    url = encodeURI(url + '&lang=' + language);
    if (email != undefined && email != '') {
        url = url + '&email=' + email;
    }
    window.open(url, 'Assistini OAuth', "width=650,height=800,scrollbars=yes,toolbar=no,status=no,resizable=no,menubar=no,location=no,directories=no,top=20,left=20");
});
jQuery(document).on('click', '.ass-account-change-btn', function (e) {
    e.preventDefault();
    let url = 'https://apiwp.assistini.com/auth/';
    url = url + '?blog_user_token=' + jQuery('#ass-plugin-token').val();
    url = url + '&access_token=' + assi_plugin_data.blog_access_token;
    let location = window.location.protocol + '//' + window.location.hostname;
    url = encodeURI(url + '&location=' + location);
    url = encodeURI(url + '&lang=en');
    window.open(url, 'Assistini OAuth', "width=650,height=800,scrollbars=yes,toolbar=no,status=no,resizable=no,menubar=no,location=no,directories=no,top=20,left=20");
});
function configureAccountPage() {
    if (assi_plugin_data?.user_account?.plan?.registered != undefined && assi_plugin_data.user_account.plan.registered == true) {
        jQuery('.ass-account-case-one').hide();
        jQuery('.ass-account-case-two').hide();
        jQuery('.ass-account-email-input').hide();
        jQuery('.ass-account-case-three').show();
        if (assi_plugin_data?.user_account?.plan?.display_name != undefined && assi_plugin_data.user_account.plan.display_name != '') {
            jQuery('.ass-account-display-name').text(assi_plugin_data.user_account.plan.display_name);
        } else {
            jQuery('.ass-account-display-name').text(__('Unknown', 'assistini'));
        }
    } else {
        jQuery('.ass-account-email-input').show();
        jQuery('.ass-account-case-three').hide();
        if (assi_plugin_data?.user_account?.plan?.bonus_available != undefined && assi_plugin_data.user_account.plan.bonus_available == true) {
            jQuery('.ass-account-case-one').show();
            jQuery('.ass-account-case-two').hide();
        } else {
            jQuery('.ass-account-case-one').hide();
            jQuery('.ass-account-case-two').show();
        }
    }
}
jQuery(document).on('click', '.ass-account-remove-btn', function (e) {
    e.preventDefault();
    let check = checkConnection('', true);
    if (!check) {
        return;
    }
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_auth_remove',
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == true) {
                window.location.href = `#/account`;
                window.location.reload();
            } else if (data.error != undefined && data.error_message != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message,
                        type: 'danger'
                    });
                }
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
});

function checkConnection(email = '', remove = false) {
    if (assi_plugin_data?.allow_server_connection != undefined && assi_plugin_data.allow_server_connection == false) {
        if (assi_plugin_data?.manage_options != undefined && assi_plugin_data.manage_options == true) {
            if (email != '') {
                jQuery('#ass-modal-connection-consent-email').val(email);
            } else {
                jQuery('#ass-modal-connection-consent-email').val('');
            }
            if (remove == true) {
                jQuery('#ass-modal-connection-consent-remove').val('1');
            } else {
                jQuery('#ass-modal-connection-consent-remove').val('0');
            }
            jQuery('#ass-modal-connection-consent').modal('show');
        } else {
            jQuery('#ass-modal-connection-consent-no-admin').modal('show');
        }
        return false;
    }
    return true;
}

function checkOpenAiStatus() {
    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        cache: false,
        data: {
            'action': 'assi_open_ai_status',
            'assi_security_nonce': jQuery('#assi_security_nonce').val()
        },
        beforeSend: function () {
            jQuery('.ass-sidebar-status-content-inner').hide();
            jQuery('.ass-sidebar-status-content-inner[data-status="-1"]').show();
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.result == true && data.status != undefined && data.status > 0) {
                proxyLiveData.aiStatus = data.status;
                jQuery('.ass-sidebar-status-content-inner').hide();
                jQuery('.ass-sidebar-status-content-inner[data-status="' + data.status + '"]').show();
                if (data.status > 1) {
                    jQuery('.ass-chat-header-open-ai-status-item').hide();
                    jQuery('.ass-chat-header-open-ai-status-item[data-status="' + data.status + '"]').show();
                    jQuery('.ass-chat-header-open-ai-status').show();
                }
            } else {
                jQuery('.ass-sidebar-status-content-inner').hide();
                jQuery('.ass-sidebar-status-content-inner[data-status="0"]').show();
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
}
// !SECTION

function startProgressCircle(circleElement, circleElementText, seconds = 45) {
    jQuery(circleElement).circleProgress({
        value: 0,
        size: 80,
        startAngle: -Math.PI / 2,
        lineCap: 'round',
        fill: {
            gradient: ['#1b1464']
        }
    });
    jQuery(circleElementText).html('0%');
    let progressArray = getRandomProgressArray(seconds);
    let counter = 0;
    let percent = 0;
    progressInterval = setInterval(() => {
        if (progressArray[counter] != undefined) {
            percent += progressArray[counter] / 100;
            if (percent >= 1) percent = 1;
            jQuery(circleElement).circleProgress('value', percent);
            jQuery(circleElementText).html(Math.round(percent * 100) + '%');
            if (percent == 1) stopProgressCircle();
            counter++;
        } else {
            stopProgressCircle();
        }
    }, 1000);
}

function stopProgressCircle() {
    clearInterval(progressInterval);
    progressInterval = null;
}

function finishProgressCircle(circleElement, circleElementText) {
    if (progressInterval != null) {
        stopProgressCircle();
    }
    jQuery(circleElement).circleProgress('value', 1);
    jQuery(circleElementText).html('100%');
}

function getRandomProgressArray(seconds = 45, maxPercent = 99) {
    let arr = [];
    for (let i = 0; i < (seconds - 1); i++) {
        arr.push(Math.random());
    }
    let sum = arr.reduce((a, b) => a + b, 0);
    arr = arr.map(x => x / sum * maxPercent);
    arr = arr.map(x => Math.round(x));
    let diff = maxPercent - arr.reduce((a, b) => a + b, 0);
    while (diff !== 0) {
        let index = Math.floor(Math.random() * 44);
        if (diff > 0) {
            arr[index]++;
            diff--;
        } else if (diff < 0 && arr[index] > 0) {
            arr[index]--;
            diff++;
        }
    }
    return arr;
}

jQuery(document).on('click', '.ass-modal-templates-add-analyze-revised-toggle', function () {
    if (jQuery('.ass-modal-templates-add-analyze-revised-full').is(':visible')) {
        jQuery('.ass-modal-templates-add-analyze-revised-full').hide();
        jQuery('.ass-modal-templates-add-analyze-revised-truncated').show();
        jQuery(this).first().removeClass('ass-transform-rotate-180');
    } else {
        jQuery('.ass-modal-templates-add-analyze-revised-truncated').hide();
        jQuery('.ass-modal-templates-add-analyze-revised-full').show();
        jQuery(this).first().addClass('ass-transform-rotate-180');
    }
});

function displayGlobalAlerts() {
    jQuery('.ass-global-alert').hide();
    if (proxyLiveData.globalAlerts != undefined && typeof proxyLiveData.globalAlerts == 'object' && assi_plugin_data?.manage_options != undefined && assi_plugin_data.manage_options == true) {
        for (const [key, value] of Object.entries(proxyLiveData.globalAlerts)) {
            jQuery('.ass-global-alert[data-alert-id="' + key + '"]').show();
            if (key == 'lost_connection') {
                if (value.email != undefined) {
                    jQuery('.ass-global-alert-lost-connection-email').html(value.email);
                } else {
                    jQuery('.ass-global-alert-lost-connection-email').html('');
                }
            }
        };
        configureAccountPage();
    }
}

jQuery(document).on('click', '.ass-global-alert-lost-connection-email', function (e) {
    e.preventDefault();
    window.location.href = `#/account?email=` + (proxyLiveData.globalAlerts.lost_connection.email != undefined ? proxyLiveData.globalAlerts.lost_connection.email : '');
});

jQuery(document).on('click', '.ass-alert-close-lost-connection', function () {
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        cache: false,
        data: {
            action: 'assi_global_alert_delete',
            type: 'lost_connection',
            assi_security_nonce: jQuery('#assi_security_nonce').val(),
        },
        success: function (data) {
            data = JSON.parse(data);
            if (data.result != undefined && data.global_alerts != undefined) {
                proxyLiveData.globalAlerts = data.global_alerts;
                displayGlobalAlerts();
            } else if (data.error != undefined && data.error_message != undefined) {
                if (data.error == 'nonce') {
                    showNonceNotice();
                } else {
                    showToast({
                        message: data.error_message,
                        type: 'danger'
                    });
                }
            } else {
                showToast({ type: 'danger' });
            }
        },
        error: function () {
            showToast({ type: 'danger' });
        }
    });
});

function updateProxyUserData(userData = null) {
    proxyLiveData.creditsOpen = (userData.credits_open != undefined && userData.credits_open != null ? userData.credits_open : 0);
    proxyLiveData.creditsTotal = (userData.credits_total != undefined && userData.credits_total != null ? userData.credits_total : 0);
    proxyLiveData.planId = (userData.plan_id != undefined && userData.plan_id != null ? userData.plan_id : 0);
    proxyLiveData.maxChats = (userData.max_chats != undefined && userData.max_chats != null ? userData.max_chats : 0);
    proxyLiveData.maxTemplates = (userData.max_templates != undefined && userData.max_templates != null ? userData.max_templates : 0);
    proxyLiveData.promocreditsOpen = (userData.promotion.credits_open != undefined && userData.promotion.credits_open != null ? userData.promotion.credits_open : 0);
    proxyLiveData.promoCreditsTotal = (userData.promotion.credits_total != undefined && userData.promotion.credits_total != null ? userData.promotion.credits_total : 0);
    if (userData.registered != undefined && userData.registered != null && assi_plugin_data?.user_account?.plan?.registered != undefined) {
        assi_plugin_data.user_account.plan.registered = userData.registered;
    }
    if (userData.bonus_available != undefined && userData.bonus_available != null && assi_plugin_data?.user_account?.plan?.bonus_available != undefined) {
        assi_plugin_data.user_account.plan.bonus_available = userData.bonus_available;
    }
    if (userData.display_name != undefined && userData.display_name != null && assi_plugin_data?.user_account?.plan?.display_name != undefined) {
        assi_plugin_data.user_account.plan.display_name = userData.display_name;
    }
}