import { CheckIcon, CopyIcon } from 'lucide-react';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

export default function CopyButton({
    value,
    className,
    label = 'Copia link',
}: {
    value: string;
    className?: string;
    label?: string;
}) {
    const [copied, setCopied] = useState(false);

    async function handleCopy() {
        try {
            await navigator.clipboard.writeText(value);
            setCopied(true);
            window.setTimeout(() => setCopied(false), 1500);
        } catch {
            // Clipboard API unavailable (e.g. insecure context); silently ignore.
        }
    }

    return (
        <Button
            type="button"
            variant="ghost"
            size="icon-sm"
            className={cn(className)}
            onClick={handleCopy}
            title={label}
        >
            {copied ? <CheckIcon className="text-primary" /> : <CopyIcon />}
            <span className="sr-only">{label}</span>
        </Button>
    );
}
