import { cn } from "@/lib/utils";

export type AdminMoneyDisplaySize = "sm" | "md" | "lg" | "xl";

const SIZE_TIERS: Record<AdminMoneyDisplaySize, readonly string[]> = {
  sm: ["text-sm", "text-xs", "text-[11px]", "text-[10px]", "text-[9px]"],
  md: ["text-base", "text-sm", "text-xs", "text-[11px]", "text-[10px]"],
  lg: ["text-lg sm:text-xl", "text-base sm:text-lg", "text-sm sm:text-base", "text-xs sm:text-sm", "text-[11px] sm:text-xs"],
  xl: ["text-2xl", "text-xl", "text-lg", "text-base sm:text-lg", "text-sm sm:text-base"],
};

function tierForLength(len: number): number {
  if (len > 20) {
    return 4;
  }
  if (len > 16) {
    return 3;
  }
  if (len > 12) {
    return 2;
  }
  if (len > 8) {
    return 1;
  }

  return 0;
}

/** 按字符长度分档缩小字号，避免卡片/栅格/表格内大额被裁切 */
export function adminMoneyDisplaySizeClass(
  value: string,
  size: AdminMoneyDisplaySize = "lg",
): string {
  const len = value.replace(/\s/g, "").length;
  const tier = tierForLength(len);
  return SIZE_TIERS[size][tier] ?? SIZE_TIERS[size][0];
}

export function adminMoneyDisplayClass(
  value: string,
  {
    size = "lg",
    emphasize = true,
    className,
  }: {
    size?: AdminMoneyDisplaySize;
    emphasize?: boolean;
    className?: string;
  } = {},
): string {
  return cn(
    "min-w-0 whitespace-normal break-words [overflow-wrap:anywhere] tabular-nums leading-tight tracking-tight",
    emphasize ? "font-semibold" : "font-medium",
    adminMoneyDisplaySizeClass(value, size),
    className,
  );
}

export function adminMoneyDisplayTitle(value: string | number | null | undefined): string | undefined {
  if (value == null) {
    return undefined;
  }
  const text = String(value).trim();
  return text === "" || text === "…" || text === "—" ? undefined : text;
}
