import { useEffect, useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';

interface CopyableEmailProps {
  email: string;
  className?: string;
}

export function CopyableEmail({ email, className }: CopyableEmailProps) {
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    if (!copied) return;
    const id = setTimeout(() => setCopied(false), 1500);
    return () => clearTimeout(id);
  }, [copied]);

  const handleCopy = async (e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      await navigator.clipboard.writeText(email);
      setCopied(true);
      toast.success('Email copied');
    } catch {
      toast.error('Failed to copy email');
    }
  };

  return (
    <button
      type="button"
      onClick={handleCopy}
      aria-label={`Copy ${email}`}
      className={cn(
        'hover:bg-accent inline-flex items-center gap-1.5 rounded-md px-2 py-1 font-mono text-sm transition-colors',
        className,
      )}
    >
      <span>{email}</span>
      {copied ? (
        <Check className="text-muted-foreground size-3.5" />
      ) : (
        <Copy className="text-muted-foreground size-3.5" />
      )}
    </button>
  );
}
