// Display helpers. Money is stored in "cents" (hundredths of the shop currency, whatever the currency).

// The locale of the WordPress user (e.g. "fr-FR"); set once at start-up, "en" until then.
let locale = "en";

export function setLocale(next: string): void {
  try {
    new Intl.NumberFormat(next);
    locale = next;
  } catch {
    locale = "en";
  }
}

export function formatCents(cents: number, currency: string): string {
  return new Intl.NumberFormat(locale, { style: "currency", currency }).format(cents / 100);
}

export function formatPercent(percent: number | null): string {
  return percent === null || !Number.isFinite(percent) ? "n/a" : `${percent.toFixed(1)} %`;
}

// A number for a text field: "12.50", never "1,250" or "1.25e+3".
export function centsToInput(cents: number): string {
  return (cents / 100).toFixed(2);
}

// A plain decimal string (12.50).
export function centsToDecimal(cents: number): string {
  return (cents / 100).toFixed(2);
}

export type Range = [min: number, max: number];

// "$12.23" for one value, "$12.23 – $23.50" for a spread, "n/a" for none.
export function formatRange(range: Range | null, currency: string): string {
  if (!range) return "n/a";
  const [min, max] = range;
  return min === max ? formatCents(min, currency) : `${formatCents(min, currency)} – ${formatCents(max, currency)}`;
}

export function rangeOf(values: number[]): Range | null {
  return values.length === 0 ? null : [Math.min(...values), Math.max(...values)];
}

// The cost of one gram or one millilitre is a fraction of a cent: show up to 4 decimals.
export function formatUnitCost(centsPerUnit: number, currency: string): string {
  return new Intl.NumberFormat(locale, { style: "currency", currency, minimumFractionDigits: 2, maximumFractionDigits: 4 }).format(centsPerUnit / 100);
}
