import { d as cleanupOldConversations } from './utils-DK_Yhmpx.js';

// Utility: Generate UUID
function generateUUID() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0, v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}
// CDN Path for language files
const cdnPath = "https://cdn.ai12z.net/assets/bot";
// Static import map for all supported languages
const langImporters = {
    ar: () => import(`${cdnPath}/v1/lang/ar.js`),
    de: () => import(`${cdnPath}/v1/lang/de.js`),
    en: () => import(`${cdnPath}/v1/lang/en.js`),
    es: () => import(`${cdnPath}/v1/lang/es.js`),
    fa: () => import(`${cdnPath}/v1/lang/fa.js`),
    fr: () => import(`${cdnPath}/v1/lang/fr.js`),
    hi: () => import(`${cdnPath}/v1/lang/hi.js`),
    it: () => import(`${cdnPath}/v1/lang/it.js`),
    ja: () => import(`${cdnPath}/v1/lang/ja.js`),
    ko: () => import(`${cdnPath}/v1/lang/ko.js`),
    nl: () => import(`${cdnPath}/v1/lang/nl.js`),
    pl: () => import(`${cdnPath}/v1/lang/pl.js`),
    pt: () => import(`${cdnPath}/v1/lang/pt.js`),
    ro: () => import(`${cdnPath}/v1/lang/ro.js`),
    sv: () => import(`${cdnPath}/v1/lang/sv.js`),
    th: () => import(`${cdnPath}/v1/lang/th.js`),
    tr: () => import(`${cdnPath}/v1/lang/tr.js`),
    uk: () => import(`${cdnPath}/v1/lang/uk.js`),
    vi: () => import(`${cdnPath}/v1/lang/vi.js`),
    zh: () => import(`${cdnPath}/v1/lang/zh.js`),
    // Add more as needed
};
// Common function to load language file
async function loadLanguageFile(langCode) {
    const importer = langImporters[langCode];
    if (importer) {
        try {
            const module = await importer();
            return module.default;
        }
        catch (_a) {
            return {};
        }
    }
    return {};
}
function insertCustomCSS(shadowRoot, css) {
    if (!shadowRoot)
        return;
    const linkEl = document.createElement("link");
    linkEl.setAttribute("rel", "stylesheet");
    linkEl.setAttribute("href", css);
    shadowRoot.appendChild(linkEl);
}
// Utility: Insert custom JS into a shadow root
function insertCustomJS(shadowRoot, jsSrc) {
    if (!shadowRoot)
        return;
    const scriptEl = document.createElement("script");
    scriptEl.setAttribute("type", "text/javascript");
    scriptEl.setAttribute("src", jsSrc);
    shadowRoot.appendChild(scriptEl);
}
// Utility: Detect language from navigator
function detectLanguage() {
    let language = (navigator.languages && navigator.languages[0]) || // Chrome / Firefox
        navigator.language; // All browsers
    let shortLang = language;
    if (shortLang.indexOf("-") !== -1)
        shortLang = shortLang.split("-")[0];
    if (shortLang.indexOf("_") !== -1)
        shortLang = shortLang.split("_")[0];
    return shortLang;
}
// Utility: Check if user is on Mac
function isMac() {
    return /(Mac|iPhone|iPod|iPad)/i.test(navigator.userAgent);
}
// Utility: Set local storage data
function setLocalData(key, data) {
    localStorage.setItem(key, JSON.stringify(data));
}
// Utility: Check if click is outside modal
function isOutsideClick(event, className) {
    return event.target.classList.contains(className);
}
// Utility: Create timer for auto reset
function createAutoResetTimer(callback, interval) {
    return setInterval(callback, interval);
}
// Utility: Clear timer
function clearTimer(timer) {
    if (timer) {
        clearInterval(timer);
    }
}
// Utility: Validate form input
function validateFormInput(search, imgFiles) {
    // console.log("Validating form input:", { search, imgFiles })
    return !search && (search === null || search === void 0 ? void 0 : search.length) < 3 && imgFiles && imgFiles.length < 1;
    // return !search || (search.length < 3 && (!imgFiles || imgFiles.length < 1))
}
// Utility: Create chat message object
function createChatMessage(message, type, status = "success", images, id, insightId, thumbsId, formModel) {
    return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ message,
        type,
        status }, (images && { images })), (id && { id })), (insightId && { insightId })), (thumbsId && { thumbsId })), (formModel && { formModel }));
}
// Utility: Update chat history
function updateChatHistory(chatHistory, newMessage, index) {
    if (index !== undefined) {
        return [...chatHistory.slice(0, index), newMessage, ...chatHistory.slice(index + 1)];
    }
    return [...chatHistory, newMessage];
}
// Utility: Remove last message from chat history
function removeLastMessage(chatHistory) {
    return chatHistory.slice(0, -1);
}
// Utility: Check if max questions reached
function isMaxQuestionsReached(questionCounter, maxQuestions) {
    return maxQuestions > 0 && questionCounter > maxQuestions;
}
function getConversationHistory(visitorId) {
    try {
        const storedData = localStorage.getItem(`${visitorId}`);
        return storedData ? JSON.parse(storedData) : [];
    }
    catch (error) {
        console.warn("Failed to read conversation history:", error);
        return [];
    }
}
function saveConversation(projectId, conversationList, conversationId, configId, visitorId, controlType, state) {
    // const visitorId = "ai12z-cta-history"
    if (!projectId) {
        return;
    }
    const clonedMessages = JSON.parse(JSON.stringify(conversationList));
    let pastMessages = getConversationHistory(visitorId);
    let conversationExists = [];
    // The local storage conversation length
    if (pastMessages.length > 0) {
        if (configId) {
            conversationExists = pastMessages.filter(item => item.conversationId === conversationId && item.projectId === projectId && item.configId === configId);
        }
        else {
            conversationExists = pastMessages.filter(item => item.conversationId === conversationId && item.projectId === projectId);
        }
        if (conversationExists.length > 0) {
            conversationExists[0].messages = clonedMessages;
            conversationExists[0].date = new Date();
            if (controlType === "bot") {
                conversationExists[0].botState = state;
            }
        }
        else {
            pastMessages.push({
                conversationId: conversationId,
                projectId,
                configId,
                date: new Date(),
                messages: clonedMessages,
                botState: controlType === "bot" ? state : {},
            });
        }
    }
    else {
        pastMessages.push({
            conversationId,
            projectId,
            configId,
            date: new Date(),
            messages: clonedMessages,
            botState: controlType === "bot" ? state : {},
        });
    }
    if (conversationList.length > 0) {
        const cleanedMessages = cleanupOldConversations(pastMessages);
        try {
            window.localStorage.setItem(`${visitorId}`, JSON.stringify(cleanedMessages));
        }
        catch (error) {
            if ((error === null || error === void 0 ? void 0 : error.name) === "QuotaExceededError") {
                const aggressiveCleanup = cleanupOldConversations(pastMessages, 1 * 1024 * 1024);
                try {
                    window.localStorage.setItem(`${visitorId}`, JSON.stringify(aggressiveCleanup));
                }
                catch (secondError) {
                    console.error("AI12Z: Even aggressive cleanup failed:", secondError);
                    window.localStorage.removeItem(`${visitorId}`);
                }
            }
        }
    }
}
function getActiveConfigId(configId) {
    const rawConfigId = configId !== null && configId !== void 0 ? configId : "";
    return typeof rawConfigId === "string" ? rawConfigId.trim() : "";
}
function filterConversationHistoryByProjectAndConfig(conversationList, configId, projectId) {
    const activeConfigId = getActiveConfigId(configId);
    const hasActiveConfigId = activeConfigId.length > 0;
    return conversationList.filter(item => {
        if (projectId && item.projectId !== projectId) {
            return false;
        }
        const itemConfigId = typeof (item === null || item === void 0 ? void 0 : item.configId) === "string" ? item.configId.trim() : "";
        if (!itemConfigId) {
            return true;
        }
        if (!hasActiveConfigId) {
            return true;
        }
        return itemConfigId === activeConfigId;
    });
}

export { getConversationHistory as a, setLocalData as b, createChatMessage as c, detectLanguage as d, clearTimer as e, filterConversationHistoryByProjectAndConfig as f, generateUUID as g, isOutsideClick as h, isMaxQuestionsReached as i, createAutoResetTimer as j, insertCustomJS as k, loadLanguageFile as l, insertCustomCSS as m, isMac as n, removeLastMessage as r, saveConversation as s, updateChatHistory as u, validateFormInput as v };
