/* date-only strings must parse as LOCAL dates — new Date('2026-07-09') is UTC
   midnight and renders as the previous day west of Greenwich */
export const parseD = (s: string | Date): Date => {
  if (s instanceof Date) return s;
  const str = String(s);
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(str.slice(0, 10));
  return m && str.length <= 10 ? new Date(+m[1], +m[2] - 1, +m[3]) : new Date(str);
};

export const fmtD = (iso: string) =>
  parseD(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });

export const fmtDY = (iso: string) =>
  parseD(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });

export const hm = (sec: number) => {
  const h = Math.floor(sec / 3600);
  const m = Math.round((sec % 3600) / 60);
  return `${h}h ${String(m).padStart(2, '0')}m`;
};

export const kfmt = (n: number) =>
  n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(Math.round(n));

export const num = (n: number) => Number(n).toLocaleString('en-US');

export const cap = (s: string | null | undefined) => String(s || '').replace(/_/g, ' ');

export const daysAgo = (iso: string) =>
  Math.floor((Date.now() - parseD(iso).getTime()) / 86400000);

export const agoTxt = (iso: string) => {
  const d = daysAgo(iso);
  return d === 0 ? 'today' : d === 1 ? 'yesterday' : `${d} days ago`;
};
