import { ref } from 'vue'

const DEFAULT_MS = 2000

/**
 * Clipboard copy with short-lived button hint ("已复制" / "复制失败").
 */
export function useClipboardFeedback(resetMs = DEFAULT_MS) {
  const hint = ref('')
  let timer = null

  const copy = async (text) => {
    if (!text) return
    try {
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(text)
      } else {
        const ta = document.createElement('textarea')
        ta.value = text
        ta.setAttribute('readonly', '')
        ta.style.position = 'fixed'
        ta.style.left = '-9999px'
        document.body.appendChild(ta)
        ta.select()
        document.execCommand('copy')
        document.body.removeChild(ta)
      }
      hint.value = '已复制'
    } catch {
      hint.value = '复制失败'
    }
    clearTimeout(timer)
    timer = setTimeout(() => {
      hint.value = ''
    }, resetMs)
  }

  const dispose = () => {
    clearTimeout(timer)
    timer = null
  }

  return { hint, copy, dispose }
}
