// Amounts arrive from the server as decimal strings in UGX ("1234500.00"). The short forms divide only for
// display; use `money()` from the accounting package where the exact figure matters.

type Amount = string | number;

function toNumber(amount: Amount): number {
  const value = typeof amount === 'number' ? amount : Number(amount);

  return Number.isFinite(value) ? value : 0;
}

export function formatUgx(amount: Amount): string {
  return `UGX ${Math.round(toNumber(amount)).toLocaleString('en')}`;
}

export function formatUgxShort(amount: Amount): string {
  const value = toNumber(amount);

  if (Math.abs(value) >= 1_000_000_000) {
    return `UGX ${(value / 1_000_000_000).toFixed(2)} bn`;
  }

  if (Math.abs(value) >= 1_000_000) {
    return `UGX ${(value / 1_000_000).toFixed(1)}M`;
  }

  return formatUgx(value);
}

/** Whole units such as shares or accounts, with thousands separators. */
export function formatCount(value: Amount): string {
  return Math.round(toNumber(value)).toLocaleString('en');
}

/** A calendar date from the server ("2026-11-09") as a short label such as "9 Nov", read without a time zone shift. */
export function formatDay(date: string): string {
  return new Date(`${date}T00:00:00Z`).toLocaleDateString('en-GB', {
    day: 'numeric',
    month: 'short',
    timeZone: 'UTC',
  });
}
