/**
 * Shared currency formatting for the reports surfaces. Three duplicated
 * `formatMoney` helpers used to live in sales-report-client,
 * sales-detail-tables, sales-deal-heat, sales-rep-leaderboard, and a
 * fourth shape buried inside the operational report — all variations of
 * the same Intl.NumberFormat call. Consolidated here so a single change
 * (e.g. switching to compact / showing decimals for tiny values)
 * propagates everywhere.
 *
 * Locked decisions (2026-05-27 currency-formatting sweep):
 *   - Use `style: 'currency'` with the row's / report's currency code so
 *     the locale's native glyph appears (€, $, £, zł). Falls back to
 *     `<rounded number> <code>` when the runtime doesn't know the code.
 *   - `maximumFractionDigits: 0` — marina deals are six figures+, the
 *     decimals add noise.
 *   - `undefined` locale → browser / Node default (en-US in CI; user's
 *     locale on the client). The Intl behaviour matches what every
 *     other money render site in the app already does.
 */

export function formatMoney(amount: number, currency: string): string {
  const safeCurrency = (currency || 'USD').toUpperCase();
  try {
    return new Intl.NumberFormat(undefined, {
      style: 'currency',
      currency: safeCurrency,
      maximumFractionDigits: 0,
    }).format(amount);
  } catch {
    return `${Math.round(amount).toLocaleString()} ${safeCurrency}`;
  }
}

/**
 * Compact form for KPI tiles when space is tight — `€1.2M` instead of
 * `€1,234,567`. Only fires above the threshold so small portfolios still
 * read literal.
 */
export function formatMoneyCompact(amount: number, currency: string): string {
  const safeCurrency = (currency || 'USD').toUpperCase();
  if (Math.abs(amount) < 100_000) return formatMoney(amount, safeCurrency);
  try {
    return new Intl.NumberFormat(undefined, {
      style: 'currency',
      currency: safeCurrency,
      notation: 'compact',
      maximumFractionDigits: 1,
    }).format(amount);
  } catch {
    return formatMoney(amount, safeCurrency);
  }
}

/**
 * Plain-number formatter with thousand separators. Use for amount
 * columns where the currency is shown in an adjacent column (the
 * custom builder's "Deposit expected" + "Currency" pair, for instance) —
 * keeping the value parseable as a number for spreadsheet analysis while
 * still being readable on screen.
 */
export function formatNumber(amount: number): string {
  try {
    return new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(amount);
  } catch {
    return Math.round(amount).toLocaleString();
  }
}
