import { getAdminLocale } from '../i18n';
import type { AdminLocale } from '../i18n/admin-messages';

function resolveLocale(locale?: AdminLocale): AdminLocale {
  return locale ?? getAdminLocale();
}

function localeTag(locale: AdminLocale): string {
  return locale;
}

/** 完整数字（悬停提示、详情对照） */
export function formatAmountFull(
  value: string | number | null | undefined,
  locale?: AdminLocale,
): string {
  const n = Number(value);
  if (!Number.isFinite(n)) return '—';
  return n.toLocaleString(localeTag(resolveLocale(locale)), { maximumFractionDigits: 4 });
}

function unitPart(abs: number, divisor: number, maxDecimals: number, locale: AdminLocale): string {
  return (abs / divisor).toLocaleString(localeTag(locale), {
    minimumFractionDigits: 0,
    maximumFractionDigits: maxDecimals,
  });
}

/**
 * 金额展示：中文用万/亿；英文用 K/M/B
 */
export function formatAmount(
  value: string | number | null | undefined,
  maxDecimals = 2,
  locale?: AdminLocale,
): string {
  const n = Number(value);
  if (!Number.isFinite(n)) return '—';

  const loc = resolveLocale(locale);
  const sign = n < 0 ? '-' : '';
  const abs = Math.abs(n);
  const zh = loc.startsWith('zh');

  if (zh) {
    if (abs >= 1e8) return `${sign}${unitPart(abs, 1e8, maxDecimals, loc)}亿`;
    if (abs >= 1e4) return `${sign}${unitPart(abs, 1e4, maxDecimals, loc)}万`;
  } else {
    if (abs >= 1e9) return `${sign}${unitPart(abs, 1e9, maxDecimals, loc)}B`;
    if (abs >= 1e6) return `${sign}${unitPart(abs, 1e6, maxDecimals, loc)}M`;
    if (abs >= 1e3) return `${sign}${unitPart(abs, 1e3, maxDecimals, loc)}K`;
  }

  return n.toLocaleString(localeTag(loc), {
    minimumFractionDigits: 0,
    maximumFractionDigits: maxDecimals,
  });
}

export function shouldCompactAmount(value: string | number | null | undefined): boolean {
  return Math.abs(Number(value) || 0) >= 1e4;
}
