'use client';

import { Check, Copy } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

import { cn } from '@/lib/utils';

/** Icon button that copies a value; the icon swaps to a check for 1.5s. */
export function CopyButton({ value, label = 'Copy', className, notify = false }: { value: string; label?: string; className?: string; /** Also show a "Copied" toast. */ notify?: boolean }) {
  const [copied, setCopied] = useState(false);
  return (
    <button
      type="button"
      aria-label={copied ? 'Copied' : label}
      className={cn(
        'grid h-7 w-7 shrink-0 place-items-center rounded-md text-subtle-foreground transition-colors hover:bg-surface-muted hover:text-foreground',
        copied && 'text-success hover:text-success',
        className,
      )}
      onClick={(event) => {
        event.preventDefault();
        event.stopPropagation();
        void navigator.clipboard.writeText(value).then(() => {
          setCopied(true);
          if (notify) toast.success('Copied');
          window.setTimeout(() => setCopied(false), 1500);
        });
      }}
    >
      {copied ? <Check className="h-3.5 w-3.5" aria-hidden="true" /> : <Copy className="h-3.5 w-3.5" aria-hidden="true" />}
    </button>
  );
}
