export function formatCurrency(n: number, currency = "USD", maxFractionDigits?: number) {
  try {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency,
      maximumFractionDigits: maxFractionDigits ?? (Math.abs(n) >= 1000 ? 0 : 2),
    }).format(n);
  } catch {
    return `$${n.toFixed(2)}`;
  }
}

export function formatCompact(n: number, currency = "USD", maxFractionDigits?: number) {
  try {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency,
      notation: "compact",
      maximumFractionDigits: maxFractionDigits ?? 1,
    }).format(n);
  } catch {
    return `$${n.toFixed(0)}`;
  }
}

export function relativeDay(date: string | Date) {
  const d = typeof date === "string" ? new Date(date) : date;
  if (Number.isNaN(d.getTime())) return "—";
  const now = new Date();
  const startOf = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
  // Compare calendar days so 2am and 11pm on the same date agree.
  const diff = Math.round((startOf(now) - startOf(d)) / 86_400_000);
  if (diff === 0) return "Today";
  if (diff === 1) return "Yesterday";
  if (diff > 1 && diff < 7) return `${diff}d ago`;
  if (diff === -1) return "Tomorrow";
  if (diff < -1 && diff > -7) return `in ${Math.abs(diff)}d`;
  return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
