import { toast } from 'sonner'

/**
 * 复制文本到剪贴板，带 execCommand fallback
 */
export async function copyToClipboard(text: string, successMsg = '已复制') {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      toast.success(successMsg)
      return
    }
  } catch {
    // fall through to fallback
  }

  // fallback: execCommand('copy') + hidden textarea
  try {
    const textarea = document.createElement('textarea')
    textarea.value = text
    textarea.style.position = 'fixed'
    textarea.style.opacity = '0'
    textarea.style.left = '-9999px'
    document.body.appendChild(textarea)
    textarea.focus()
    textarea.select()
    const ok = document.execCommand('copy')
    document.body.removeChild(textarea)
    if (ok) {
      toast.success(successMsg)
    } else {
      toast.error('复制失败，请手动复制')
    }
  } catch {
    toast.error('复制失败，请手动复制')
  }
}
