// One home for the renderer's date/time formatters (M9). These were previously
// three private functions — `relTime` (LibraryView), `formatWhen` (HistoryView)
// and `fmtSchedule` (QueueItem) — each reimplementing date math inline.

/** Relative "time since" label: "just now" / "5 min ago" / "3 h ago" /
 *  "2 d ago" / "3 w ago" / "2 mo ago". Returns "never" for a missing
 *  timestamp. (Library last-indexed.) */
export function relTime(ms?: number): string {
  if (!ms) return 'never'
  const mins = Math.round((Date.now() - ms) / 60000)
  if (mins < 1) return 'just now'
  if (mins < 60) return `${mins} min ago`
  const hrs = Math.round(mins / 60)
  if (hrs < 24) return `${hrs} h ago`
  const days = Math.round(hrs / 24)
  if (days < 7) return `${days} d ago`
  const weeks = Math.round(days / 7)
  if (weeks < 5) return `${weeks} w ago`
  return `${Math.round(days / 30)} mo ago`
}

/** Absolute "when" label: "Today, 3:04 PM" / "Yesterday, 3:04 PM" /
 *  "Jun 5" (current year) / "Jun 5, 2024" (past year). (History rows.) */
export function formatWhen(ts: number): string {
  const d = new Date(ts)
  const time = d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
  const now = new Date()
  const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
  const dayMs = 1000 * 60 * 60 * 24
  if (ts >= startOfToday) return `Today, ${time}`
  if (ts >= startOfToday - dayMs) return `Yesterday, ${time}`
  const sameYear = d.getFullYear() === now.getFullYear()
  return d.toLocaleDateString(undefined, {
    month: 'short',
    day: 'numeric',
    ...(sameYear ? {} : { year: 'numeric' })
  })
}

/** Full date + time for a scheduled download, e.g. "Jun 5, 2025, 3:04 PM".
 *  Returns '' if the timestamp can't be formatted. (Queue scheduled badge.) */
export function fmtSchedule(ms: number): string {
  try {
    return new Date(ms).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })
  } catch {
    return ''
  }
}
