import fetchWidgetConfig from "../api/fetchWidgetConfig";
import createShadowRoot from "../utils/createShadowRoot";
import initializeFonts from "../html/fonts";
import renderWidgetWithBubble from "./renderWidget";
import shouldRenderWidget from "./render/shouldRenderWidget";

export default async function initializeWidget() {
  try {
    const { config, theme, content } = await fetchWidgetConfig();

    if (!shouldRenderWidget(config)) {
      return;
    }

    const widgetContainer = document.createElement("firevert-widget-root");
    widgetContainer.id = "firevert-widget-root";
    const shadowRoot = createShadowRoot(widgetContainer);

    initializeFonts();

    const widgetElement = document.body;
    widgetElement.appendChild(widgetContainer);

    renderWidgetWithBubble(shadowRoot, config, theme, content);

    console.log(
      "%c🚀 FIREVERT WIDGET INITIALIZED ✨",
      "color: #9900ff; font-size: 18px; font-weight: bold;"
    );
  } catch (error) {
    console.error(error);
  }
}
