/**
 * Turn an ISO-8601 timestamp into a short, humane relative string.
 *
 * Examples:
 *   "just now", "2 minutes ago", "1 hour ago", "yesterday", "3 days ago",
 *   "2 weeks ago", "4 months ago", "1 year ago".
 *
 * Pure function — no deps, no Date mutation. Returns an empty string for
 * missing or unparseable input so callers can easily render nothing.
 */
export function formatAgo(iso: string, now: Date = new Date()): string {
  if (!iso) return "";
  const then = new Date(iso);
  const t = then.getTime();
  if (Number.isNaN(t)) return "";

  const diffMs = now.getTime() - t;
  if (diffMs < 0) return "just now";

  const sec = Math.floor(diffMs / 1000);
  if (sec < 45) return "just now";

  const min = Math.floor(sec / 60);
  if (min < 2) return "1 minute ago";
  if (min < 60) return `${min} minutes ago`;

  const hr = Math.floor(min / 60);
  if (hr < 2) return "1 hour ago";
  if (hr < 24) return `${hr} hours ago`;

  const day = Math.floor(hr / 24);
  if (day < 2) return "yesterday";
  if (day < 7) return `${day} days ago`;

  const week = Math.floor(day / 7);
  if (week < 2) return "1 week ago";
  if (week < 5) return `${week} weeks ago`;

  const month = Math.floor(day / 30);
  if (month < 2) return "1 month ago";
  if (month < 12) return `${month} months ago`;

  const year = Math.floor(day / 365);
  if (year < 2) return "1 year ago";
  return `${year} years ago`;
}
