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 widgetElement = document.querySelector(
      ".promo-time-widget-placeholder"
    );

    if (!widgetElement) {
      return;
    }

    const widget_instance_id = widgetElement.dataset?.instanceId;

    const { config, theme } = await fetchWidgetConfig(widget_instance_id);

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

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

    initializeFonts();

    widgetElement.appendChild(widgetContainer);

    renderWidget(shadowRoot, theme, config);

    console.log(
      "%c🚀 FIREVERT PROMO TIME WIDGET INITIALIZED ✨",
      "color:rgb(0, 207, 0); font-size: 18px; font-weight: bold;"
    );
  } catch (error) {
    console.error(error);
  }
}
