/**
 * formatValue formats a numeric value according to a format string.
 *
 * Format string grammar: [width.][precision]type
 *   type  f  — fixed-point:    toFixed(precision)
 *         e  — exponential:    toExponential(precision)
 *         g  — significant:    toPrecision(precision), trailing zeros stripped
 *
 * Examples: "3f", "0.3f", "2e", "0.1e", "4g"
 * The optional leading "0." is ignored — only the digits before the type
 * letter are used as precision.
 *
 * An empty or unrecognised format falls back to the default display
 * (4 significant figures, trailing zeros stripped, exponential for very
 * large or very small values).
 */
export function formatValue(v: number | null | undefined, fmt: string): string {
  if (v === null || v === undefined || typeof v !== 'number') return '---';
  if (!Number.isFinite(v)) return String(v);

  const s = fmt.trim();
  if (s) {
    // Match optional "0." prefix then digits then type letter
    const m = s.match(/^(?:\d+\.)?(\d+)([fFeEgG])$/);
    if (m) {
      const prec = Math.max(0, parseInt(m[1], 10));
      const type = m[2].toLowerCase();
      try {
        switch (type) {
          case 'f': return v.toFixed(prec);
          case 'e': return v.toExponential(prec);
          case 'g': return v.toPrecision(Math.max(1, prec)).replace(/\.?0+$/, '');
        }
      } catch {
        // Fall through to default
      }
    }
  }

  // Default: 4 significant figures, exponential for extreme magnitudes
  const a = Math.abs(v);
  if (a !== 0 && (a >= 1e5 || a < 1e-3)) return v.toExponential(3);
  return v.toPrecision(4).replace(/\.?0+$/, '');
}
