"use strict";
// Wrap in IIFE to avoid conflicts with index.ts
(function () {
    const getCurrentScript = () => {
        if (typeof document === "undefined") {
            return null;
        }
        const { currentScript } = document;
        if (currentScript instanceof HTMLScriptElement) {
            return currentScript;
        }
        const scripts = document.getElementsByTagName("script");
        return scripts.length ? scripts[scripts.length - 1] : null;
    };
    const getEnvironment = (value) => {
        if (value === "production" ||
            value === "development" ||
            value === "staging") {
            return value;
        }
        return undefined;
    };
    const DEFAULT_WIDGET_ASSET_BASE = "https://unpkg.com/@eka-care/medassist-widget@latest/dist/";
    const scriptEl = getCurrentScript();
    const scriptBaseUrl = (() => {
        if (!scriptEl) {
            return "";
        }
        try {
            return new URL(".", scriptEl.src || window.location.href).href;
        }
        catch {
            return "";
        }
    })();
    const widgetAssetBaseUrl = (() => {
        if (!scriptEl) {
            return DEFAULT_WIDGET_ASSET_BASE;
        }
        const dataValue = scriptEl.dataset.widgetAssets;
        if (dataValue === "local") {
            return `${scriptBaseUrl}src/`;
        }
        if (dataValue && dataValue.length > 0) {
            try {
                return new URL(dataValue, scriptBaseUrl).href;
            }
            catch {
                return dataValue.endsWith("/") ? dataValue : `${dataValue}/`;
            }
        }
        return DEFAULT_WIDGET_ASSET_BASE;
    })();
    const WIDGET_JS_URL = `${widgetAssetBaseUrl}medassist-widget.js`;
    const WIDGET_CSS_URL = `${widgetAssetBaseUrl}medassist-widget.css`;
    let widgetScriptPromise = null;
    let widgetCssTextPromise = null;
    // Auto-initialize from URL parameters (no shadow DOM needed in iframe)
    const initializeFromUrlParams = async () => {
        var _a;
        const urlParams = new URLSearchParams(window.location.search);
        const agentId = urlParams.get("agentId");
        if (!agentId) {
            console.error("Agent ID is required in URL parameters");
            return;
        }
        const title = urlParams.get("title") || "Medi Clinic";
        const iconUrl = urlParams.get("iconUrl") || undefined;
        const environment = (_a = getEnvironment(urlParams.get("environment"))) !== null && _a !== void 0 ? _a : "production";
        const container = document.getElementById("root") || document.body;
        // Load CSS first
        await loadWidgetCss();
        // Load and wait for script
        await loadWidgetScript();
        if (typeof window.renderMedAssist !== "function") {
            throw new Error("renderMedAssist is not available on window");
        }
        const config = {
            title,
            iconUrl,
            environment,
            onClose: () => {
                // Send message to parent window to close iframe
                if (window.parent !== window) {
                    window.parent.postMessage({ type: "WIDGET_CLOSE" }, "*");
                }
            },
        };
        window.renderMedAssist(container, agentId, config);
    };
    async function loadWidgetCss() {
        // Check if already loaded
        if (document.querySelector("[data-medassist-style='true']")) {
            return;
        }
        if (!widgetCssTextPromise) {
            widgetCssTextPromise = fetch(WIDGET_CSS_URL).then((response) => {
                if (!response.ok) {
                    throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);
                }
                return response.text();
            });
        }
        const cssText = await widgetCssTextPromise;
        const styleTag = document.createElement("style");
        styleTag.setAttribute("data-medassist-style", "true");
        styleTag.textContent = cssText;
        document.head.appendChild(styleTag);
    }
    function loadWidgetScript() {
        if (!widgetScriptPromise) {
            widgetScriptPromise = new Promise((resolve, reject) => {
                const existingScript = document.querySelector(`script[src="${WIDGET_JS_URL}"]`);
                if (existingScript) {
                    if (existingScript.dataset.loaded === "true") {
                        resolve();
                        return;
                    }
                    existingScript.addEventListener("load", () => resolve());
                    existingScript.addEventListener("error", (event) => reject(event.error || new Error("Unknown script loading error")));
                    return;
                }
                const script = document.createElement("script");
                script.src = WIDGET_JS_URL;
                script.async = true;
                script.dataset.widget = "medassist";
                script.onload = () => {
                    script.dataset.loaded = "true";
                    resolve();
                };
                script.onerror = (event) => {
                    if (event instanceof ErrorEvent && event.error) {
                        reject(event.error);
                        return;
                    }
                    reject(new Error(`Failed to load ${WIDGET_JS_URL}`));
                };
                document.head.appendChild(script);
            });
        }
        return widgetScriptPromise;
    }
    // Auto-initialize when script loads
    if (typeof document !== "undefined") {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", initializeFromUrlParams);
        }
        else {
            initializeFromUrlParams();
        }
    }
})();
