// @ts-nocheck
const scriptElementId = 'messaggera-script';

export const Messaggera = (websiteId: string, userData: object) => {
    console.log('messaggera script called')
    if (!websiteId || typeof websiteId !== "string" || !/^[a-zA-Z0-9-_]+$/.test(websiteId)) {
        console.error("Invalid Website ID.");
        return;
    }

    if (userData) {
        if (typeof userData !== "object" || Array.isArray(userData) || Object.keys(userData).length === 0) {
            throw new Error("User data must be a non-empty object.");
        }

        const { id, email, ...optionalData } = userData;
        if (!id || typeof id !== "string") {
            throw new Error("The 'id' field is required and must be a string.");
        }
        if (!email || typeof email !== "string" || !/\S+@\S+\.\S+/.test(email)) {
            throw new Error("The 'email' field is required and must be a valid email address.");
        }

        window.$takiChat = [];
        window.$takiChat.push({ id, email, ...optionalData });
    }

    if (typeof window !== 'undefined') {
        window.WEBSITE_ID = websiteId;
        init();
    }
};

const init = () => {
    if (isDocumentReady()) {
        addScriptToPage();
    } else {
        document.addEventListener('readystatechange', handleReadyStateChange);
        window.addEventListener('load', addScriptToPage, { once: true });
    }
};

const handleReadyStateChange = () => {
    if (isDocumentReady()) {
        document.removeEventListener('readystatechange', handleReadyStateChange);
        addScriptToPage();
    }
};

const addScriptToPage = () => {
    if (document.getElementById(scriptElementId)) return;

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.id = scriptElementId;

    script.src = `https://api.messaggera.com/api/owner/websites/${window.WEBSITE_ID}/check?q=${new Date().getTime()}`;
    const firstScript = document.getElementsByTagName('script')[0];
    if (firstScript && firstScript.parentNode) {
        firstScript.parentNode.insertBefore(script, firstScript);
    }
};

const isDocumentReady = () =>
    document.readyState === 'complete' || document.readyState === 'interactive';

export default Messaggera;