import { JSX } from "solid-js/jsx-runtime";
import { render } from "solid-js/web";

// const DEFAULT_ROOT_ELEMENT_ID = "mm-external-elements-container";

// export const runAppEvent = new Event("runApp", { bubbles: true });

export function setupRoot(identifier: string): HTMLElement {
  const rootElement = document.body.appendChild((<div id={identifier}></div>) as HTMLElement);

  // addStyles(bootstrap_css, custom_css);

  if (import.meta.env.DEV && !(rootElement instanceof HTMLElement)) {
    throw new Error(
      "Root element not found. Did you forget to add it to your index.html? Or maybe the id attribute got mispelled?"
    );
  }

  return rootElement;
}

export function addStyles(...stylesheets: string[]) {
  stylesheets.forEach((stylesheet) => {
    const blob = new Blob([stylesheet], { type: "text/css" });
    const link = document.createElement("link");
    link.classList.add("mm-custom-stylesheet");
    link.rel = "stylesheet";
    link.href = URL.createObjectURL(blob);
    document.head.appendChild(link);
  });
}

export function mountApp(App: () => JSX.Element, identifier: string, runAppEvent: CustomEvent) {
  if (!identifier.startsWith("mm-")) {
    identifier += "mm-" + identifier;
  }

  let rootElement = document.getElementById(identifier);

  if (rootElement === null) {
    console.log("Mounting App", identifier);
    rootElement = setupRoot(identifier);
    render(() => <App />, rootElement);
  } else {
    console.log("App already mounted. Making App visible");
    window.dispatchEvent(runAppEvent);
  }
}
