<script>
  import IDBManager from "@components/ts/IDBManager";

  function switchTheme() {
    const currentTheme = Alu.store.get("theme");
    document.documentElement.setAttribute("data-theme", currentTheme.value!);
  }

  switchTheme();

  document.addEventListener("astro:after-swap", switchTheme);

  const idb = IDBManager.loadIDB("AluDB", 1);

  idb.onsuccess = () => {
    const store = IDBManager.GetStore("InstalledExtensions", "readonly");
    store.getAll().onsuccess = (event) => {
      const result = (event.target as IDBRequest).result;
      if (result) {
        result.forEach((extension: ExtensionMetadata) => {
          if (extension.type === "theme" && extension.themeName) {
            // Load theme CSS
            const decoder = new TextDecoder();
            const style = decoder.decode(extension.scriptCopy!);


            loadStyleFromString(style);

            document.addEventListener("astro:after-swap", () => {
              loadStyleFromString(style);
            });
          }
        });
      }
    };
  };
  function loadStyleFromString(style: string) {
    const styleEl = document.createElement("style");
    styleEl.textContent = style;
    document.head.appendChild(styleEl);
  }
</script>
