import { SEND_FREQ_TABLE, SAMPLE_FREQ_TABLE, AMP_RATIO_TABLE, SOURCE_MODE_TABLE } from '../protocol/constants';

export function formatUV(uv: number): string {
  const abs = Math.abs(uv);
  if (abs >= 1e6) return `${(uv / 1e6).toFixed(2)} V`;
  if (abs >= 1e3) return `${(uv / 1e3).toFixed(2)} mV`;
  if (abs >= 1) return `${uv.toFixed(2)} μV`;
  if (abs >= 1e-3) return `${(uv * 1e3).toFixed(2)} nV`;
  return `${uv.toExponential(2)} μV`;
}

export function formatCoord(deg: number, isLon: boolean): string {
  if (!isFinite(deg)) return '--';
  const dir = isLon ? (deg >= 0 ? 'E' : 'W') : deg >= 0 ? 'N' : 'S';
  return `${Math.abs(deg).toFixed(6)}°${dir}`;
}

export function formatUtc(utcSec: number): string {
  if (!utcSec) return '--';
  const d = new Date(utcSec * 1000);
  const p = (n: number) => String(n).padStart(2, '0');
  return `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())} ${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())}`;
}

export function formatBattery(raw: number): string {
  // raw ADC → voltage conversion depends on hardware; placeholder
  const v = (raw / 4096) * 3.3 * 10; // rough estimate
  return `${v.toFixed(1)} V`;
}

export function formatTemperature(raw: number): string {
  // placeholder conversion
  const c = raw / 10;
  return `${c.toFixed(1)} °C`;
}

export function sendFreqLabel(code: number): string {
  return SEND_FREQ_TABLE.find((t) => t.code === code)?.label ?? `0x${code.toString(16)}`;
}

export function sampleFreqLabel(code: number): string {
  return SAMPLE_FREQ_TABLE.find((t) => t.code === code)?.label ?? `0x${code.toString(16)}`;
}

export function ampRatioLabel(code: number): string {
  return AMP_RATIO_TABLE.find((t) => t.code === code)?.label ?? `0x${code.toString(16)}`;
}

export function sourceModeLabel(code: number): string {
  return SOURCE_MODE_TABLE.find((t) => t.code === code)?.label ?? `0x${code.toString(16)}`;
}
