const DATE_FMT: Intl.DateTimeFormatOptions = {
  month: "short",
  day: "numeric",
  hour: "2-digit",
  minute: "2-digit",
  hour12: false,
  timeZone: "UTC",
};

const TIME_FMT: Intl.DateTimeFormatOptions = {
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
  hour12: false,
  timeZone: "UTC",
};

export function formatTimestamp(value: string | null | undefined): string {
  if (!value) return "n/a";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "n/a";
  return date.toLocaleDateString("en-US", DATE_FMT) + " UTC";
}

export function formatShortTime(value: string | null | undefined): string {
  if (!value) return "n/a";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "n/a";
  return date.toLocaleTimeString("en-US", TIME_FMT) + " UTC";
}

export function formatChartTick(value: string): string {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  const month = String(date.getUTCMonth() + 1).padStart(2, "0");
  const day = String(date.getUTCDate()).padStart(2, "0");
  const hour = String(date.getUTCHours()).padStart(2, "0");
  return `${month}-${day} ${hour}:00`;
}

export function formatNumber(value: number | null | undefined): string {
  return formatMetricValue(value);
}

const COMPACT_TS_FMT: Intl.DateTimeFormatOptions = {
  month: "short",
  day: "numeric",
  hour: "2-digit",
  minute: "2-digit",
  hour12: false,
  timeZone: "UTC",
};

export function formatCompactTs(value: string | null | undefined): string {
  if (!value) return "n/a";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "n/a";
  return date.toLocaleDateString("en-US", COMPACT_TS_FMT);
}

export function formatDelta(value: number | null | undefined): string {
  if (value == null) return "—";
  const sign = value >= 0 ? "+" : "";
  return `${sign}${formatMetricValue(value)}`;
}

export function formatDuration(ms: number | null | undefined): string {
  if (ms == null) return "—";
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}

export function formatMetricValue(
  value: number | null | undefined,
  context?: string | null,
): string {
  if (value == null) return "—";
  const normalized = (context ?? "").toLowerCase();
  const isFunding =
    normalized.includes("funding") && !normalized.includes("zscore") && !normalized.includes(" z");
  if (isFunding) {
    const bps = value * 10_000;
    return `${bps.toFixed(Math.abs(bps) < 1 ? 2 : 1)} bps`;
  }
  const isPercent =
    normalized.endsWith("_pct") ||
    normalized.includes(" pct") ||
    normalized.includes("%") ||
    normalized.includes("percentile");
  if (isPercent) {
    return `${(value * 100).toFixed(2)}%`;
  }
  if (Math.abs(value) >= 1000) {
    return new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(value);
  }
  if (Math.abs(value) > 0 && Math.abs(value) < 0.01) {
    return value.toFixed(6);
  }
  return value.toFixed(2);
}
