<script>
  function loadCloak() {
    const cloak = Alu.store.get("cloak");
    if (cloak) {
      if (cloak && typeof cloak === "object") {
        if (cloak.name != "None") {
          document.title = cloak.name;
          let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement;
          if (!link) {
            link = document.createElement("link");
            link.rel = "icon";
          }
          if (cloak.icon && !cloak.icon.startsWith("http")) {
            cloak.icon = window.location.origin + cloak.icon;
          }
          if (cloak.isCustom) {
            link.href = `/custom-favicon?url=${cloak.icon}`;
          } else {
            link.href = cloak.icon!;
          }

          document.getElementsByTagName("head")[0].appendChild(link);
        }
      }
    } else {
      // Load default cloak
      let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement;
      if (!link) {
        link = document.createElement("link");
        link.rel = "icon";
      }
      link.href = "/favicon.svg";
      document.getElementsByTagName("head")[0].appendChild(link);
    }
  }

  loadCloak();
  document.addEventListener("astro:after-swap", loadCloak);
</script>
