// Display helpers. Money is stored in "cents" (hundredths of the shop currency, whatever the currency).
import { __ } from "@wordpress/i18n";

// 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", "lotcost") : `${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);
}
