import { useParams } from 'react-router';

// The left panel picks a scope and the right panel renders it, and neither tells the other: the scope is
// `/system-monitor/:scope`. It used to be a `monitor:scope` panel channel, which meant the URL said
// `/system-monitor` however deep you were — nothing to link, nothing to bookmark, and the list came back
// on whatever you last clicked in some other tab.
export type MonitorScope = 'btop' | 'pm2' | 'docker';

export const SCOPES: { id: MonitorScope; label: string }[] = [
  { id: 'btop', label: 'bTop' },
  { id: 'pm2', label: 'pm2 processes' },
  { id: 'docker', label: 'dockers' },
];

/** Where /system-monitor lands, and where an unrecognised scope redirects to. */
export const DEFAULT_MONITOR_SCOPE: MonitorScope = 'btop';

export const isMonitorScope = (value: string | undefined): value is MonitorScope => SCOPES.some((s) => s.id === value);

export const monitorScopePath = (scope: MonitorScope) => `/system-monitor/${scope}`;

// SystemMonitorScreen redirects anything unrecognised, so the fallback here only covers the instant before
// that lands.
export const useMonitorScope = (): MonitorScope => {
  const { scope } = useParams();
  return isMonitorScope(scope) ? scope : DEFAULT_MONITOR_SCOPE;
};

export function fmtBytes(n: number): string {
  if (!n) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.min(units.length - 1, Math.floor(Math.log(n) / Math.log(1024)));
  return `${(n / 1024 ** i).toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
}

export function fmtDuration(ms: number): string {
  if (!ms || ms < 0) return '—';
  const s = Math.floor(ms / 1000);
  const d = Math.floor(s / 86400);
  const h = Math.floor((s % 86400) / 3600);
  const m = Math.floor((s % 3600) / 60);
  return [d && `${d}d`, (d || h) && `${h}h`, `${m}m`].filter(Boolean).join(' ') || `${s}s`;
}
