<script setup lang="ts">
import { computed, watch, ref } from 'vue'
import { http } from '@/api'
import type { WatchSlot, WatchProcess } from '@/composables/useWatchPins'

const props = defineProps<{
  modelValue: boolean
  slotData: WatchSlot | null
}>()

const emit = defineEmits<{ 'update:modelValue': [v: boolean] }>()

const processes = ref<WatchProcess[]>([])
const loading = ref(false)

const open = computed({
  get: () => props.modelValue,
  set: (v) => emit('update:modelValue', v),
})

async function loadProcesses() {
  if (!props.slotData?.server_id) return
  loading.value = true
  try {
    const data = await http.get<{ processes: WatchProcess[] }>(
      `/watch/processes/${props.slotData.server_id}`,
    )
    processes.value = data.processes || props.slotData.processes || []
  } catch {
    processes.value = props.slotData.processes || []
  } finally {
    loading.value = false
  }
}

watch(
  () => [open.value, props.slotData?.server_id] as const,
  ([isOpen]) => {
    if (isOpen) loadProcesses()
  },
)
</script>

<template>
  <v-navigation-drawer
    v-model="open"
    location="right"
    temporary
    width="360"
  >
    <v-toolbar density="compact" flat>
      <v-toolbar-title class="text-subtitle-1">
        进程 Top5 · {{ slotData?.server_name }}
      </v-toolbar-title>
      <v-spacer />
      <v-btn icon="mdi-close" variant="text" @click="open = false" />
    </v-toolbar>
    <v-divider />
    <v-progress-linear v-if="loading" indeterminate />
    <v-list v-if="processes.length" density="compact">
      <v-list-item v-for="(p, i) in processes" :key="`${p.pid}-${i}`">
        <v-list-item-title class="text-body-2">{{ p.name || '—' }}</v-list-item-title>
        <v-list-item-subtitle>PID {{ p.pid ?? '—' }} · CPU {{ p.cpu_pct ?? '—' }}% · MEM {{ p.mem_pct ?? '—' }}%</v-list-item-subtitle>
      </v-list-item>
    </v-list>
    <div v-else class="pa-4 text-medium-emphasis text-caption">
      暂无进程数据（约 10 秒刷新一次）
    </div>
  </v-navigation-drawer>
</template>
