// Shared UI formatting helpers — tone mapping, time-ago labels (vi-VN)

type DeployTone = "success" | "danger" | "warning" | "info" | "muted";

export function deployToneFor(status: string): DeployTone {
  switch (status) {
    case "success":
    case "deployed":
      return "success";
    case "failed":
    case "error":
      return "danger";
    case "building":
    case "deploying":
      return "info";
    case "queued":
      return "warning";
    default:
      return "muted";
  }
}

const STATUS_LABEL_VI: Record<string, string> = {
  success: "thành công",
  deployed: "đã deploy",
  failed: "thất bại",
  error: "lỗi",
  building: "đang build",
  deploying: "đang deploy",
  queued: "trong hàng đợi",
  cancelled: "đã huỷ",
};

export function deployLabelFor(status: string): string {
  return STATUS_LABEL_VI[status] ?? status;
}

export function ago(date: Date | string | null | undefined): string {
  if (!date) return "—";
  const d = typeof date === "string" ? new Date(date) : date;
  const ms = Date.now() - d.getTime();
  const sec = Math.round(ms / 1000);
  if (sec < 5) return "vừa xong";
  if (sec < 60) return `${sec} giây trước`;
  const min = Math.round(sec / 60);
  if (min < 60) return `${min} phút trước`;
  const hr = Math.round(min / 60);
  if (hr < 24) return `${hr} giờ trước`;
  const day = Math.round(hr / 24);
  if (day < 7) return `${day} ngày trước`;
  const wk = Math.round(day / 7);
  if (wk < 4) return `${wk} tuần trước`;
  const mo = Math.round(day / 30);
  if (mo < 12) return `${mo} tháng trước`;
  const yr = Math.round(day / 365);
  return `${yr} năm trước`;
}

export function bytesHuman(n: number): string {
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`;
  return `${(n / 1024 / 1024 / 1024).toFixed(2)} GB`;
}
