import { LOCALE_UI_LABELS } from '@thebet365/shared';

export interface LocaleDisplay {
  countryCode: 'cn' | 'us' | 'my';
  currency: string;
  label: string;
}

const LOCALE_DISPLAY: Record<string, LocaleDisplay> = {
  'zh-CN': { countryCode: 'cn', currency: 'CNY', label: LOCALE_UI_LABELS['zh-CN'] },
  'en-US': { countryCode: 'us', currency: 'USD', label: LOCALE_UI_LABELS['en-US'] },
  'ms-MY': { countryCode: 'my', currency: 'MYR', label: LOCALE_UI_LABELS['ms-MY'] },
};

export function getLocaleDisplay(locale: string): LocaleDisplay {
  return LOCALE_DISPLAY[locale] ?? LOCALE_DISPLAY['en-US'];
}

export function parseAmount(amount: unknown): number {
  if (amount == null) return 0;
  if (typeof amount === 'number') return Number.isFinite(amount) ? amount : 0;
  if (typeof amount === 'string') {
    const n = Number(amount);
    return Number.isFinite(n) ? n : 0;
  }
  if (typeof amount === 'object') {
    const value = amount as { toString?: () => string; d?: number[] };
    if (typeof value.toString === 'function') {
      const n = Number(value.toString());
      if (Number.isFinite(n)) return n;
    }
    if (Array.isArray(value.d) && value.d.length) {
      const n = Number(value.d.join(''));
      return Number.isFinite(n) ? n : 0;
    }
  }
  return 0;
}

export function sumAmounts(...amounts: unknown[]): number {
  return amounts.reduce<number>((sum, item) => sum + parseAmount(item), 0);
}

export function formatMoney(amount: unknown, locale: string): string {
  const value = parseAmount(amount);
  const { currency } = getLocaleDisplay(locale);
  try {
    return new Intl.NumberFormat(locale, {
      style: 'currency',
      currency,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(value);
  } catch {
    return `${getLocaleDisplay(locale).currency} ${value.toFixed(2)}`;
  }
}

export function formatMoneyCompact(amount: unknown, locale: string): string {
  const value = parseAmount(amount);
  const abs = Math.abs(value);
  const sign = value < 0 ? '-' : '';
  const { currency } = getLocaleDisplay(locale);
  const sym = currency === 'CNY' ? '¥' : currency === 'MYR' ? 'RM' : '$';

  if (abs >= 10000 && locale === 'zh-CN') {
    const v = abs / 10000;
    return `${sign}${sym}${v % 1 === 0 ? v.toFixed(0) : v.toFixed(1)}万`;
  }
  if (abs >= 1000000) {
    const v = abs / 1000000;
    return `${sign}${sym}${v % 1 === 0 ? v.toFixed(0) : v.toFixed(1)}M`;
  }
  if (abs >= 10000) {
    const v = abs / 1000;
    return `${sign}${sym}${v % 1 === 0 ? v.toFixed(0) : v.toFixed(1)}K`;
  }

  try {
    return new Intl.NumberFormat(locale, {
      style: 'currency',
      currency,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(value);
  } catch {
    return `${sym}${value.toFixed(2)}`;
  }
}
