'use client'

import { ButtonHTMLAttributes, useRef } from 'react'
import { Copy } from 'lucide-react'
import { cn } from '@/utils/cn'

type CopyButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
  textToCopy: string
}

export function CopyButton({ textToCopy, className, ...props }: CopyButtonProps) {
  const buttonRef = useRef<HTMLButtonElement | null>(null)

  const handleCopy = () => {
    navigator.clipboard.writeText(textToCopy)
    const button = buttonRef.current
    if (button) {
      const original = button.innerHTML
      button.innerHTML = 'Copied!'
      button.disabled = true
      setTimeout(() => {
        button.innerHTML = original
        button.disabled = false
      }, 2000)
    }
  }

  return (
    <button
      className={cn(
        'text-fg-dim hover:text-fg transition-colors js-only text-xs cursor-pointer disabled:cursor-default disabled:hover:text-fg-dim',
        className,
      )}
      onClick={handleCopy}
      ref={buttonRef}
      {...props}
    >
      <Copy className="w-4 h-4" />
    </button>
  )
}
