export const CURRENCY = "MAD";

const NF_LOCALE: Record<string, string> = { fr: "fr-FR", en: "en-MA", ar: "ar-MA" };

export function formatPrice(cents: number, locale = "fr") {
  const amount = cents / 100;
  const formatter = new Intl.NumberFormat(NF_LOCALE[locale] ?? "fr-MA", {
    maximumFractionDigits: Number.isInteger(amount) ? 0 : 2,
    minimumFractionDigits: 0,
  });
  return `${formatter.format(amount)} DH`;
}

/** Parses a "1 250" / "1250,50" / "1250.50" DH input into centimes. */
export function parsePriceInput(value: string | number): number | null {
  if (typeof value === "number") {
    return Number.isFinite(value) && value >= 0 ? Math.round(value * 100) : null;
  }
  const normalized = value.replace(/[^\d.,-]/g, "").replace(",", ".");
  if (!normalized) return null;
  const amount = Number.parseFloat(normalized);
  if (!Number.isFinite(amount) || amount < 0) return null;
  return Math.round(amount * 100);
}

export function discountPercent(price: number, compareAt?: number | null) {
  if (!compareAt || compareAt <= price) return 0;
  return Math.round(((compareAt - price) / compareAt) * 100);
}

export function centsToInput(cents: number) {
  return (cents / 100).toString();
}