/**
 * Safe formatting utilities — null/undefined/NaN-proof.
 * Every view that displays API data should use these instead of
 * raw .toFixed(), .toLocaleString(), or new Date().toLocaleString().
 */

/** Format a number to fixed decimal places, safely. */
export function safeFixed(value: number | null | undefined, decimals: number = 2, fallback: string = '0'): string {
  if (value == null || isNaN(value)) return fallback
  return value.toFixed(decimals)
}

/** Format a number with locale grouping (e.g. 1,234), safely. */
export function safeLocaleString(value: number | null | undefined, fallback: string = '0'): string {
  if (value == null || isNaN(value)) return fallback
  return value.toLocaleString()
}

/** Format a number as USD currency, safely. */
export function safeCurrency(value: number | null | undefined, symbol: string = '$', fallback: string = '$0.00'): string {
  if (value == null || isNaN(value)) return fallback
  return `${symbol}${value.toFixed(2)}`
}

/** Format a byte count as human-readable size, safely. */
export function safeFileSize(bytes: number | null | undefined, fallback: string = '0 KB'): string {
  if (bytes == null || isNaN(bytes) || bytes === 0) return fallback
  const units = ['B', 'KB', 'MB', 'GB']
  let i = 0
  let size = bytes
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024
    i++
  }
  return `${size.toFixed(i === 0 ? 0 : 1)} ${units[i]}`
}

/** Format an ISO date string as locale string, safely. */
export function safeDate(isoString: string | null | undefined, fallback: string = '\u2014'): string {
  if (!isoString) return fallback
  const date = new Date(isoString)
  if (isNaN(date.getTime())) return fallback
  return date.toLocaleString()
}
