/**
 * Centralized currency formatting for the DoItEasy Shop.
 *
 * Primary currency is Saudi Riyal (SAR). All prices in the catalog, cart,
 * checkout, receipts and admin views are displayed using this helper so the
 * currency can be changed in one place.
 *
 * For UI rendering we prefer the React `<Price>` component in
 * `components/ui/Price.tsx`, which renders the official SVG Saudi Riyal
 * symbol followed by the numeric amount. For plain-string contexts (email
 * bodies, CSV exports, window titles, etc.) use `formatPrice` which still
 * returns a textual "SAR" prefix.
 */

/** Primary currency code used across the storefront and backend. */
export const PRIMARY_CURRENCY = "SAR" as const;

/** Human-friendly currency symbol shown before prices (textual fallback). */
export const CURRENCY_SYMBOL = "ر.س";

/**
 * Format a numeric amount as Saudi Riyal using the short "SAR " prefix
 * and two decimal places. Falls back gracefully when `amount` is invalid.
 *
 * Prefer the `<Price>` React component for UI rendering — it shows the
 * official Saudi Riyal SVG symbol instead of the "SAR" text prefix.
 *
 * @example
 *   formatPrice(199.5)    // "SAR 199.50"
 *   formatPrice(0)        // "SAR 0.00"
 */
export function formatPrice(amount: number | null | undefined): string {
  const n = typeof amount === "number" && Number.isFinite(amount) ? amount : 0;
  return `SAR ${n.toFixed(2)}`;
}

/**
 * Format a numeric amount as a raw 2-decimal number with no currency prefix
 * or symbol. Used alongside the `<SarSymbol>` / `<Price>` components.
 *
 * @example
 *   formatAmount(199.5)   // "199.50"
 */
export function formatAmount(amount: number | null | undefined): string {
  const n = typeof amount === "number" && Number.isFinite(amount) ? amount : 0;
  return n.toFixed(2);
}

/**
 * Short symbol-only variant (e.g. "ر.س 199.50"). Useful for tight UI like
 * autocomplete rows or chips where the SVG component is not available.
 */
export function formatPriceShort(amount: number | null | undefined): string {
  const n = typeof amount === "number" && Number.isFinite(amount) ? amount : 0;
  return `${CURRENCY_SYMBOL} ${n.toFixed(2)}`;
}

/**
 * Locale-aware Intl formatter. Prefer this when a browser-localized
 * rendering is desired (e.g. Arabic locale pages).
 */
export function formatSARIntl(
  amount: number | null | undefined,
  locale: string = "en-SA",
): string {
  const n = typeof amount === "number" && Number.isFinite(amount) ? amount : 0;
  try {
    return new Intl.NumberFormat(locale, {
      style: "currency",
      currency: PRIMARY_CURRENCY,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(n);
  } catch {
    return formatPrice(n);
  }
}