"use client";
import * as React from "react";
import { Check, Copy } from "lucide-react";
import { cn } from "@/lib/utils";

export interface CopyTextProps {
  value: string;
  display?: string;
  className?: string;
  truncate?: boolean;
}

export function CopyText({ value, display, className, truncate }: CopyTextProps) {
  const [copied, setCopied] = React.useState(false);
  const onCopy = async (e: React.MouseEvent) => {
    e.stopPropagation();
    e.preventDefault();
    try {
      await navigator.clipboard.writeText(value);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {
      /* ignore */
    }
  };
  return (
    <button
      type="button"
      onClick={onCopy}
      title={value}
      className={cn(
        "group inline-flex max-w-full items-center gap-1.5 rounded font-mono text-[0.78rem] text-foreground/85 transition-colors hover:text-foreground",
        className,
      )}
    >
      <span className={cn(truncate && "truncate")}>{display ?? value}</span>
      {copied ? (
        <Check className="h-3 w-3 shrink-0 text-success" />
      ) : (
        <Copy className="h-3 w-3 shrink-0 text-muted-foreground/60 opacity-0 transition-opacity group-hover:opacity-100" />
      )}
    </button>
  );
}
