// Every date is rendered in the timezone from Monitoring Settings; callers
// must pass it explicitly so no page can silently fall back to another zone.

// Assembled from parts rather than a locale pattern: locale output differs
// between runtimes (en-GB gives "Sept" on newer ICU builds), and the server
// and browser must render the same string.
function dateParts(date: Date, timeZone: string) {
  const parts = new Intl.DateTimeFormat("en-US", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: true,
    timeZone,
  }).formatToParts(date);
  const get = (type: Intl.DateTimeFormatPartTypes) => parts.find((part) => part.type === type)?.value ?? "";
  return {
    date: `${get("day")} ${get("month")} ${get("year")}`,
    time: `${get("hour")}:${get("minute")} ${get("dayPeriod").toUpperCase()}`,
  };
}

/** e.g. "17 Sep 2026, 09:00 AM" */
export function formatDateTime(date: Date, timeZone: string): string {
  const { date: day, time } = dateParts(date, timeZone);
  return `${day}, ${time}`;
}

/** e.g. "15 Sep 2026" */
export function formatDate(date: Date, timeZone: string): string {
  return dateParts(date, timeZone).date;
}

/** e.g. "1,243 ms" */
export function formatResponseTime(ms: number): string {
  return `${new Intl.NumberFormat("en-US").format(ms)} ms`;
}

/** Rough elapsed time for "Not working since … (3 days)". */
export function formatElapsed(from: Date, to: Date = new Date()): string {
  const minutes = Math.max(0, Math.floor((to.getTime() - from.getTime()) / 60_000));
  if (minutes < 1) return "just now";
  const plural = (n: number, unit: string) => `${n} ${unit}${n === 1 ? "" : "s"}`;
  if (minutes < 60) return plural(minutes, "minute");
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return plural(hours, "hour");
  return plural(Math.floor(hours / 24), "day");
}

/** Compact response time for tight spaces: "184 ms", "1.2 s", "34.1 s". */
export function formatDuration(ms: number): string {
  if (ms < 1000) return `${ms} ms`;
  return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)} s`;
}

/** Percentage with no decimals unless it is close to the edges: "100%", "99.5%", "0%". */
export function formatPercent(value: number): string {
  if (!Number.isFinite(value)) return "—";
  const rounded = Math.round(value);
  if (value > 99 && value < 100) return `${value.toFixed(1)}%`;
  if (value > 0 && value < 1) return `${value.toFixed(1)}%`;
  return `${rounded}%`;
}
