import { numberValue } from "./number.js";

export function formatMoney(value) {
  const amount = moneyMajor(value);
  if (Math.abs(amount) >= 1_000_000) {
    return `$${(amount / 1_000_000).toFixed(2)}M`;
  }
  if (Math.abs(amount) >= 10_000) {
    return `$${Math.round(amount).toLocaleString("en-US")}`;
  }
  return `$${amount.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: amount < 10 ? 2 : 0 })}`;
}

export function formatMoneyFull(value) {
  return formatSignedDollar(Math.round(moneyMajor(value)));
}

export function formatWholeMoney(value) {
  return formatSignedDollar(numberValue(value));
}

export function formatCoin(value) {
  return numberValue(value).toLocaleString("en-US");
}

export function formatNumber(value) {
  return numberValue(value).toLocaleString("en-US");
}

export function formatPercent(value) {
  return `${(numberValue(value) * 100).toFixed(2)}%`;
}

export function formatCompactPercent(value) {
  return `${(numberValue(value) * 100).toFixed(1)}%`;
}

export function compactMoneyAxis(value) {
  if (Math.abs(value) >= 1_000_000) {
    return `${(value / 1_000_000).toFixed(1)}M`;
  }
  if (Math.abs(value) >= 1_000) {
    return `${Math.round(value / 1_000)}K`;
  }
  return value;
}

export function moneyMajor(value) {
  return numberValue(value) / 100;
}

function formatSignedDollar(value) {
  const amount = Number(value) || 0;
  const sign = amount < 0 ? "-" : "";
  return `${sign}$${Math.abs(amount).toLocaleString("en-US")}`;
}
