export type FormatShortNumberOptions = {
  /** Prefix positive values with "+" (e.g. +37k) */
  plus?: boolean;
  /** Fraction digits for K / M / B suffixes (default 1) */
  maximumFractionDigits?: number;
};

function trimTrailingZeros(value: string) {
  return value.replace(/\.0+$/, "").replace(/(\.[0-9]*?)0+$/, "$1");
}

function formatScaled(value: number, maximumFractionDigits: number) {
  if (Number.isInteger(value)) return String(value);
  return trimTrailingZeros(value.toFixed(maximumFractionDigits));
}

/**
 * Shortens large numbers for display: 37030 → "37k", 2500000 → "2.5M".
 * Use `plus: true` for "+37k" style labels (e.g. chart totals).
 */
export function formatShortNumber(
  value: number,
  options?: FormatShortNumberOptions,
): string {
  const { plus = false, maximumFractionDigits = 1 } = options ?? {};

  if (!Number.isFinite(value)) return "—";

  const sign =
    value < 0 ? "-" : plus && value > 0 ? "+" : "";
  const abs = Math.abs(value);

  let body: string;

  if (abs < 1000) {
    body =
      abs % 1 === 0
        ? String(Math.round(abs))
        : trimTrailingZeros(abs.toFixed(maximumFractionDigits));
  } else if (abs < 1_000_000) {
    body = `${formatScaled(abs / 1000, maximumFractionDigits)}k`;
  } else if (abs < 1_000_000_000) {
    body = `${formatScaled(abs / 1_000_000, maximumFractionDigits)}M`;
  } else {
    body = `${formatScaled(abs / 1_000_000_000, maximumFractionDigits)}B`;
  }

  return `${sign}${body}`;
}

/** @deprecated Prefer `formatShortNumber` — kept for existing imports */
export function compactFormat(value: number) {
  return formatShortNumber(value);
}

export function standardFormat(value: number) {
  return value.toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}
