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

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

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

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

    initializeFonts();

    const widgetElement = document.querySelector(
      ".spectator-views-placeholder"
    );
    widgetElement.appendChild(widgetContainer);

    renderWidget(shadowRoot, theme, state);

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