/**
 * Copy a shareable URL for an item to the clipboard. Prefers TMDB (the
 * most universally-recognised media DB), falls back to IMDB. Returns
 * `null` when neither id is available; caller is expected to fall back
 * to a toast like "no shareable link" in that case.
 */
export function buildShareUrl(opts: {
  tmdbId?: string | number | null
  imdbId?: string | null
  kind?: 'movie' | 'tv' | null
}): string | null {
  const { tmdbId, imdbId, kind } = opts
  if (tmdbId) {
    const numeric = String(tmdbId).replace(/^tmdb-(movie|tv)-/, '')
    return `https://www.themoviedb.org/${kind === 'tv' ? 'tv' : 'movie'}/${numeric}`
  }
  if (imdbId) {
    return `https://www.imdb.com/title/${imdbId}/`
  }
  return null
}

export async function copyToClipboard(text: string): Promise<boolean> {
  try {
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(text)
      return true
    }
  } catch {
    /* fall through */
  }
  // Fallback for ancient browsers / contexts without clipboard API
  try {
    const ta = document.createElement('textarea')
    ta.value = text
    ta.style.position = 'fixed'
    ta.style.opacity = '0'
    document.body.appendChild(ta)
    ta.select()
    const ok = document.execCommand('copy')
    document.body.removeChild(ta)
    return ok
  } catch {
    return false
  }
}
