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

// Superadmin-only: this server's display name. Like the PocketBase and Web App
// cards, the change is applied at runtime AND persisted to the server's .env,
// so it survives a restart. There is nothing to probe here — the name is a
// label, not an address — so this card saves without a test button.
const form = ref({ name: "" });
const error = ref("");
const notice = ref("");
const busy = ref(false);

async function load() {
  try {
    const view = await request("/api/admin/server-config");
    form.value = { name: view.name };
  } catch (e) {
    error.value = e.message;
  }
}
onMounted(load);

async function save() {
  error.value = "";
  notice.value = "";
  busy.value = true;
  try {
    const out = await request("/api/admin/server-config", {
      method: "PUT",
      body: { name: form.value.name },
    });
    form.value = { name: out.config.name };
    notice.value = out.warning || t("server.savedNotice");
  } catch (e) {
    error.value = e.message;
  } finally {
    busy.value = false;
  }
}
</script>

<template>
  <div class="dh-card overflow-hidden">
    <div class="border-b border-subtle px-5 py-4">
      <div class="text-base font-bold tracking-[-0.02em] text-strong">{{ t("server.title") }}</div>
      <p class="mt-0.5 text-xs text-muted">{{ t("server.subtitle") }}</p>
    </div>

    <div class="flex flex-col gap-4 px-5 py-4">
      <div>
        <label class="dh-label" for="server-name">{{ t("server.name") }}</label>
        <input
          id="server-name"
          v-model="form.name"
          class="dh-input"
          maxlength="64"
          placeholder="DriverVault API Server"
          @keyup.enter="save"
        />
        <p class="mt-1 text-xs text-muted">{{ t("server.nameHint") }}</p>
      </div>

      <p v-if="notice" class="rounded-control bg-info-soft px-3 py-2 text-xs text-info">{{ notice }}</p>
      <p v-if="error" class="rounded-control bg-danger-soft px-3 py-2 text-xs text-danger">{{ error }}</p>

      <div class="flex items-center gap-2">
        <button class="dh-btn" :disabled="busy" @click="save">{{ t("server.saveApply") }}</button>
        <span class="flex-1"></span>
        <span class="eyebrow">{{ t("server.persistedEnv") }}</span>
      </div>
    </div>
  </div>
</template>
