---
import { Icon } from "astro-icon/components";

const meta: Record<string, string> = {};
const {
  "data-meta": dataMeta,
  "data-code": dataCode,
  class: className,
  ...props
} = Astro.props;

if (dataMeta) {
  dataMeta.split(",").forEach((prop: string) => {
    const tokens = prop.split("=");
    meta[tokens[0].trim()] = tokens[1];
  });
}

const languageIcons: Record<string, string> = {
  javascript: "mdi:language-javascript",
  typescript: "mdi:language-typescript",
  csharp: "mdi:language-csharp",
  css: "mdi:language-css3",
  html: "mdi:language-html5",
  bash: "mdi:bash",
  astro: "simple-icons:astro"
};

const language = props["data-language"];

const languageIcon = languageIcons[language];

const title = meta.title;

const copyID = Math.random().toString(36);
---

<figure class="my-4 rounded-b">
  <figcaption>
    <div
      class="bg-primary w-full rounded-t-md border-1 border-gray-600 px-4 py-2 text-white"
    >
      <div class="flex justify-between">
        <div class="flex items-center justify-between gap-2 font-bold">
          {languageIcon && <Icon name={languageIcon} />}
          {
            !languageIcon && language !== "plaintext" && (
              <p class="uppercase">{language}</p>
            )
          }
          {title && <p>{title}</p>}
        </div>
        <button class="font-bold" id=`copy-${copyID}`>
          Copy <Icon name="mdi:content-copy" class="ml-0.5 inline-block" />
        </button>
      </div>
    </div>
  </figcaption>

  <pre
    class:list={["border-x border-b border-gray-600", "rounded-b", className]}
    {...props}><slot /></pre>
</figure>

<script define:vars={{ dataCode, copyID }}>
  if (typeof navigator.clipboard !== undefined) {
    const trigger = document.getElementById(`copy-${copyID}`);

    trigger.addEventListener("click", () => {
      navigator.clipboard.writeText(dataCode);
    });
  }
</script>
