// Money + date + relative-time formatters used app-wide.

function fmt$(n, opts = {}) {
  const { compact = false, sign = false } = opts;
  if (n == null || isNaN(n)) return '—';
  const abs = Math.abs(n);
  let str;
  if (compact && abs >= 10000) {
    if (abs >= 1e6) str = '$' + (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M';
    else str = '$' + (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'k';
  } else {
    str = '$' + abs.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
    if (n < 0) str = '-' + str;
  }
  if (sign && n > 0) str = '+' + str;
  return str;
}

function fmtDate(iso, opts = {}) {
  const d = new Date(iso + 'T12:00:00');
  const { short = false, year = false } = opts;
  const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  if (short) return `${months[d.getMonth()]} ${d.getDate()}`;
  if (year) return `${months[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`;
  return `${months[d.getMonth()]} ${d.getDate()}`;
}

function relativeTime(iso) {
  const d = new Date(iso);
  const now = new Date('2026-04-24T10:00:00');
  const diff = Math.floor((now - d) / 1000);
  if (diff < 60) return 'just now';
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  return `${Math.floor(diff / 86400)}d ago`;
}

Object.assign(window, { fmt$, fmtDate, relativeTime });
