<template>
  <section class="px-6 py-20 md:px-12 max-w-7xl mx-auto">
    <div class="mb-10">
      <h2 class="text-3xl md:text-4xl font-bold text-center mb-14">
        Статус серверов
      </h2>
      <div class="flex justify-center mt-6">
        <button
          @click="refreshData"
          :disabled="loading"
          class="px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-sm font-medium transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer"
        >
          <RefreshCw :size="16" :class="{ 'animate-spin': loading }" />
          {{ loading ? 'Обновление...' : 'Обновить пинг' }}
        </button>
      </div>
    </div>

    <div v-if="loading && !hosts.length" class="flex justify-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
    </div>

    <p v-else-if="error" class="text-center text-red-500 py-12">{{ error }}</p>

    <div v-else class="space-y-2 max-w-3xl mx-auto">
      <div
        v-for="host in sortedHosts"
        :key="host.address + host.port"
        class="flex items-center justify-between bg-white dark:bg-gray-900 rounded-xl px-4 py-2.5 border"
        :class="host.isOnline ? 'border-green-500/30' : 'border-red-500/30 opacity-60'"
      >
        <div class="flex items-center gap-3">
          <img
            v-if="host.countryCode"
            :src="`https://cdn.jsdelivr.net/npm/flag-icons@7.2.3/flags/4x3/${host.countryCode.toLowerCase()}.svg`"
            class="h-5 w-auto rounded-sm"
            :alt="host.name"
            @error="handleFlagError"
          />
          <div v-else class="h-5 w-7 rounded-sm bg-gray-200 dark:bg-gray-700 flex items-center justify-center text-xs">
            🌐
          </div>
          <span class="font-semibold text-gray-800 dark:text-white">{{ host.name }}</span>
          
          <span class="relative flex h-2 w-2">
            <span
              class="animate-ping absolute inline-flex h-full w-full rounded-full opacity-75"
              :class="host.isOnline ? 'bg-green-500' : 'bg-red-500'"
            ></span>
            <span
              class="relative inline-flex rounded-full h-2 w-2"
              :class="host.isOnline ? 'bg-green-600' : 'bg-red-600'"
            ></span>
          </span>
        </div>

        <div class="flex items-center gap-3">
          <span
            v-if="host.ping !== undefined && host.ping !== null && host.ping !== 0"
            class="font-mono font-semibold flex items-center gap-1.5"
            :class="{
              'text-green-600': host.ping < 200,
              'text-yellow-600': host.ping >= 200 && host.ping < 500,
              'text-red-600': host.ping >= 500,
            }"
          >
            <Wifi :size="14" />
            {{ host.ping }} ms
          </span>
          <span v-else class="text-gray-400 font-mono text-sm">⏳</span>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Wifi, RefreshCw } from '@lucide/vue'

const hosts = ref([])
const loading = ref(true)
const error = ref(null)

const sortedHosts = computed(() => {
  return [...hosts.value].sort((a, b) => {
    if (a.ping === null && b.ping === null) return 0
    if (a.ping === null) return 1
    if (b.ping === null) return -1
    return a.ping - b.ping
  })
})

const handleFlagError = (e) => {
  e.target.style.display = 'none'
}

const pingHost = async (host) => {
  const url = `https://${host.address}:${host.port}`
  const start = performance.now()

  try {
    await fetch(url, {
      method: 'HEAD',
      mode: 'no-cors',
      cache: 'no-cache',
      signal: AbortSignal.timeout(5000),
    })
    return Math.round(performance.now() - start)
  } catch {
    return Math.round(performance.now() - start)
  }
}

const loadData = async () => {
  try {
    const res = await fetch('/api/v1/hosts')
    if (!res.ok) throw new Error(`HTTP ${res.status}`)
    const data = await res.json()
    
    return data.map((h) => ({
      ...h,
      countryCode: h.country_code ? h.country_code.toLowerCase() : null,
      isOnline: true,
      ping: null
    }))
  } catch (err) {
    throw new Error('Ошибка загрузки данных')
  }
}

const refreshData = async () => {
  loading.value = true
  error.value = null
  
  try {
    const data = await loadData()
    hosts.value = data
    
    // Пингуем все хосты
    const pings = await Promise.all(hosts.value.map(h => pingHost(h)))
    hosts.value.forEach((h, i) => {
      h.ping = pings[i]
    })
  } catch (err) {
    error.value = err.message
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  refreshData()
})
</script>