"use client";

import { IconCheck, IconCopy } from "@tabler/icons-react";
import { useCallback, useState } from "react";

export function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);

  const copy = useCallback(async () => {
    await navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }, [text]);

  return (
    <button
      aria-label={copied ? "Copied" : "Copy code"}
      className="absolute top-3 right-3 rounded-md border border-white/10 bg-white/5 p-1.5 text-neutral-400 opacity-0 backdrop-blur-sm transition-all hover:bg-white/10 hover:text-neutral-200 focus-visible:opacity-100 group-hover/code:opacity-100"
      onClick={copy}
      type="button"
    >
      {copied ? (
        <IconCheck className="text-emerald-400" size={14} />
      ) : (
        <IconCopy size={14} />
      )}
    </button>
  );
}
