import { getI18n } from '~/i18n/instance'

export function formatTimeAgo(timestampSeconds: number, nowMs = Date.now()): string {
  const t = getI18n().t
  const seconds = Math.max(0, Math.floor(nowMs / 1000) - timestampSeconds)
  if (seconds < 60) {
    return t('common:time.justNow')
  }
  const minutes = Math.floor(seconds / 60)
  if (minutes < 60) {
    return t('common:time.minutesAgo', { count: minutes })
  }
  const hours = Math.floor(minutes / 60)
  if (hours < 24) {
    return t('common:time.hoursAgo', { count: hours })
  }
  const days = Math.floor(hours / 24)
  if (days < 30) {
    return t('common:time.daysAgo', { count: days })
  }
  return t('common:time.monthsAgo', { count: Math.floor(days / 30) })
}

function _timeAgoShort(tsSeconds: number, nowMs: number): string {
  const diff = Math.floor(nowMs / 1000) - tsSeconds
  if (diff < 60) {
    return getI18n().t('common:time.justNow')
  }
  if (diff < 3600) {
    return `${Math.floor(diff / 60)}m`
  }
  if (diff < 86400) {
    return `${Math.floor(diff / 3600)}h`
  }
  if (diff < 2592000) {
    return `${Math.floor(diff / 86400)}d`
  }
  return `${Math.floor(diff / 2592000)}mo`
}

const timestampFmt = new Intl.DateTimeFormat(undefined, {
  dateStyle: 'short',
  timeStyle: 'short',
})

const timeOnlyFmt = new Intl.DateTimeFormat('en-US', {
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false,
})

function _formatTimestamp(tsSeconds: number): string {
  return timestampFmt.format(tsSeconds * 1000)
}

export function formatTimeOnly(tsMs: number): string {
  return timeOnlyFmt.format(tsMs)
}
