---
interface Props {
  text: string;
  class?: string;
}
const { text, class: className } = Astro.props;
---

<button
  type="button"
  class:list={[
    "copy-btn rounded p-1.5 text-overlay transition-colors hover:bg-mantle hover:text-text",
    className,
  ]}
  data-copy={text}
  aria-label="Copy command to clipboard"
  title="Copy"
>
  <svg
    class="copy-icon h-4 w-4"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
  </svg>
  <svg
    class="check-icon hidden h-4 w-4 text-green"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <path d="M20 6 9 17l-5-5"></path>
  </svg>
</button>
<script>
  const RESET_DELAY_MS = 1500;

  const handleCopy = async (button: HTMLElement) => {
    const text = button.getAttribute("data-copy") ?? "";
    try {
      await navigator.clipboard.writeText(text);
    } catch {
      return;
    }

    const copyIcon = button.querySelector(".copy-icon");
    const checkIcon = button.querySelector(".check-icon");
    copyIcon?.classList.add("hidden");
    checkIcon?.classList.remove("hidden");

    window.setTimeout(() => {
      copyIcon?.classList.remove("hidden");
      checkIcon?.classList.add("hidden");
    }, RESET_DELAY_MS);
  };

  document.addEventListener("click", (event) => {
    const button = (event.target as HTMLElement)?.closest<HTMLElement>(
      ".copy-btn",
    );
    if (button) {
      handleCopy(button);
    }
  });
</script>
