import { ref } from 'vue'

export function useCopy() {
  const copied = ref(false)

  async function copy(text) {
    if (!text) return
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(text)
    } else {
      const el = document.createElement('textarea')
      el.value = text
      el.style.cssText = 'position:fixed;opacity:0'
      document.body.appendChild(el)
      el.select()
      try {
        document.execCommand('copy')
      } finally {
        document.body.removeChild(el)
      }
    }
    copied.value = true
    setTimeout(() => { copied.value = false }, 1500)
  }

  return { copied, copy }
}
