const CURRENCY_SYMBOLS: Record<string, string> = {
  USD: '$', EUR: '\u20ac', GBP: '\u00a3', INR: '\u20b9', AED: 'AED',
  SAR: 'SAR', CAD: 'CA$', AUD: 'A$', SGD: 'S$', MYR: 'RM',
  THB: '\u0e3f', PHP: '\u20b1', IDR: 'Rp', JPY: '\u00a5', KRW: '\u20a9',
  CNY: '\u00a5', HKD: 'HK$', TWD: 'NT$', NZD: 'NZ$', ZAR: 'R',
  BRL: 'R$', MXN: 'MX$', CLP: 'CL$', COP: 'CO$', ARS: 'AR$',
  PEN: 'S/.', TRY: '\u20ba', EGP: 'E\u00a3', NGN: '\u20a6', KES: 'KSh',
  GHS: 'GH\u20b5', PKR: 'Rs', BDT: '\u09f3', LKR: 'Rs', NPR: 'Rs',
  QAR: 'QR', KWD: 'KD', BHD: 'BD', OMR: 'OMR', JOD: 'JD',
  CHF: 'CHF', SEK: 'kr', NOK: 'kr', DKK: 'kr', PLN: 'z\u0142',
  CZK: 'K\u010d', HUF: 'Ft', RON: 'lei', RUB: '\u20bd', UAH: '\u20b4',
  ILS: '\u20aa', VND: '\u20ab', MMK: 'K', KHR: '\u17db', LAK: '\u20ad',
};

const ZERO_DECIMAL = new Set(['JPY', 'KRW', 'VND', 'CLP', 'HUF', 'IDR', 'KHR', 'LAK', 'MMK']);

export function getCurrencySymbol(code: string | null | undefined): string {
  if (!code) return '$';
  return CURRENCY_SYMBOLS[code.toUpperCase()] || code;
}

export function formatCurrency(
  amount: number,
  currencyCode?: string | null,
): string {
  const code = (currencyCode || 'USD').toUpperCase();
  const symbol = getCurrencySymbol(code);
  const decimals = ZERO_DECIMAL.has(code) ? 0 : 2;
  const formatted = amount.toLocaleString(undefined, {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  });
  return `${symbol}${formatted}`;
}

export function formatCurrencyCompact(
  amount: number,
  currencyCode?: string | null,
): string {
  const code = (currencyCode || 'USD').toUpperCase();
  const symbol = getCurrencySymbol(code);
  if (amount >= 1000) {
    return `${symbol}${(amount / 1000).toFixed(1)}k`;
  }
  return `${symbol}${amount}`;
}
