// Helper function to create and open MedAssist widget in fullscreen iframe
// This eliminates the need for Sebenza app to add custom styles

type WidgetEnvironment = "production" | "development" | "staging";
type TContext = {
  profile?: {
    name?: string;
    age?: number;
    mobile?: string;
    marital_status?: string;
    gender?: "F" | "M" | "O";
  };
  intent?: string;
  user_location?: {
    lat: number;
    long: number;
  };
  referer?: string;
};
interface OpenIframeOptions {
  agentId: string;
  title?: string;
  iconUrl?: string;
  environment?: WidgetEnvironment;
  iframeBaseUrl?: string; // Base URL where iframe.html is hosted
  context?: TContext;
}

const DEFAULT_IFRAME_BASE = "https://unpkg.com/@eka-care/medassist-widget-embed@latest/dist/";

// Get current script to determine base URL
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;
};

const getIframeBaseUrl = (customUrl?: string): string => {
  return customUrl || DEFAULT_IFRAME_BASE;
};

export const openMedAssistIframe = (options: OpenIframeOptions): void => {
  const { agentId, title, iconUrl, environment, iframeBaseUrl ,context} = options;

  if (!agentId) {
    console.error("Agent ID is required");
    return;
  }

  // Remove existing iframe if any
  const existingIframe = document.getElementById("medassist-iframe");
  if (existingIframe) {
    existingIframe.remove();
  }

  // Build iframe URL
  const baseUrl = getIframeBaseUrl(iframeBaseUrl);
  const iframeUrl = new URL(`${baseUrl}iframe.html`);
  iframeUrl.searchParams.set("agentId", agentId);
  if (title) {
    iframeUrl.searchParams.set("title", title);
  }
  if (iconUrl) {
    iframeUrl.searchParams.set("iconUrl", iconUrl);
  }
  if (environment) {
    iframeUrl.searchParams.set("environment", environment);
  }
  if (context) {
    iframeUrl.searchParams.set("context", JSON.stringify(context));
  }
  // Create iframe element
  const iframe = document.createElement("iframe");
  iframe.id = "medassist-iframe";
  iframe.src = iframeUrl.toString();
  iframe.setAttribute("allow", "microphone; camera");
  
  // Apply fullscreen styles automatically
  iframe.style.cssText = `
    width: 100vw;
    height: 100vh;
    height: 100dvh;
    border: none;
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9999;
    background: white;
  `;

  // Append to body
  document.body.appendChild(iframe);

  // Listen for close message from iframe
  const messageHandler = (event: MessageEvent) => {
    // Optional: verify origin for security
    // if (event.origin !== "https://your-cdn.com") return;

    if (event.data?.type === "WIDGET_CLOSE") {
      const iframeElement = document.getElementById("medassist-iframe");
      if (iframeElement) {
        iframeElement.remove();
      }
      // Remove event listener after closing
      window.removeEventListener("message", messageHandler);
    }
  };

  window.addEventListener("message", messageHandler);
};

// Make it available on window for easy access
if (typeof window !== "undefined") {
  (window as any).openMedAssistIframe = openMedAssistIframe;
}


