<template>
  <div class="flex items-center gap-3 text-xs">
    <!-- Indicateur CPU -->
    <div class="flex items-center gap-1.5">
      <span class="text-[11px] text-monokai-comment">CPU</span>
      <span
        :class="[
          'font-mono font-bold text-[11px]',
          cpuColorClass
        ]"
      >
        {{ stats.cpu_percent }}%
      </span>
    </div>

    <!-- Séparateur -->
    <div class="h-6 w-px bg-monokai-comment"></div>

    <!-- Indicateur RAM Système -->
    <div class="flex items-center gap-1.5">
      <span class="text-[11px] text-monokai-comment">RAM PC</span>
      <span
        :class="[
          'font-mono font-bold text-[11px]',
          ramColorClass
        ]"
      >
        {{ stats.ram_used }} MB
      </span>
    </div>

    <!-- Séparateur -->
    <div class="h-6 w-px bg-monokai-comment"></div>

    <!-- Indicateur RAM App -->
    <div class="flex items-center gap-1.5">
      <span class="text-[11px] text-monokai-comment">RAM App</span>
      <span class="font-mono font-bold text-[11px] text-monokai-purple">
        {{ stats.process_ram_mb }} MB
      </span>
    </div>

    <!-- Tooltip détaillé au survol -->
    <div class="relative group">
      <button
        class="text-monokai-comment hover:text-monokai-cyan transition-colors text-xs"
        title="Détails système"
      >
        ⓘ
      </button>

      <!-- Tooltip -->
      <div
        class="absolute right-0 top-full mt-2 w-64 bg-monokai-bg border border-monokai-comment rounded-lg p-3 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50 shadow-lg"
      >
        <div class="text-xs space-y-2">
          <!-- CPU détaillé -->
          <div>
            <div class="text-monokai-cyan font-bold mb-1">Processeur</div>
            <div class="flex justify-between text-monokai-text">
              <span>Utilisation:</span>
              <span class="font-mono">{{ stats.cpu_percent }}%</span>
            </div>
            <div class="flex justify-between text-monokai-text">
              <span>Cœurs:</span>
              <span class="font-mono">{{ stats.cpu_count }}</span>
            </div>
          </div>

          <div class="border-t border-monokai-comment"></div>

          <!-- RAM détaillée -->
          <div>
            <div class="text-monokai-green font-bold mb-1">Mémoire</div>
            <div class="flex justify-between text-monokai-text">
              <span>Utilisée:</span>
              <span class="font-mono">{{ stats.ram_used }} MB</span>
            </div>
            <div class="flex justify-between text-monokai-text">
              <span>Disponible:</span>
              <span class="font-mono">{{ stats.ram_available }} MB</span>
            </div>
            <div class="flex justify-between text-monokai-text">
              <span>Total:</span>
              <span class="font-mono">{{ stats.ram_total }} MB</span>
            </div>
          </div>

          <div class="border-t border-monokai-comment"></div>

          <!-- Processus IPWatch -->
          <div>
            <div class="text-monokai-purple font-bold mb-1">IPWatch</div>
            <div class="flex justify-between text-monokai-text">
              <span>RAM:</span>
              <span class="font-mono">{{ stats.process_ram_mb }} MB</span>
            </div>
            <div class="flex justify-between text-monokai-text">
              <span>CPU:</span>
              <span class="font-mono">{{ formatPercent(stats.process_cpu_percent) }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Icône refresh -->
    <button
      @click="fetchStats"
      :disabled="loading"
      class="text-monokai-comment hover:text-monokai-cyan transition-colors disabled:opacity-50"
      :class="{ 'animate-spin': loading }"
      title="Rafraîchir"
    >
      ↻
    </button>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'

const stats = ref({
  cpu_percent: 0,
  cpu_count: 0,
  ram_percent: 0,
  ram_used: 0,
  ram_total: 0,
  ram_available: 0,
  process_ram_mb: 0,
  process_cpu_percent: 0
})

const loading = ref(false)
let intervalId = null

// Couleur CPU selon le pourcentage
const cpuColorClass = computed(() => {
  const percent = stats.value.cpu_percent
  if (percent >= 80) return 'text-monokai-pink'
  if (percent >= 60) return 'text-monokai-yellow'
  return 'text-monokai-cyan'
})

// Couleur RAM selon le pourcentage
const ramColorClass = computed(() => {
  const percent = stats.value.ram_percent
  if (percent >= 80) return 'text-monokai-pink'
  if (percent >= 60) return 'text-monokai-yellow'
  return 'text-monokai-green'
})

function formatPercent(value) {
  if (value === null || value === undefined || Number.isNaN(value)) return '0.0'
  return Number(value).toFixed(1)
}

async function fetchStats() {
  loading.value = true
  try {
    const response = await fetch('/api/system/stats')
    if (response.ok) {
      const data = await response.json()
      stats.value = data
    } else {
      // Erreur HTTP silencieuse - pas de log pour éviter le spam
      // Les stats précédentes restent affichées
    }
  } catch (error) {
    // Erreur réseau silencieuse (déconnexion temporaire, etc.)
    // Les stats précédentes restent affichées
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // Charger immédiatement
  fetchStats()

  // Rafraîchir toutes les 5 secondes
  intervalId = setInterval(fetchStats, 5000)
})

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId)
  }
})
</script>
