const NBSP = " ";

export function formatEuros(amount: number, opts: { decimals?: boolean } = {}): string {
  const decimals = opts.decimals ?? false;
  const n = decimals ? amount.toFixed(2) : Math.round(amount).toString();
  const [intPart, decPart] = n.split(".");
  const withSep = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, NBSP);
  return decPart ? `${withSep},${decPart}${NBSP}€` : `${withSep}${NBSP}€`;
}

export function formatNumber(n: number): string {
  return n.toLocaleString("fr-FR").replace(/\s/g, NBSP);
}

export function formatPercent(n: number, opts: { sign?: boolean; decimals?: number } = {}): string {
  const decimals = opts.decimals ?? 1;
  const sign = opts.sign && n > 0 ? "+" : "";
  return `${sign}${n.toFixed(decimals).replace(".", ",")}${NBSP}%`;
}

const MONTHS_SHORT = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."];
const MONTHS_LONG = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"];

export function formatDate(d: Date | string, variant: "short" | "long" | "numeric" = "short"): string {
  const date = typeof d === "string" ? new Date(d) : d;
  const day = date.getDate();
  const month = date.getMonth();
  const year = date.getFullYear();
  if (variant === "numeric") return `${String(day).padStart(2, "0")}/${String(month + 1).padStart(2, "0")}/${year}`;
  if (variant === "long") return `${day} ${MONTHS_LONG[month]} ${year}`;
  return `${day} ${MONTHS_SHORT[month]} ${year}`;
}

export function formatMonth(d: Date | string): string {
  const date = typeof d === "string" ? new Date(d) : d;
  return `${MONTHS_LONG[date.getMonth()]} ${date.getFullYear()}`;
}
