/** Formatage partagé entre la carte VPS et le modal de statistiques. */

/** Débit en octets/seconde → chaîne lisible. */
export function formatBps(bps) {
  if (bps === undefined || bps === null) return '—'
  if (bps < 1024)      return `${bps.toFixed(0)} B/s`
  if (bps < 1024 ** 2) return `${(bps / 1024).toFixed(1)} KB/s`
  return `${(bps / 1024 ** 2).toFixed(1)} MB/s`
}

/** Volume d'octets → chaîne lisible. */
export function formatBytes(bytes) {
  if (!bytes || bytes < 1) return '0 B'
  if (bytes < 1024)       return `${bytes.toFixed(0)} B`
  if (bytes < 1024 ** 2)  return `${(bytes / 1024).toFixed(1)} KB`
  if (bytes < 1024 ** 3)  return `${(bytes / 1024 ** 2).toFixed(1)} MB`
  return `${(bytes / 1024 ** 3).toFixed(2)} GB`
}

/** Octets de RAM → MB en dessous de 1 Go, GB au-delà. */
export function formatRam(bytes) {
  if (!bytes) return '—'
  if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(0)} MB`
  return `${(bytes / 1024 ** 3).toFixed(1)} GB`
}

/** Date → « il y a 12 s », « il y a 3 min »… */
export function formatRelative(date) {
  if (!date) return ''
  const seconds = Math.max(0, Math.round((Date.now() - date.getTime()) / 1000))
  if (seconds < 5)  return "à l'instant"
  if (seconds < 60) return `il y a ${seconds} s`
  const minutes = Math.round(seconds / 60)
  if (minutes < 60) return `il y a ${minutes} min`
  return `il y a ${Math.round(minutes / 60)} h`
}

/** Heure courte d'un timestamp ISO (axes et infobulles des graphiques). */
export function formatClock(ts, withSeconds = true) {
  if (!ts) return ''
  const d = new Date(ts)
  if (Number.isNaN(d.getTime())) return ''
  return d.toLocaleTimeString('fr-FR', {
    hour:   '2-digit',
    minute: '2-digit',
    ...(withSeconds ? { second: '2-digit' } : {}),
  })
}

/** Seuils partagés pour colorer CPU / RAM. */
export function loadColor(percent) {
  if (percent > 85) return 'text-red-400'
  if (percent > 60) return 'text-yellow-400'
  return 'text-emerald-400'
}

export function loadBarColor(percent) {
  if (percent > 85) return 'bg-red-500'
  if (percent > 60) return 'bg-yellow-500'
  return 'bg-emerald-500'
}
