import i18next from 'i18next'

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

  lang = lang || i18next.language || 'en'
  const pad = (n) => String(n).padStart(2, '0')
  const dd = pad(d.getDate())
  const mm = pad(d.getMonth() + 1)
  const yyyy = d.getFullYear()

  if (lang === 'fr') {
    return `${dd}/${mm}/${yyyy}`
  }
  return `${mm}/${dd}/${yyyy}`
}

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 ''

  lang = lang || i18next.language || 'en'
  const pad = (n) => String(n).padStart(2, '0')
  const dd = pad(d.getDate())
  const mm = pad(d.getMonth() + 1)
  const yyyy = d.getFullYear()
  const HH = pad(d.getHours())
  const min = pad(d.getMinutes())
  const ss = pad(d.getSeconds())

  if (lang === 'fr') {
    return `${dd}/${mm}/${yyyy}, ${HH}:${min}:${ss}`
  }
  return d.toLocaleString()
}
