---
import { getI18n } from "src/i18n/i18n";
import Button from "./Button.astro";

interface Props {
  href: string;
  filename: string;
}

const { href, filename } = Astro.props;

const { t } = await getI18n(Astro.locals.currentLocale);
---

{/* ------------------------------------------- HTML ------------------------------------------- */}

<download-button href={href} filename={filename} class="when-js when-no-print">
  <Button title={t("global.downloadButton")} icon="material-symbols:download" />
</download-button>

{/* ------------------------------------------- JS --------------------------------------------- */}

<script>
  import { customElement } from "src/utils/customElements";

  customElement("download-button", (elem) => {
    const href = elem.getAttribute("href");
    const filename = elem.getAttribute("filename");

    if (!href || !filename) return;

    elem.addEventListener("click", async () => {
      const res = await fetch(href);
      const blob = await res.blob();
      const blobURL = window.URL.createObjectURL(blob);

      var link = document.createElement("a");
      link.download = filename;
      link.href = blobURL;
      link.click();
      link.remove();
    });
  });
</script>