<template>
  <header class="bg-monokai-bg border-b-2 border-monokai-comment p-4 no-select">
    <div class="flex items-center justify-between">
      <!-- Logo et titre -->
      <div class="flex items-center gap-4">
        <img :src="logoUrl" alt="IPWatch" class="w-10 h-10" />
        <h1 class="text-3xl font-bold text-monokai-green">IPWatch</h1>
        <div class="flex flex-col">
          <span class="text-monokai-comment">Scanner Réseau</span>
          <span class="text-xs text-monokai-comment/60">v{{ appVersion }}</span>
        </div>
      </div>

      <!-- Stats et contrôles -->
      <div class="flex items-center gap-6">
        <!-- Stats système (RAM/CPU) -->
        <SystemStats />

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

        <!-- Statistiques -->
        <div class="flex gap-4 text-xs">
          <div class="flex items-center gap-2">
            <span class="text-monokai-comment">Total:</span>
            <span class="text-monokai-text font-bold">{{ stats.total }}</span>
          </div>
          <div class="flex items-center gap-2">
            <span class="w-3 h-3 rounded-full bg-monokai-green"></span>
            <span class="text-monokai-text">{{ stats.online }}</span>
          </div>
          <div class="flex items-center gap-2">
            <span class="w-3 h-3 rounded-full bg-monokai-pink opacity-50"></span>
            <span class="text-monokai-text">{{ stats.offline }}</span>
          </div>
        </div>

        <!-- Dernier scan -->
        <div v-if="lastScanDate" class="text-xs text-monokai-comment">
          Dernier scan: {{ formatScanDate(lastScanDate) }}
        </div>

        <!-- Progression du scan -->
        <div v-if="isScanning" class="flex items-center gap-2 text-xs">
          <span class="text-monokai-cyan">
            {{ scanProgress.current }} / {{ scanProgress.total }}
          </span>
          <span v-if="scanProgress.currentIP" class="text-monokai-comment">
            ({{ scanProgress.currentIP }})
          </span>
        </div>

        <!-- Bouton scan -->
        <button
          @click="triggerScan"
          :disabled="isScanning"
          class="px-3 py-1.5 rounded bg-monokai-cyan text-monokai-bg text-xs font-bold hover:bg-monokai-green transition-colors disabled:opacity-50"
          title="Lancer un scan réseau"
        >
          {{ isScanning ? 'Scan en cours...' : 'Lancer Scan' }}
        </button>

        <!-- Bouton Suivi -->
        <button
          @click="goToTracking"
          class="px-3 py-1.5 rounded bg-monokai-yellow text-monokai-bg text-sm font-bold hover:bg-monokai-orange transition-colors"
          title="Ouvrir la page des équipements suivis"
        >
          <span class="mdi mdi-star"></span> Suivi
        </button>

        <!-- Bouton Ports & Services -->
        <button
          @click="goToServices"
          class="px-3 py-1.5 rounded bg-monokai-cyan/80 text-monokai-bg text-sm font-bold hover:bg-monokai-cyan transition-colors"
          title="Scanner les services réseau"
        >
          <span class="mdi mdi-lan-check"></span> Ports & Services
        </button>

        <!-- Bouton Architecture -->
        <button
          @click="goToArchitecture"
          class="px-3 py-1.5 rounded bg-monokai-green text-monokai-bg text-sm font-bold hover:bg-monokai-cyan transition-colors"
          title="Ouvrir la page architecture réseau"
        >
          🧭 Architecture
        </button>

        <!-- Bouton Test -->
        <button
          @click="goToTest"
          class="px-3 py-1.5 rounded bg-monokai-orange text-monokai-bg text-sm font-bold hover:bg-monokai-yellow transition-colors"
          title="Ouvrir la page de tests réseau"
        >
          🧪 Test
        </button>

        <!-- Bouton Paramètres -->
        <button
          @click="openSettings"
          class="px-3 py-1.5 rounded bg-monokai-purple text-monokai-bg text-sm hover:bg-monokai-pink transition-colors"
          title="Ouvrir les paramètres"
        >
          ⚙ Paramètres
        </button>

        <!-- Indicateur WebSocket -->
        <div class="flex items-center gap-2">
          <div
            :class="[
              'w-2 h-2 rounded-full',
              wsConnected ? 'bg-monokai-green' : 'bg-monokai-pink'
            ]"
          ></div>
          <span class="text-sm text-monokai-comment">
            {{ wsConnected ? 'Connecté' : 'Déconnecté' }}
          </span>
        </div>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { useIPStore } from '@/stores/ipStore'
import SystemStats from './SystemStats.vue'
import logoUrl from '@/assets/ipwatch-logo.png'

const emit = defineEmits(['openSettings'])
const router = useRouter()

const ipStore = useIPStore()
const { stats, loading, wsConnected, lastScanDate, scanProgress, isScanning } = storeToRefs(ipStore)
const appVersion = ref('')

onMounted(async () => {
  // Charger la version depuis le config
  try {
    const response = await fetch('/api/ips/config/options')
    if (response.ok) {
      const config = await response.json()
      appVersion.value = config.version || '1.0.0'
    }
  } catch (error) {
    console.error('Erreur chargement version:', error)
    appVersion.value = '1.0.0'
  }
})

async function triggerScan() {
  try {
    await ipStore.startScan()
  } catch (err) {
    console.error('Erreur lancement scan:', err)
  }
}

function openSettings() {
  emit('openSettings')
}

function goToTracking() {
  router.push('/tracking')
}

function goToServices() {
  router.push('/services')
}

function goToArchitecture() {
  router.push('/architecture')
}

function goToTest() {
  router.push('/test')
}

function formatScanDate(date) {
  if (!date) return ''
  const d = new Date(date)
  const now = new Date()
  const diff = now - d

  if (diff < 60000) return 'il y a quelques secondes'
  if (diff < 3600000) return `il y a ${Math.floor(diff / 60000)} min`
  if (diff < 86400000) return `il y a ${Math.floor(diff / 3600000)}h`

  return d.toLocaleString('fr-FR', {
    day: '2-digit',
    month: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>
