/**
 * Divisi Metrics — Number / currency / percentage formatting utilities
 */

const numberFormatter = new Intl.NumberFormat('en-US');
const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});
const percentFormatter = new Intl.NumberFormat('en-US', {
  style: 'percent',
  minimumFractionDigits: 1,
  maximumFractionDigits: 1,
});

/**
 * Format a number with thousand separators.
 * @example formatNumber(1234567) → "1,234,567"
 */
export function formatNumber(n: number): string {
  return numberFormatter.format(n);
}

/**
 * Format a number as USD currency.
 * @example formatCurrency(1234.5) → "$1,234.50"
 */
export function formatCurrency(n: number): string {
  return currencyFormatter.format(n);
}

/**
 * Format a decimal ratio as a percentage.
 * The input is a fraction (0–1 range), not already multiplied by 100.
 * @example formatPercentage(0.456) → "45.6%"
 */
export function formatPercentage(n: number): string {
  return percentFormatter.format(n);
}

/**
 * Format a number in compact notation (K / M / B).
 * @example formatCompactNumber(1234567) → "1.2M"
 */
export function formatCompactNumber(n: number): string {
  const abs = Math.abs(n);

  if (abs >= 1_000_000_000) {
    return `${(n / 1_000_000_000).toFixed(1)}B`;
  }
  if (abs >= 1_000_000) {
    return `${(n / 1_000_000).toFixed(1)}M`;
  }
  if (abs >= 1_000) {
    return `${(n / 1_000).toFixed(1)}K`;
  }

  return n.toString();
}

/**
 * Format a number as Chilean Pesos (CLP) with compact notation.
 * Uses "M" for millions (abs >= 1,000,000), "K" for thousands (abs >= 1,000),
 * and plain integers for values below 1,000.
 * Negative values are prefixed with "-".
 *
 * @example formatCLP(4760000)  → "CLP 4.8 M"
 * @example formatCLP(120000)   → "CLP 120.0 K"
 * @example formatCLP(500)      → "CLP 500"
 * @example formatCLP(-4760000) → "-CLP 4.8 M"
 */
export function formatCLP(n: number): string {
  const abs = Math.abs(n);
  const sign = n < 0 ? '-' : '';

  if (abs >= 1_000_000) {
    return `${sign}CLP ${(abs / 1_000_000).toFixed(1)} M`;
  }
  if (abs >= 1_000) {
    return `${sign}CLP ${(abs / 1_000).toFixed(1)} K`;
  }

  return `${sign}CLP ${Math.round(abs)}`;
}
