/** API 统一用百分比（0–100）；后台表单统一用百分比（0–100）展示与录入。 */

const RATIO_TO_PERCENT = 100;

/** 表单展示：去掉无意义的尾随 0（20.00 → "20"，0.50 → "0.5"） */
function formatPercentNumber(value: number, decimals = 2): string {
  const scaled = Math.round(value * 10 ** decimals) / 10 ** decimals;
  return String(scaled);
}

/** API 已是 0–100 的占成等，直接格式化 */
export function percentValueToUi(
  percent: number | string | null | undefined,
  decimals = 2,
): string {
  const n = typeof percent === "string" ? Number.parseFloat(percent) : percent;
  if (n == null || !Number.isFinite(n)) {
    return "0";
  }
  return formatPercentNumber(n, decimals);
}

/** @deprecated API 已统一为百分比，不再需要此转换 */
export function ratioToPercentUi(
  ratio: number | string | null | undefined,
  decimals = 2,
): string {
  const n = typeof ratio === "string" ? Number.parseFloat(ratio) : ratio;
  if (n == null || !Number.isFinite(n)) {
    return "0";
  }
  return formatPercentNumber(n * RATIO_TO_PERCENT, decimals);
}

/** @deprecated API 已统一为百分比，不再需要此转换 */
export function percentUiToRatio(percent: number | string | null | undefined): number {
  const n = typeof percent === "string" ? Number.parseFloat(percent.trim()) : percent;
  if (n == null || !Number.isFinite(n)) {
    return 0;
  }
  return n / RATIO_TO_PERCENT;
}

export function parsePercentUi(value: string): number | null {
  const trimmed = value.trim();
  if (trimmed === "") {
    return null;
  }
  const n = Number.parseFloat(trimmed);
  return Number.isFinite(n) ? n : null;
}

/** 只读展示：0.005 → "0.50%" */
export function formatRatioAsPercent(
  ratio: number | null | undefined,
  decimals = 2,
): string {
  return `${ratioToPercentUi(ratio, decimals)}%`;
}
