<template>
  <section class="space-y-6 p-4 md:p-8">
    <div>
      <p class="text-sm font-bold uppercase tracking-[0.2em] text-brand">ZKTeco Integration</p>
      <h2 class="mt-2 text-3xl font-black">Device command center</h2>
      <p class="mt-1 text-slate-500">F22, K40, MB Series, UFace, and iClock sync monitoring.</p>
    </div>

    <div class="grid gap-4 md:grid-cols-3">
      <MetricCard label="Devices" :value="devices.length" helper="Registered terminals" tone="live" />
      <MetricCard label="Online" :value="onlineCount" helper="Reporting now" tone="ok" />
      <MetricCard label="Models" :value="supportedModels.length" helper="Supported families" tone="live" />
    </div>

    <div class="grid gap-4 xl:grid-cols-2">
      <article v-for="device in devices" :key="device.serial" class="rounded-3xl border border-slate-200 bg-white p-6 shadow-soft">
        <div class="flex items-start justify-between gap-4">
          <div>
            <h3 class="text-xl font-black">{{ device.serial }}</h3>
            <p class="mt-1 text-sm text-slate-500">{{ device.model }} · {{ device.branch }}</p>
          </div>
          <span class="rounded-full bg-emerald-50 px-3 py-1 text-xs font-bold uppercase text-emerald-700">{{ device.status }}</span>
        </div>
        <div class="mt-5 flex flex-wrap gap-2">
          <span v-for="mode in device.modes" :key="mode" class="rounded-full bg-slate-100 px-3 py-1 text-xs font-bold">{{ mode }}</span>
        </div>
        <p class="mt-5 text-sm text-slate-500">Last sync: {{ device.last_sync_at }}</p>
        <div class="mt-5 flex flex-wrap gap-2">
          <button v-for="command in commands" :key="command" class="rounded-xl border border-slate-200 px-3 py-2 text-xs font-bold hover:bg-slate-50">{{ command }}</button>
        </div>
      </article>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import MetricCard from '../components/MetricCard.vue';
import { getJson } from '../services/api.js';

const devices = ref([]);
const commands = ref([]);
const supportedModels = ref([]);
const onlineCount = computed(() => devices.value.filter((device) => device.status === 'online').length);

onMounted(async () => {
  try {
    const data = await getJson('/devices');
    devices.value = data.devices;
    commands.value = data.commands;
    supportedModels.value = data.supported_models;
  } catch (error) {
    console.warn(error.message);
  }
});
</script>
