"use client";

import { useState, type ReactNode } from "react";

type CopyButtonProps = {
  value: string;
  label: string;
  copiedLabel?: string;
  className?: string;
  children: ReactNode;
};

export default function CopyButton({
  value,
  label,
  copiedLabel = "Copied!",
  className = "rounded-md p-1 text-neutral-600 transition-colors duration-200 hover:text-neutral-200 cursor-pointer",
  children,
}: CopyButtonProps) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async (e: React.MouseEvent<HTMLButtonElement>) => {
    e.currentTarget.blur();
    try {
      await navigator.clipboard.writeText(value);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1500);
    } catch {
      // clipboard unavailable — silently ignore
    }
  };

  return (
    <span className="group relative inline-flex">
      <button
        type="button"
        onClick={handleCopy}
        aria-label={label}
        className={className}
      >
        {children}
      </button>
      <span
        role="tooltip"
        className="
          pointer-events-none absolute bottom-full left-1/2 mb-2 -translate-x-1/2
          rounded-md bg-neutral-800 px-2 py-1 text-xs text-neutral-100
          whitespace-nowrap opacity-0
          transition-opacity duration-150
          group-hover:opacity-100 group-focus-within:opacity-100
        "
      >
        {copied ? copiedLabel : label}
      </span>
    </span>
  );
}
