// Wrap in IIFE to avoid conflicts with index.ts
(function () {
  const getCurrentScript = (): HTMLScriptElement | null => {
    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;
  };

  type WidgetEnvironment = "production" | "development" | "staging";

  const getEnvironment = (
    value: string | null
  ): WidgetEnvironment | undefined => {
    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: Promise<void> | null = null;
  let widgetCssTextPromise: Promise<string> | null = null;

  // Auto-initialize from URL parameters (no shadow DOM needed in iframe)
  const initializeFromUrlParams = async (): Promise<void> => {
    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 context = urlParams.get("context");
    const baseUrl = urlParams.get("baseUrl") || undefined;
    const environment =
      getEnvironment(urlParams.get("environment")) ?? "production";
    const container = document.getElementById("root") || document.body;
    try {
      await Promise.all([
        loadWidgetCss(),
        loadWidgetScript(),
      ])
      if (!window?.renderMedAssist || 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" }, "*");
          }
        },
        context: context ? JSON.parse(context) : undefined,
        baseUrl,
        displayMode: "full" as "full" | "widget",//for iframe default display mode is full
      };
      window.renderMedAssist(container, agentId, config);
    } catch (error) {
      console.error("Failed to initialize MedAssist widget", error);
      throw error;
    }
  };

  async function loadWidgetCss(): Promise<void> {
    // Check if already loaded
    const existingLink = document.querySelector<HTMLLinkElement>(`link[data-medassist-style='true']`);

    if (existingLink) {
      return;
    }
    if (!widgetCssTextPromise) {
      widgetCssTextPromise = new Promise((resolve, reject) => {
        const link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = WIDGET_CSS_URL;
        link.setAttribute("data-medassist-style", "true");

        link.onload = () => {
          resolve("");
        };
        link.onerror = () => {
          reject(new Error(`Failed to load ${WIDGET_CSS_URL}`));
        };
        document.head.appendChild(link);
      });
    }

    await widgetCssTextPromise;
  }

  function loadWidgetScript(): Promise<void> {
    if (!widgetScriptPromise) {
      widgetScriptPromise = new Promise<void>((resolve, reject) => {
        const existingScript = document.querySelector<HTMLScriptElement>(
          `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 {
      try {
        initializeFromUrlParams();
      } catch (error) {
        console.error("Failed to initialize MedAssist widget", error);
      }
    }
  }
})();

