import i18next from 'i18next'

// App language → BCP-47 tag (same mapping as useSpeech.js). Fixed tags keep
// the output deterministic per app language regardless of the OS locale, so
// tests can assert it (en: 03/15/2026, fr: 15/03/2026, da: 15.03.2026).
const LANG_MAP = { en: 'en-US', fr: 'fr-FR', da: 'da-DK' }

function toLangTag(lang) {
  return LANG_MAP[lang || i18next.language] || LANG_MAP.en
}

export function formatDate(date, lang) {
  if (!date) return ''
  const d = date instanceof Date ? date : new Date(date)
  if (isNaN(d.getTime())) return ''

  return new Intl.DateTimeFormat(toLangTag(lang), {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  }).format(d)
}

export function formatItemDuration(ms) {
  if (!ms || ms <= 0) return null
  const totalSecs = Math.round(ms / 1000)
  if (totalSecs <= 0) return null
  const mins = Math.floor(totalSecs / 60)
  const secs = totalSecs % 60
  if (mins === 0) return `${secs}s`
  if (secs === 0) return `${mins}min`
  return `${mins}min${secs}s`
}

export function formatDuration(start, end) {
  if (!start || !end) return null
  const s = start instanceof Date ? start : new Date(start)
  const e = end instanceof Date ? end : new Date(end)
  if (isNaN(s.getTime()) || isNaN(e.getTime())) return null
  const mins = Math.round((e - s) / 60000)
  if (mins <= 0) return null
  if (mins < 60) return `${mins} min`
  const h = Math.floor(mins / 60)
  const m = mins % 60
  return m === 0 ? `${h}h` : `${h}h ${m}min`
}

export function formatDateTime(date, lang) {
  if (!date) return ''
  const d = date instanceof Date ? date : new Date(date)
  if (isNaN(d.getTime())) return ''

  return new Intl.DateTimeFormat(toLangTag(lang), {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  }).format(d)
}
