const NBSP = '\u00a0';

export function formatDurationMsHuman(ms: number | null | undefined): string {
  if (ms === null || ms === undefined || !Number.isFinite(ms)) {
    return '—';
  }

  const rounded = Math.round(ms);
  if (rounded < 0) {
    return '—';
  }
  if (rounded === 0) {
    return `0${NBSP}с`;
  }

  if (rounded < 1000) {
    return `${rounded}${NBSP}мс`;
  }

  const secFloat = rounded / 1000;
  if (secFloat < 60) {
    const hasFraction = rounded % 1000 !== 0;
    const text = hasFraction
      ? secFloat.toLocaleString('ru-RU', { minimumFractionDigits: 0, maximumFractionDigits: 1 })
      : String(Math.round(secFloat));
    return `${text}${NBSP}с`;
  }

  const totalSec = Math.floor(rounded / 1000);
  const h = Math.floor(totalSec / 3600);
  const m = Math.floor((totalSec % 3600) / 60);
  const s = totalSec % 60;

  const parts: string[] = [];
  if (h > 0) {
    parts.push(`${h}${NBSP}ч`);
  }
  if (m > 0) {
    parts.push(`${m}${NBSP}мин`);
  }
  if (s > 0 || parts.length === 0) {
    parts.push(`${s}${NBSP}с`);
  }

  return parts.join(' ');
}
