export function formatMoney(amount: number): string {
  return '$' + (Math.round((amount + Number.EPSILON) * 100) / 100).toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

export function round2(n: number): number {
  return Math.round((n + Number.EPSILON) * 100) / 100;
}

export function calcOrderTotals(order: {
  items: Array<{ kind: string; qty: number; unitPrice: number }>;
  discount: number;
  taxRate: number;
}): {
  parts: number;
  labor: number;
  custom: number;
  subtotal: number;
  discount: number;
  tax: number;
  total: number;
} {
  const parts = order.items
    .filter((i) => i.kind === 'part')
    .reduce((s, i) => s + i.qty * i.unitPrice, 0);
  const labor = order.items
    .filter((i) => i.kind === 'labor')
    .reduce((s, i) => s + i.qty * i.unitPrice, 0);
  const custom = order.items
    .filter((i) => i.kind === 'custom')
    .reduce((s, i) => s + i.qty * i.unitPrice, 0);
  const subtotal = parts + labor + custom;
  const discount = order.discount || 0;
  const taxable = Math.max(0, subtotal - discount);
  const tax = taxable * (order.taxRate ?? 0.0875);
  const total = taxable + tax;
  return {
    parts: round2(parts),
    labor: round2(labor),
    custom: round2(custom),
    subtotal: round2(subtotal),
    discount: round2(discount),
    tax: round2(tax),
    total: round2(total),
  };
}
