<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { request } from "../api";
import { t } from "../i18n";

// /api/status probes PocketBase and the Web App server-side, so the browser
// never has to reach either directly.
const status = ref(null);
const error = ref("");
let timer = null;

async function check() {
  try {
    status.value = await request("/api/status", { auth: false });
    error.value = "";
  } catch (e) {
    status.value = null;
    error.value = e.message || t("status.unreachable");
  }
}

// Computed so the row labels re-evaluate when the language changes.
const rows = computed(() => [
  { key: "apiServer", label: t("status.apiServer"), h: status.value?.apiServer },
  { key: "pocketBase", label: t("status.pocketBase"), h: status.value?.pocketBase },
  { key: "webApp", label: t("status.webApp"), h: status.value?.webApp },
]);

onMounted(() => {
  check();
  timer = setInterval(check, 10000);
});
onUnmounted(() => clearInterval(timer));

const pillFor = (s) =>
  s === "ok" ? "bg-success-soft text-success" : "bg-danger-soft text-danger";
</script>

<template>
  <div class="dh-card overflow-hidden">
    <div class="flex items-center justify-between border-b border-subtle px-5 py-4">
      <div class="text-base font-bold tracking-[-0.02em] text-strong">{{ t("status.title") }}</div>
      <span v-if="error" class="dh-pill bg-danger-soft text-danger">
        <span class="h-1.5 w-1.5 rounded-full bg-current"></span>{{ t("status.unreachable") }}
      </span>
    </div>

    <div v-if="error" class="px-5 py-4 text-sm text-danger">{{ error }}</div>

    <table v-else-if="status" class="w-full text-left text-sm">
      <tbody>
        <tr v-for="row in rows" :key="row.key" class="border-t border-subtle first:border-t-0">
          <td class="px-5 py-3 font-medium text-strong">{{ row.label }}</td>
          <td class="data px-5 py-3 text-xs text-muted">{{ row.h.url || t("status.thisProcess") }}</td>
          <td class="data px-5 py-3 text-right text-xs text-muted">
            {{ row.h.latencyMs != null ? row.h.latencyMs + "ms" : t("common.empty") }}
          </td>
          <td class="px-5 py-3 text-right">
            <span class="dh-pill" :class="pillFor(row.h.status)">
              <span class="h-1.5 w-1.5 rounded-full bg-current"></span>{{ row.h.status }}
            </span>
          </td>
        </tr>
      </tbody>
    </table>

    <div v-else class="px-5 py-4 text-sm text-muted">{{ t("status.checking") }}</div>
  </div>
</template>
