export type CopyTextResult = 'success' | 'denied' | 'failed'

function fallbackCopy(text: string): boolean {
  try {
    const ta = document.createElement('textarea')
    ta.value = text
    ta.setAttribute('readonly', '')
    ta.style.position = 'fixed'
    ta.style.left = '-9999px'
    ta.style.top = '0'
    document.body.appendChild(ta)
    ta.focus()
    ta.select()
    const ok = document.execCommand('copy')
    document.body.removeChild(ta)
    return ok
  } catch {
    return false
  }
}

async function queryClipboardPermission(): Promise<PermissionState | null> {
  if (!navigator.permissions?.query) return null
  try {
    const result = await navigator.permissions.query({ name: 'clipboard-write' as PermissionName })
    return result.state
  } catch {
    return null
  }
}

function isClipboardDeniedError(e: unknown): boolean {
  const err = e as DOMException
  return err?.name === 'NotAllowedError' || err?.name === 'SecurityError'
}

export async function copyTextToClipboard(text: string): Promise<CopyTextResult> {
  const value = text?.trim()
  if (!value) return 'failed'

  const perm = await queryClipboardPermission()
  if (perm === 'denied') return 'denied'

  if (navigator.clipboard?.writeText) {
    try {
      await navigator.clipboard.writeText(value)
      return 'success'
    } catch (e) {
      if (isClipboardDeniedError(e)) return 'denied'
    }
  }

  if (fallbackCopy(value)) return 'success'
  return 'failed'
}

export function isMacChrome(): boolean {
  if (typeof navigator === 'undefined') return false
  const ua = navigator.userAgent
  return /Macintosh|Mac OS X/.test(ua) && /Chrome\//.test(ua) && !/Edg\//.test(ua)
}
