Newer
Older
gnexus-book / ui / src / main.js
import { computed, createApp, onMounted, reactive, ref, watch } from "vue";
import { marked } from "marked";
import DOMPurify from "dompurify";
import "gnexus-ui-kit/dist/css/kit.css";
import "gnexus-ui-kit/dist/assets/fonts/phosphor-icons/src/css/icons.css";
import {
  GnAlert,
  GnBadge,
  GnButton,
  GnCard,
  GnChip,
  GnConfirmDialog,
  GnDescriptionList,
  GnDrawer,
  GnEmptyState,
  GnInput,
  GnMetricCard,
  GnModal,
  GnPageHeader,
  GnSearchField,
  GnTable,
  GnTabs,
  GnTextarea,
  GnToastProvider,
  GnToolbar,
  GnUserCard,
  useToast
} from "gnexus-ui-kit/vue";
import {
  locale,
  localeOptions,
  savedLocale,
  setLocale,
  t
} from "./i18n/index.js";
import "./styles.css";

const encodePath = path =>
  String(path || "")
    .split("/")
    .map(encodeURIComponent)
    .join("/");

const pretty = value =>
  typeof value === "string" ? value : JSON.stringify(value ?? null, null, 2);

const defaultDocTemplate = () => {
  const today = new Date().toISOString().slice(0, 10);
  return `---\nowner: gmikcon\nstatus: draft\nlast_reviewed: ${today}\nreview_interval: 30d\nconfidence: medium\nsource_of_truth: manual\n---\n\n# New document\n\n`;
};

marked.setOptions({ gfm: true, breaks: false });

const renderMarkdown = value =>
  DOMPurify.sanitize(marked.parse(String(value || "")));

const readableKey = key =>
  String(key)
    .replace(/[_-]+/g, " ")
    .replace(/\b\w/g, char => char.toUpperCase());

const displayValue = value => {
  if (value === null || value === undefined || value === "") return "—";
  if (Array.isArray(value)) return value.map(displayValue).join(", ");
  if (typeof value === "object") return JSON.stringify(value, null, 2);
  if (typeof value === "boolean") return value ? "true" : "false";
  return String(value);
};

const IssueList = {
  components: { GnBadge },
  props: {
    issues: { type: Array, default: () => [] }
  },
  setup() {
    return { t };
  },
  template: `
    <div class="gnb-issues">
      <p v-if="!issues.length" class="gnb-muted">{{ t('status.noIssues') }}</p>
      <div v-for="issue in issues" :key="issue.path + issue.code + issue.message" class="gnb-issue">
        <GnBadge :variant="issue.severity === 'error' ? 'danger' : 'warning'">{{ issue.severity || 'warning' }}</GnBadge>
        <div class="gnb-issue-copy">
          <div class="gnb-issue-path">
            <code>{{ issue.path }}</code>
            <span>{{ issue.code }}</span>
          </div>
          <p>{{ issue.message }}</p>
        </div>
      </div>
    </div>
  `
};

const AppScreen = {
  components: {
    GnAlert,
    GnBadge,
    GnButton,
    GnCard,
    GnChip,
    GnConfirmDialog,
    GnDescriptionList,
    GnDrawer,
    GnEmptyState,
    GnInput,
    GnMetricCard,
    GnModal,
    GnPageHeader,
    GnSearchField,
    GnTable,
    GnTabs,
    GnTextarea,
    GnToolbar,
    GnUserCard,
    IssueList
  },
  setup() {
    const toast = useToast();

    const booting = ref(true);
    const authEnabled = ref(false);
    const user = ref(null);
    const localeOverride = ref(null);
    const storage = ref("unknown");
    const healthStatus = ref("unknown");
    const pageError = ref("");
    const activePage = ref("docs");
    const drawerOpen = ref(false);

    const docs = ref([]);
    const docQuery = ref("");
    const searchResults = ref([]);
    const searching = ref(false);
    const selectedDocPath = ref("");
    const selectedDoc = ref(null);
    const docLoading = ref(false);
    const docError = ref("");
    const docHistory = ref([]);
    const historyError = ref("");
    const docDiff = ref("");
    const diffError = ref("");
    const proposal = reactive({
      target: "10-systems/example.md",
      summary: "",
      reason: "",
      content: defaultDocTemplate()
    });
    const proposalRunning = ref(false);
    const proposalOpen = ref(false);
    const historyOpen = ref(false);
    const mobileDocView = ref("list");

    const inventoryTypes = ref([]);
    const inventoryType = ref("");
    const inventoryRecords = ref([]);
    const inventoryFilter = ref("");
    const selectedInventoryId = ref("");
    const inventoryRaw = ref(false);
    const inventoryTab = ref("fields");
    const inventoryRawText = ref("");
    const inventoryLoading = ref(false);
    const inventoryError = ref("");

    const changes = ref([]);
    const selectedChangeId = ref("");
    const selectedChange = ref(null);
    const changeLoading = ref(false);
    const changeError = ref("");
    const applyingChange = ref(false);

    const validation = ref(null);
    const freshness = ref(null);

    const keys = ref([]);
    const keysShowAll = ref(false);
    const keysLoading = ref(false);
    const keysError = ref("");
    const issuedToken = ref("");
    const issuedKey = ref(null);
    const keyForm = reactive({ consumer: "claude-code", name: "" });

    const confirmState = reactive({
      open: false,
      title: "",
      message: "",
      confirmText: "",
      variant: "warning",
      action: null
    });

    let searchTimer = null;

    const userDisplayName = computed(
      () =>
        user.value?.display_name ||
        user.value?.email ||
        user.value?.user_id ||
        ""
    );
    const userInitials = computed(() => {
      const source = userDisplayName.value || "?";
      return source
        .split(/\s+/)
        .slice(0, 2)
        .map(part => part[0])
        .join("")
        .toUpperCase()
        .slice(0, 2);
    });
    const isAuthenticated = computed(
      () => !authEnabled.value || Boolean(user.value)
    );
    const canWrite = computed(
      () => !authEnabled.value || Boolean(user.value)
    );
    const isAdmin = computed(() => user.value?.system_role === "admin");
    const storageIsDb = computed(() => storage.value === "db");

    const navItems = computed(() => [
      { id: "docs", label: t("nav.docs"), icon: "ph-files" },
      { id: "inventory", label: t("nav.inventory"), icon: "ph-database" },
      { id: "changes", label: t("nav.changes"), icon: "ph-git-pull-request" },
      { id: "status", label: t("nav.status"), icon: "ph-heartbeat" },
      ...(authEnabled.value && user.value
        ? [{ id: "keys", label: t("nav.keys"), icon: "ph-key" }]
        : [])
    ]);

    const pageMeta = computed(
      () =>
        ({
          docs: { title: t("docs.title"), subtitle: t("docs.subtitle") },
          inventory: {
            title: t("inventory.title"),
            subtitle: t("inventory.subtitle")
          },
          changes: {
            title: t("changes.title"),
            subtitle: t("changes.subtitle")
          },
          status: { title: t("status.title"), subtitle: t("status.subtitle") },
          keys: { title: t("keys.title"), subtitle: t("keys.subtitle") },
          settings: {
            title: t("settings.title"),
            subtitle: t("settings.subtitle")
          }
        })[activePage.value] || {
          title: t("app.title"),
          subtitle: t("app.subtitle")
        }
    );
    const pageTitle = computed(() => pageMeta.value.title);
    const pageSubtitle = computed(() => pageMeta.value.subtitle);
    const activeLocaleLabel = computed(
      () =>
        (localeOptions.find(option => option.value === locale.value) || localeOptions[0])
          .label
    );
    const settingsItems = computed(() => [
      {
        key: "storage",
        term: t("settings.storage"),
        value: storage.value || t("common.unknown")
      },
      {
        key: "health",
        term: t("common.status"),
        value: healthStatus.value || t("common.unknown")
      },
      {
        key: "auth",
        term: t("settings.auth"),
        value: authEnabled.value ? t("auth.title") : t("settings.authDisabled")
      },
      {
        key: "account",
        term: t("auth.account"),
        value: user.value
          ? `${userDisplayName.value} · ${user.value.email || user.value.user_id}`
          : t("common.none")
      },
      {
        key: "language",
        term: t("settings.language"),
        value: activeLocaleLabel.value
      }
    ]);

    const docFrontmatterItems = computed(() => {
      const frontmatter = selectedDoc.value?.frontmatter || {};
      const priority = [
        "owner",
        "status",
        "last_reviewed",
        "review_interval",
        "confidence",
        "source_of_truth"
      ];
      const keys = Object.keys(frontmatter).sort((a, b) => {
        const ai = priority.indexOf(a);
        const bi = priority.indexOf(b);
        if (ai === -1 && bi === -1) return a.localeCompare(b);
        if (ai === -1) return 1;
        if (bi === -1) return -1;
        return ai - bi;
      });
      return keys.map(key => ({
        key,
        term: readableKey(key),
        value: displayValue(frontmatter[key])
      }));
    });

    const renderedDocBody = computed(() =>
      renderMarkdown(selectedDoc.value?.body || "")
    );

    const filteredInventory = computed(() => {
      const query = inventoryFilter.value.trim().toLowerCase();
      if (!query) return inventoryRecords.value;
      return inventoryRecords.value.filter(item =>
        [item.id, item.name, item.fqdn, item.host]
          .filter(Boolean)
          .some(value => String(value).toLowerCase().includes(query))
      );
    });
    const selectedInventoryRecord = computed(
      () =>
        inventoryRecords.value.find(
          item => item.id === selectedInventoryId.value
        ) || null
    );
    const inventoryFieldItems = computed(() =>
      Object.entries(selectedInventoryRecord.value || {}).map(([key, value]) => ({
        key,
        term: readableKey(key),
        value: displayValue(value)
      }))
    );
    const inventoryColumns = computed(() => [
      { key: "name", label: t("common.name") },
      { key: "id", label: t("inventory.recordId") },
      { key: "host", label: t("inventory.host") }
    ]);
    const inventoryTabs = computed(() => [
      { id: "fields", label: t("common.fields"), icon: "ph-list-dashes" },
      { id: "json", label: t("common.raw"), icon: "ph-code" }
    ]);
    const inventoryDisplay = computed(() => {
      if (inventoryRaw.value) return inventoryRawText.value;
      return selectedInventoryRecord.value
        ? pretty(selectedInventoryRecord.value)
        : "";
    });

    const formatDate = value => {
      if (!value) return "—";
      const date = new Date(value);
      return Number.isNaN(date.getTime())
        ? String(value)
        : date.toLocaleString(locale.value);
    };
    const statusLabel = status =>
      ({
        draft: t("changes.draft"),
        pending: t("changes.pending"),
        applied: t("changes.appliedStatus"),
        rejected: t("changes.rejected")
      })[status] || status;
    const changeStatusVariant = status =>
      status === "applied"
        ? "success"
        : status === "rejected"
          ? "danger"
          : "secondary";
    const isLatestVersion = versionNo => {
      if (!docHistory.value.length) return false;
      const latest = Math.max(
        ...docHistory.value.map(version => version.version_no)
      );
      return versionNo === latest;
    };

    const changeDetailItems = computed(() => {
      const change = selectedChange.value;
      if (!change) return [];
      return [
        { key: "summary", term: t("common.summary"), value: change.summary },
        { key: "status", term: t("common.status"), value: statusLabel(change.status) },
        { key: "kind", term: t("common.type"), value: change.kind },
        { key: "target", term: t("common.target"), value: change.target },
        { key: "reason", term: t("common.reason"), value: change.reason || "—" },
        { key: "created", term: t("common.created"), value: formatDate(change.created_at) },
        {
          key: "actor",
          term: t("auth.account"),
          value: [change.actor_name, change.actor_kind, change.via].filter(Boolean).join(" · ") || "—"
        }
      ];
    });

    async function request(path, options = {}) {
      const response = await fetch(`/api${path}`, {
        credentials: "same-origin",
        ...options
      });
      if (response.status === 401) {
        user.value = null;
        throw new Error(t("errors.unauthorized"));
      }
      if (response.status === 204) return null;
      if (!response.ok) {
        const text = await response.text();
        let detail = text;
        try {
          const data = JSON.parse(text);
          detail = data.detail || data.error || text;
        } catch {
          /* keep text */
        }
        throw new Error(`${response.status}: ${detail}`);
      }
      const contentType = response.headers.get("content-type") || "";
      return contentType.includes("application/json")
        ? response.json()
        : response.text();
    }
    const apiGet = path => request(path);
    const apiSend = (path, method, body) =>
      request(path, {
        method,
        headers: body ? { "Content-Type": "application/json" } : undefined,
        body: body ? JSON.stringify(body) : undefined
      });

    async function loadMe() {
      booting.value = true;
      pageError.value = "";
      try {
        const response = await fetch("/api/me", {
          credentials: "same-origin"
        });
        if (!response.ok) {
          throw new Error(`/me ${response.status}`);
        }
        const data = await response.json();
        authEnabled.value = Boolean(data.auth_enabled);
        user.value = data.user || null;
        localeOverride.value = data.locale || null;
        if (data.user && data.locale_effective) {
          setLocale(data.locale_effective);
        } else if (!data.user) {
          setLocale(savedLocale() || data.locale_effective || "en");
        }

        const params = new URLSearchParams(window.location.search);
        if (params.get("auth_error")) {
          pageError.value = t("auth.denied");
          window.history.replaceState({}, "", window.location.pathname);
        }
      } catch (error) {
        pageError.value =
          error instanceof Error ? error.message : t("errors.loadFailed");
      } finally {
        booting.value = false;
      }

      if (isAuthenticated.value) {
        await loadAll();
      }
    }

    async function loadAll() {
      pageError.value = "";
      const results = await Promise.allSettled([
        apiGet("/health"),
        apiGet("/docs"),
        apiGet("/inventory"),
        apiGet("/changes"),
        apiGet("/validate"),
        apiGet("/health/freshness"),
        authEnabled.value && user.value
          ? apiGet("/mcp-keys")
          : Promise.resolve(null)
      ]);
      const [health, docsResult, inventoryResult, changesResult, validationResult, freshnessResult, keysResult] =
        results;

      if (health.status === "fulfilled") {
        storage.value = health.value?.storage || "unknown";
        healthStatus.value = health.value?.status || "unknown";
      }
      if (docsResult.status === "fulfilled") {
        docs.value = docsResult.value || [];
        if (
          selectedDocPath.value &&
          docs.value.some(doc => doc.path === selectedDocPath.value)
        ) {
          await loadDoc(selectedDocPath.value);
        } else if (docs.value.length) {
          await loadDoc(docs.value[0].path, false);
        }
      }
      if (inventoryResult.status === "fulfilled") {
        inventoryTypes.value = inventoryResult.value || [];
        if (
          inventoryType.value &&
          inventoryTypes.value.includes(inventoryType.value)
        ) {
          await loadInventoryType(inventoryType.value);
        } else if (inventoryTypes.value.length) {
          await loadInventoryType(inventoryTypes.value[0]);
        }
      }
      if (changesResult.status === "fulfilled") {
        changes.value = changesResult.value || [];
        if (
          selectedChangeId.value &&
          changes.value.some(change => change.id === selectedChangeId.value)
        ) {
          await loadChange(selectedChangeId.value);
        } else if (changes.value.length) {
          await loadChange(changes.value[0].id);
        } else {
          selectedChangeId.value = "";
          selectedChange.value = null;
        }
      }
      if (validationResult.status === "fulfilled") {
        validation.value = validationResult.value;
      }
      if (freshnessResult.status === "fulfilled") {
        freshness.value = freshnessResult.value;
      }
      if (keysResult.status === "fulfilled" && keysResult.value) {
        keys.value = keysResult.value.items || [];
      }

      const failed = results.find(result => result.status === "rejected");
      if (failed) {
        pageError.value =
          failed.reason?.message || t("errors.loadFailed");
      }
    }

    async function loadDoc(path, openDetail = true) {
      if (!path) return;
      if (docQuery.value) docQuery.value = "";
      selectedDocPath.value = path;
      if (openDetail) mobileDocView.value = "detail";
      selectedDoc.value = null;
      docLoading.value = true;
      docError.value = "";
      docHistory.value = [];
      historyError.value = "";
      docDiff.value = "";
      diffError.value = "";
      try {
        selectedDoc.value = await apiGet(
          `/docs/read?path=${encodeURIComponent(path)}`
        );
        if (storageIsDb.value) {
          try {
            docHistory.value = await apiGet(
              `/documents/${encodePath(path)}/history`
            );
          } catch {
            historyError.value = t("docs.noHistory");
          }
        } else {
          historyError.value = t("docs.noHistory");
        }
      } catch (error) {
        docError.value =
          error instanceof Error ? error.message : t("errors.loadFailed");
      } finally {
        docLoading.value = false;
      }
    }

    async function requestDiff(fromVersion, toVersion) {
      docDiff.value = "";
      diffError.value = "";
      if (!selectedDocPath.value) return;
      try {
        const data = await apiGet(
          `/documents/${encodePath(selectedDocPath.value)}/diff?from=${fromVersion}&to=${toVersion}`
        );
        docDiff.value = data.diff || "";
        if (!docDiff.value) diffError.value = t("docs.noDiff");
      } catch (error) {
        diffError.value =
          error instanceof Error ? error.message : t("errors.loadFailed");
      }
    }

    async function loadDiffFrom(versionNo) {
      const latest = docHistory.value.length
        ? Math.max(...docHistory.value.map(version => version.version_no))
        : versionNo;
      await requestDiff(versionNo, latest);
    }

    async function loadLatestDiff() {
      if (!docHistory.value.length) return;
      const latest = Math.max(
        ...docHistory.value.map(version => version.version_no)
      );
      await requestDiff(Math.max(1, latest - 1), latest);
    }

    function openProposal() {
      if (!selectedDoc.value) return;
      proposal.target = selectedDocPath.value;
      proposal.content =
        selectedDoc.value.raw || selectedDoc.value.body || defaultDocTemplate();
      proposal.summary = "";
      proposal.reason = "";
      proposalOpen.value = true;
    }

    function openHistory() {
      historyOpen.value = true;
      if (selectedDocPath.value && !docHistory.value.length) {
        loadDoc(selectedDocPath.value);
      }
    }

    function backToDocList() {
      mobileDocView.value = "list";
    }

    function switchInventoryTab(tab) {
      inventoryTab.value = tab;
      if (tab === "json" && !inventoryRawText.value) {
        refreshInventoryRaw();
      }
    }

    function restoreVersion(versionNo) {
      askConfirm({
        title: t("docs.restoreConfirm"),
        message: t("docs.restoreConfirmText", { version: versionNo }),
        confirmText: t("docs.restore"),
        variant: "warning",
        action: async () => {
          try {
            await apiSend(
              `/documents/${encodePath(selectedDocPath.value)}/restore/${versionNo}?summary=${encodeURIComponent(
                `${t("docs.restoreConfirm")} ${versionNo}`
              )}`,
              "POST"
            );
            toast.success({ title: t("docs.restored") });
            await loadDoc(selectedDocPath.value);
            await refreshChanges();
          } catch (error) {
            toast.danger({
              title: t("errors.actionFailed"),
              text: error instanceof Error ? error.message : t("errors.actionFailed")
            });
          }
        }
      });
    }

    async function submitProposal() {
      if (
        !proposal.summary.trim() ||
        !proposal.target.trim() ||
        !proposal.content.trim()
      ) {
        toast.warning({
          title: t("common.error"),
          text: t("docs.proposalMeta")
        });
        return;
      }
      proposalRunning.value = true;
      try {
        const created = await apiSend("/changes", "POST", {
          kind: "doc",
          target: proposal.target.trim(),
          summary: proposal.summary.trim(),
          reason: proposal.reason.trim(),
          payload: { content: proposal.content }
        });
        toast.success({
          title: t("docs.proposalCreated"),
          text: created.target || created.id
        });
        proposal.summary = "";
        proposal.reason = "";
        proposalOpen.value = false;
        activePage.value = "changes";
        drawerOpen.value = false;
        await refreshChanges();
        await loadChange(created.id);
      } catch (error) {
        toast.danger({
          title: t("errors.actionFailed"),
          text: error instanceof Error ? error.message : t("errors.actionFailed")
        });
      } finally {
        proposalRunning.value = false;
      }
    }

    async function refreshChanges() {
      try {
        changes.value = await apiGet("/changes");
        if (
          selectedChangeId.value &&
          changes.value.some(change => change.id === selectedChangeId.value)
        ) {
          await loadChange(selectedChangeId.value);
        } else if (changes.value.length) {
          await loadChange(changes.value[0].id);
        } else {
          selectedChangeId.value = "";
          selectedChange.value = null;
        }
      } catch (error) {
        changeError.value =
          error instanceof Error ? error.message : t("errors.loadFailed");
      }
    }

    async function loadChange(id) {
      selectedChangeId.value = id;
      changeLoading.value = true;
      changeError.value = "";
      try {
        selectedChange.value = await apiGet(
          `/changes/${encodeURIComponent(id)}`
        );
      } catch (error) {
        selectedChange.value = null;
        changeError.value =
          error instanceof Error ? error.message : t("errors.loadFailed");
      } finally {
        changeLoading.value = false;
      }
    }

    function applyChange(change) {
      if (!change) return;
      askConfirm({
        title: t("changes.applyConfirm"),
        message: t("changes.applyConfirmText"),
        confirmText: t("changes.apply"),
        variant: "success",
        action: async () => {
          applyingChange.value = true;
          try {
            await apiSend(
              `/changes/${encodeURIComponent(change.id)}/apply`,
              "POST"
            );
            toast.success({ title: t("changes.applied") });
            await refreshChanges();
            await refreshStatus();
          } catch (error) {
            toast.danger({
              title: t("errors.actionFailed"),
              text: error instanceof Error ? error.message : t("errors.actionFailed")
            });
          } finally {
            applyingChange.value = false;
          }
        }
      });
    }

    async function refreshStatus() {
      const results = await Promise.allSettled([
        apiGet("/validate"),
        apiGet("/health/freshness")
      ]);
      if (results[0].status === "fulfilled") validation.value = results[0].value;
      if (results[1].status === "fulfilled") freshness.value = results[1].value;
    }

    async function loadInventoryType(type) {
      if (!type) return;
      inventoryType.value = type;
      selectedInventoryId.value = "";
      inventoryLoading.value = true;
      inventoryError.value = "";
      try {
        inventoryRawText.value = "";
        inventoryRecords.value = (await apiGet(`/inventory/${encodeURIComponent(type)}`)) || [];
        selectedInventoryId.value = inventoryRecords.value[0]?.id || "";
        if (inventoryTab.value === "json") await refreshInventoryRaw();
      } catch (error) {
        inventoryRecords.value = [];
        inventoryError.value =
          error instanceof Error ? error.message : t("errors.loadFailed");
      } finally {
        inventoryLoading.value = false;
      }
    }

    async function refreshInventoryRaw() {
      if (!inventoryType.value) {
        inventoryRawText.value = "";
        return;
      }
      try {
        const data = await apiGet(
          `/inventory/${encodeURIComponent(inventoryType.value)}?raw=true`
        );
        inventoryRawText.value = data.raw || "";
      } catch (error) {
        inventoryError.value =
          error instanceof Error ? error.message : t("errors.loadFailed");
        inventoryRaw.value = false;
      }
    }

    async function toggleInventoryRaw() {
      inventoryRaw.value = !inventoryRaw.value;
      if (inventoryRaw.value) {
        await refreshInventoryRaw();
      }
    }

    async function loadKeys() {
      if (!user.value) return;
      keysLoading.value = true;
      keysError.value = "";
      try {
        const data = await apiGet(
          `/mcp-keys${keysShowAll.value ? "?all=true" : ""}`
        );
        keys.value = data.items || [];
      } catch (error) {
        keysError.value =
          error instanceof Error ? error.message : t("errors.loadFailed");
      } finally {
        keysLoading.value = false;
      }
    }

    async function createKey() {
      if (!keyForm.consumer.trim()) {
        toast.warning({ title: t("common.error"), text: t("keys.consumer") });
        return;
      }
      keysLoading.value = true;
      keysError.value = "";
      try {
        const data = await apiSend("/mcp-keys", "POST", {
          consumer: keyForm.consumer.trim(),
          name: keyForm.name.trim()
        });
        issuedToken.value = data.token;
        issuedKey.value = data;
        keyForm.name = "";
        toast.success({ title: t("keys.issuedTitle") });
        await loadKeys();
      } catch (error) {
        keysError.value =
          error instanceof Error ? error.message : t("errors.actionFailed");
      } finally {
        keysLoading.value = false;
      }
    }

    function rotateKey(key) {
      askConfirm({
        title: t("keys.rotate"),
        message: t("keys.issuedText"),
        confirmText: t("keys.rotate"),
        variant: "warning",
        action: async () => {
          try {
            const data = await apiSend(
              `/mcp-keys/${encodeURIComponent(key.key_id)}/rotate`,
              "POST"
            );
            issuedToken.value = data.token;
            issuedKey.value = data;
            toast.success({ title: t("keys.rotated") });
            await loadKeys();
          } catch (error) {
            toast.danger({
              title: t("errors.actionFailed"),
              text: error instanceof Error ? error.message : t("errors.actionFailed")
            });
          }
        }
      });
    }

    function revokeKey(key) {
      askConfirm({
        title: t("keys.revokeConfirm"),
        message: t("keys.revokeConfirmText"),
        confirmText: t("keys.revoke"),
        variant: "danger",
        action: async () => {
          try {
            await apiSend(
              `/mcp-keys/${encodeURIComponent(key.key_id)}`,
              "DELETE"
            );
            toast.success({ title: t("keys.revoked") });
            await loadKeys();
          } catch (error) {
            toast.danger({
              title: t("errors.actionFailed"),
              text: error instanceof Error ? error.message : t("errors.actionFailed")
            });
          }
        }
      });
    }

    async function copyToken() {
      try {
        await navigator.clipboard.writeText(issuedToken.value);
        toast.success({ title: t("common.copied") });
      } catch {
        toast.danger({ title: t("errors.actionFailed") });
      }
    }

    function dismissIssued() {
      issuedToken.value = "";
      issuedKey.value = null;
    }

    async function toggleAllKeys() {
      if (!isAdmin.value) return;
      keysShowAll.value = !keysShowAll.value;
      await loadKeys();
    }

    async function changeLocale(value) {
      if (!authEnabled.value || !user.value) {
        setLocale(value);
        localeOverride.value = null;
        toast.success({ title: t("common.saved") });
        return;
      }
      try {
        if (value === "auto") {
          await apiSend("/me", "PATCH", { locale: "" });
          const data = await apiGet("/me");
          user.value = data.user;
          localeOverride.value = null;
          setLocale(data.locale_effective || "en");
        } else {
          await apiSend("/me", "PATCH", { locale: value });
          localeOverride.value = value;
          setLocale(value);
        }
        toast.success({ title: t("common.saved") });
      } catch (error) {
        toast.danger({
          title: t("errors.saveFailed"),
          text: error instanceof Error ? error.message : t("errors.saveFailed")
        });
      }
    }

    function login() {
      window.location.assign("/api/auth/login");
    }

    function logout() {
      askConfirm({
        title: t("auth.logoutConfirm"),
        message: t("auth.logoutConfirmText"),
        confirmText: t("nav.logout"),
        variant: "danger",
        action: async () => {
          try {
            await apiSend("/auth/logout", "POST");
          } catch {
            /* the local session is cleared regardless */
          }
          user.value = null;
          localeOverride.value = null;
          activePage.value = "docs";
          toast.info({ title: t("auth.loggedOut") });
        }
      });
    }

    function askConfirm({ title, message, confirmText, variant, action }) {
      confirmState.title = title || "";
      confirmState.message = message || "";
      confirmState.confirmText = confirmText || "";
      confirmState.variant = variant || "warning";
      confirmState.action = action || null;
      confirmState.open = true;
    }

    function runConfirm() {
      const action = confirmState.action;
      confirmState.action = null;
      if (action) action();
    }

    function clearConfirm() {
      confirmState.action = null;
    }

    function go(page) {
      activePage.value = page;
      if (page === "docs") mobileDocView.value = "list";
      drawerOpen.value = false;
      if (page === "keys") loadKeys();
      if (page === "status") refreshStatus();
    }

    async function refreshAll() {
      await loadMe();
    }

    watch(docQuery, value => {
      window.clearTimeout(searchTimer);
      const query = value.trim();
      if (!query) {
        searchResults.value = [];
        searching.value = false;
        return;
      }
      searching.value = true;
      searchTimer = window.setTimeout(async () => {
        try {
          searchResults.value = await apiGet(
            `/search?q=${encodeURIComponent(query)}`
          );
        } catch (error) {
          toast.danger({
            title: t("errors.loadFailed"),
            text: error instanceof Error ? error.message : t("errors.loadFailed")
          });
        } finally {
          searching.value = false;
        }
      }, 300);
    });

    onMounted(loadMe);

    return {
      activeLocaleLabel,
      activePage,
      applyingChange,
      applyChange,
      authEnabled,
      backToDocList,
      booting,
      canWrite,
      changeError,
      changeDetailItems,
      changeLoading,
      changes,
      changeStatusVariant,
      clearConfirm,
      confirmState,
      copyToken,
      createKey,
      diffError,
      dismissIssued,
      docDiff,
      docError,
      docFrontmatterItems,
      docHistory,
      docLoading,
      docQuery,
      docs,
      drawerOpen,
      filteredInventory,
      formatDate,
      freshness,
      go,
      healthStatus,
      historyError,
      historyOpen,
      inventoryColumns,
      inventoryDisplay,
      inventoryError,
      inventoryFieldItems,
      inventoryFilter,
      inventoryLoading,
      inventoryRaw,
      inventoryRecords,
      inventoryTab,
      inventoryTabs,
      inventoryType,
      inventoryTypes,
      isAdmin,
      isLatestVersion,
      issuedKey,
      issuedToken,
      keyForm,
      keys,
      keysError,
      keysLoading,
      keysShowAll,
      loadDiffFrom,
      loadDoc,
      loadInventoryType,
      loadKeys,
      loadLatestDiff,
      locale,
      localeOptions,
      localeOverride,
      login,
      logout,
      mobileDocView,
      navItems,
      openHistory,
      openProposal,
      pageError,
      pageSubtitle,
      pageTitle,
      pretty,
      proposal,
      proposalOpen,
      proposalRunning,
      refreshAll,
      renderedDocBody,
      restoreVersion,
      revokeKey,
      rotateKey,
      runConfirm,
      searchResults,
      searching,
      selectedChange,
      selectedChangeId,
      selectedDoc,
      selectedDocPath,
      selectedInventoryId,
      selectedInventoryRecord,
      setActiveLocale: changeLocale,
      settingsItems,
      statusLabel,
      storage,
      storageIsDb,
      submitProposal,
      switchInventoryTab,
      t,
      toast,
      toggleAllKeys,
      toggleInventoryRaw,
      user,
      userDisplayName,
      userInitials,
      validation
    };
  },
  template: `
    <main class="gnb-app">
      <div v-if="booting" class="gnb-boot">
        <p>{{ t('common.loading') }}…</p>
      </div>

      <section v-else-if="authEnabled && !user" class="gnb-gate">
        <GnPageHeader
          :title="t('auth.title')"
          :subtitle="t('auth.subtitle')"
          :kicker="t('app.kicker')"
          accent
        />
        <GnCard :title="t('app.title')">
          <p class="gnb-lead">{{ t('auth.loginText') }}</p>
          <GnAlert v-if="pageError" variant="danger">{{ pageError }}</GnAlert>
          <div class="gnb-actions">
            <GnButton icon="ph-sign-in" variant="accent" @click="login">{{ t('auth.login') }}</GnButton>
            <GnButton icon="ph-arrow-clockwise" variant="secondary" @click="refreshAll">{{ t('auth.recheck') }}</GnButton>
          </div>
        </GnCard>
      </section>

      <section v-else class="gnb-shell">
        <aside class="gnb-sidebar" :class="{ 'is-open': drawerOpen }">
          <div class="gnb-brand">
            <span class="gnb-brand-mark">GB</span>
            <span class="gnb-brand-copy">
              <strong>{{ t('app.title') }}</strong>
              <small>{{ t('app.kicker') }}</small>
            </span>
          </div>
          <nav class="gnb-nav">
            <button
              v-for="item in navItems"
              :key="item.id"
              type="button"
              class="gnb-nav-item"
              :class="{ 'is-active': activePage === item.id }"
              @click="go(item.id)"
            >
              <i :class="['ph', item.icon]"></i>
              <span>{{ item.label }}</span>
            </button>
          </nav>
          <div class="gnb-sidebar-footer">
            <GnUserCard
              v-if="user"
              :name="userDisplayName"
              :email="user.email || ''"
              :avatar="{ initials: userInitials }"
              compact
            />
            <button type="button" class="gnb-nav-item" :class="{ 'is-active': activePage === 'settings' }" @click="go('settings')">
              <i class="ph ph-sliders"></i><span>{{ t('nav.settings') }}</span>
            </button>
            <button v-if="authEnabled && user" type="button" class="gnb-nav-item" @click="logout">
              <i class="ph ph-sign-out"></i><span>{{ t('nav.logout') }}</span>
            </button>
          </div>
        </aside>
        <div v-if="drawerOpen" class="gnb-backdrop" @click="drawerOpen = false"></div>

        <section class="gnb-main">
          <GnPageHeader
            :title="pageTitle"
            :subtitle="pageSubtitle"
            :kicker="t('app.kicker')"
            accent
          >
            <template #actions>
              <GnButton class="gnb-mobile-menu" variant="secondary" icon="ph-list" @click="drawerOpen = true">{{ t('nav.menu') }}</GnButton>
              <GnButton variant="secondary" icon="ph-arrow-clockwise" :loading="booting" @click="refreshAll">{{ t('common.refresh') }}</GnButton>
            </template>
          </GnPageHeader>

          <GnAlert v-if="pageError" variant="danger">{{ pageError }}</GnAlert>

          <section v-if="activePage === 'docs'" class="gnb-page">
            <div class="gnb-docs-layout">
              <aside class="gnb-doc-list gnb-panel" :class="{ 'is-mobile-hidden': mobileDocView === 'detail' }">
                <div class="gnb-panel-head">
                  <span class="gnb-panel-title">{{ t('docs.index') }}</span>
                  <span class="gnb-muted">{{ docs.length }}</span>
                </div>
                <GnSearchField v-model="docQuery" :placeholder="t('docs.searchPlaceholder')" />
                <div v-if="docQuery.trim()" class="gnb-list-body">
                  <p v-if="searching" class="gnb-muted">{{ t('common.loading') }}…</p>
                  <GnEmptyState v-else-if="!searchResults.length" :title="t('docs.noResults')" icon="ph-magnifying-glass" />
                  <button
                    v-for="result in searchResults"
                    :key="result.path"
                    type="button"
                    class="gnb-doc-row"
                    @click="loadDoc(result.path)"
                  >
                    <strong>{{ result.title }}</strong>
                    <span>{{ result.path }}</span>
                    <small v-for="match in result.matches" :key="result.path + '-' + match.line">{{ match.line }}: {{ match.text }}</small>
                  </button>
                </div>
                <div v-else class="gnb-list-body">
                  <GnEmptyState v-if="!docs.length" :title="t('docs.noDocs')" icon="ph-files" />
                  <button
                    v-for="doc in docs"
                    :key="doc.path"
                    type="button"
                    class="gnb-doc-row"
                    :class="{ 'is-active': doc.path === selectedDocPath }"
                    @click="loadDoc(doc.path)"
                  >
                    <strong>{{ doc.title }}</strong>
                    <span>{{ doc.path }}</span>
                  </button>
                </div>
              </aside>

              <section class="gnb-doc-detail" :class="{ 'is-mobile-hidden': mobileDocView === 'list' }">
                <div class="gnb-doc-toolbar">
                  <GnButton class="gnb-mobile-back" size="sm" variant="secondary" icon="ph-arrow-left" @click="backToDocList">{{ t('common.back') }}</GnButton>
                  <div class="gnb-doc-heading">
                    <span class="gnb-doc-kicker">{{ t('docs.document') }}</span>
                    <h2>{{ selectedDoc?.path || t('docs.select') }}</h2>
                  </div>
                  <div class="gnb-actions">
                    <GnButton v-if="selectedDoc" size="sm" variant="secondary" icon="ph-clock-counter-clockwise" @click="openHistory">{{ t('common.history') }}</GnButton>
                    <GnButton v-if="selectedDoc && storageIsDb" size="sm" variant="secondary" icon="ph-git-diff" @click="loadLatestDiff(); historyOpen = true">{{ t('common.diff') }}</GnButton>
                    <GnButton v-if="selectedDoc && canWrite" size="sm" variant="accent" icon="ph-plus" @click="openProposal">{{ t('docs.newDraft') }}</GnButton>
                  </div>
                </div>

                <GnAlert v-if="docError" variant="danger">{{ docError }}</GnAlert>
                <GnEmptyState v-else-if="!selectedDoc" :title="t('docs.select')" icon="ph-file-text" />
                <div v-else class="gnb-doc">
                  <GnCard v-if="docFrontmatterItems.length" :title="t('docs.metadata')">
                    <GnDescriptionList :items="docFrontmatterItems" />
                  </GnCard>
                  <GnCard :title="t('docs.body')" class="gnb-doc-body-card">
                    <div class="gnb-markdown" v-html="renderedDocBody"></div>
                  </GnCard>
                  <GnAlert v-if="diffError" variant="warning">{{ diffError }}</GnAlert>
                </div>
              </section>
            </div>

            <GnDrawer v-model:open="historyOpen" :title="t('common.history')" position="right">
              <div class="gnb-history-drawer">
                <p v-if="historyError" class="gnb-muted">{{ historyError }}</p>
                <GnEmptyState v-else-if="!docHistory.length" :title="t('docs.noHistory')" icon="ph-clock" />
                <div v-else class="gnb-history">
                  <div v-for="version in docHistory" :key="version.version_no" class="gnb-history-row">
                    <button type="button" class="gnb-doc-row" @click="loadDiffFrom(version.version_no)">
                      <strong>v{{ version.version_no }} · {{ version.summary || t('common.unknown') }}</strong>
                      <span>{{ version.actor_kind }} / {{ version.actor_name || '—' }} · {{ version.via }} · {{ formatDate(version.created_at) }}</span>
                    </button>
                    <GnButton
                      v-if="storageIsDb && !isLatestVersion(version.version_no)"
                      size="sm"
                      variant="secondary"
                      icon="ph-arrow-counter-clockwise"
                      @click="restoreVersion(version.version_no)"
                    >{{ t('docs.restore') }}</GnButton>
                  </div>
                </div>
                <div v-if="docDiff" class="gnb-diff">
                  <div class="gnb-drawer-section-head">
                    <span>{{ t('docs.diffTitle') }}</span>
                    <GnButton size="sm" variant="secondary" @click="docDiff = ''">{{ t('common.close') }}</GnButton>
                  </div>
                  <pre class="gnb-pre">{{ docDiff }}</pre>
                </div>
                <GnAlert v-else-if="diffError" variant="warning">{{ diffError }}</GnAlert>
              </div>
            </GnDrawer>

            <GnModal v-model:open="proposalOpen" :title="t('docs.proposalTitle')">
              <p class="gnb-muted">{{ t('docs.proposalMeta') }}</p>
              <div class="gnb-form">
                <GnInput v-model="proposal.summary" :label="t('common.summary')" icon="ph-note-pencil" />
                <GnInput v-model="proposal.target" :label="t('common.target')" icon="ph-file-md" :placeholder="t('docs.targetPlaceholder')" />
                <GnInput v-model="proposal.reason" :label="t('common.reason')" icon="ph-question" />
                <GnTextarea v-model="proposal.content" :label="t('common.content')" :rows="14" class="gnb-textarea" :placeholder="t('docs.contentPlaceholder')" />
                <div class="gnb-actions">
                  <GnButton variant="success" icon="ph-plus" :loading="proposalRunning" :disabled="!canWrite" @click="submitProposal">{{ t('docs.submit') }}</GnButton>
                  <GnButton variant="secondary" @click="proposalOpen = false">{{ t('common.cancel') }}</GnButton>
                </div>
              </div>
            </GnModal>
          </section>

          <section v-else-if="activePage === 'inventory'" class="gnb-page">
            <div class="gnb-inventory-toolbar">
              <div class="gnb-chip-row">
                <GnChip
                  v-for="type in inventoryTypes"
                  :key="type"
                  clickable
                  variant="secondary"
                  :selected="type === inventoryType"
                  @click="loadInventoryType(type)"
                >{{ type }}</GnChip>
              </div>
              <span class="gnb-muted">{{ t('inventory.recordCount', { n: inventoryRecords.length }) }}</span>
            </div>

            <GnAlert v-if="inventoryError" variant="danger">{{ inventoryError }}</GnAlert>
            <GnEmptyState v-else-if="!inventoryTypes.length" :title="t('inventory.noTypes')" icon="ph-database" />
            <div v-else-if="inventoryType" class="gnb-inventory-layout">
              <aside class="gnb-record-list gnb-panel">
                <div class="gnb-panel-head">
                  <span class="gnb-panel-title">{{ inventoryType }}</span>
                  <span class="gnb-muted">{{ filteredInventory.length }}</span>
                </div>
                <GnSearchField v-model="inventoryFilter" :placeholder="t('inventory.filterPlaceholder')" />
                <GnTable
                  :columns="inventoryColumns"
                  :rows="filteredInventory"
                  :empty-text="t('inventory.noRecords')"
                >
                  <template #cell-name="{ row }">
                    <button
                      type="button"
                      class="gnb-table-link"
                      :class="{ 'is-active': row.id === selectedInventoryId }"
                      @click="selectedInventoryId = row.id"
                    >{{ row.name || row.fqdn || row.id || t('common.unknown') }}</button>
                  </template>
                  <template #cell-id="{ row }"><code>{{ row.id || '—' }}</code></template>
                  <template #cell-host="{ row }">{{ row.host || '—' }}</template>
                </GnTable>
              </aside>

              <GnCard class="gnb-record-detail">
                <template #title>
                  <span>{{ selectedInventoryRecord?.name || selectedInventoryRecord?.id || t('inventory.selectRecord') }}</span>
                </template>
                <GnEmptyState v-if="!selectedInventoryRecord" :title="t('inventory.selectRecord')" icon="ph-database" />
                <GnTabs v-else :model-value="inventoryTab" :items="inventoryTabs" aria-label="Record view" @update:model-value="switchInventoryTab">
                  <template #fields>
                    <GnDescriptionList :items="inventoryFieldItems" />
                  </template>
                  <template #json>
                    <GnAlert variant="info">{{ t('inventory.rawNotice') }}</GnAlert>
                    <pre v-if="inventoryRawText" class="gnb-pre">{{ inventoryRawText }}</pre>
                    <p v-else class="gnb-muted">{{ t('common.loading') }}…</p>
                  </template>
                </GnTabs>
              </GnCard>
            </div>
            <GnEmptyState v-else :title="t('inventory.selectType')" icon="ph-database" />
          </section>

          <section v-else-if="activePage === 'changes'" class="gnb-page">
            <div class="gnb-docs-layout">
              <aside class="gnb-doc-list gnb-panel">
                <GnEmptyState v-if="!changes.length" :title="t('changes.noChanges')" icon="ph-git-pull-request" />
                <button
                  v-for="change in changes"
                  :key="change.id"
                  type="button"
                  class="gnb-doc-row"
                  :class="{ 'is-active': change.id === selectedChangeId }"
                  @click="selectedChangeId = change.id; loadChange(change.id)"
                >
                  <strong>{{ change.summary }}</strong>
                  <span>{{ statusLabel(change.status) }} · {{ change.kind }} · {{ change.target }}</span>
                  <GnBadge :variant="changeStatusVariant(change.status)">{{ statusLabel(change.status) }}</GnBadge>
                </button>
              </aside>

              <section class="gnb-doc-detail">
                <GnToolbar
                  :title="selectedChange?.summary || t('changes.title')"
                  :meta="changeLoading ? t('common.loading') : statusLabel(selectedChange?.status || '')"
                >
                  <template #actions>
                    <GnButton
                      v-if="selectedChange && ['draft', 'pending'].includes(selectedChange.status) && canWrite"
                      variant="success"
                      icon="ph-check"
                      :loading="applyingChange"
                      @click="applyChange(selectedChange)"
                    >{{ t('changes.apply') }}</GnButton>
                  </template>
                </GnToolbar>
                <GnAlert v-if="changeError" variant="danger">{{ changeError }}</GnAlert>
                <GnEmptyState v-else-if="!selectedChange" :title="t('changes.select')" icon="ph-git-pull-request" />
                <div v-else class="gnb-doc">
                  <GnCard :title="t('common.details')">
                    <GnDescriptionList :items="changeDetailItems" />
                  </GnCard>
                  <GnCard :title="t('changes.validation')">
                    <p v-if="!selectedChange.validation" class="gnb-muted">{{ t('changes.noValidation') }}</p>
                    <template v-else>
                      <div class="gnb-badges">
                        <GnBadge :variant="selectedChange.validation.status === 'ok' ? 'success' : 'danger'">{{ selectedChange.validation.status }}</GnBadge>
                        <span>{{ t('common.issueCount', { n: selectedChange.validation.issue_count || 0 }) }}</span>
                      </div>
                      <IssueList :issues="selectedChange.validation.issues || []" />
                    </template>
                  </GnCard>
                </div>
              </section>
            </div>
          </section>

          <section v-else-if="activePage === 'status'" class="gnb-page">
            <div class="gnb-metrics">
              <GnMetricCard
                :label="t('status.validation')"
                :value="validation?.status || t('common.unknown')"
                icon="ph-shield-check"
                :meta="t('common.issueCount', { n: validation?.issue_count || 0 })"
              />
              <GnMetricCard
                :label="t('status.freshness')"
                :value="freshness?.status || t('common.unknown')"
                icon="ph-clock"
                :meta="t('common.issueCount', { n: freshness?.issue_count || 0 })"
              />
              <GnMetricCard
                :label="t('status.documents')"
                :value="String(freshness?.document_count ?? '—')"
                icon="ph-files"
                :meta="t('status.storage') + ': ' + storage"
              />
            </div>
            <div class="gnb-status-columns">
              <GnCard>
                <template #title>
                  <div class="gnb-card-title-row">
                    <span>{{ t('status.validation') }}</span>
                    <GnBadge :variant="validation?.status === 'ok' ? 'success' : 'danger'">{{ validation?.status || t('common.unknown') }}</GnBadge>
                  </div>
                </template>
                <IssueList :issues="(validation && validation.issues) || []" />
              </GnCard>
              <GnCard>
                <template #title>
                  <div class="gnb-card-title-row">
                    <span>{{ t('status.freshness') }}</span>
                    <GnBadge :variant="freshness?.status === 'ok' ? 'success' : 'warning'">{{ freshness?.status || t('common.unknown') }}</GnBadge>
                  </div>
                </template>
                <IssueList :issues="(freshness && freshness.issues) || []" />
              </GnCard>
            </div>
          </section>

          <section v-else-if="activePage === 'keys'" class="gnb-page">
            <GnAlert v-if="!authEnabled" variant="info">{{ t('keys.notConfigured') }}</GnAlert>
            <div v-else class="gnb-split">
              <GnCard :title="t('keys.createTitle')">
                <p class="gnb-muted">{{ t('keys.createMeta') }}</p>
                <div class="gnb-form">
                  <GnInput v-model="keyForm.consumer" :label="t('keys.consumer')" icon="ph-robot" placeholder="navi" />
                  <GnInput v-model="keyForm.name" :label="t('keys.name')" icon="ph-tag" />
                  <div class="gnb-actions">
                    <GnButton variant="success" icon="ph-key" :loading="keysLoading" @click="createKey">{{ t('keys.create') }}</GnButton>
                    <GnButton v-if="isAdmin" variant="secondary" @click="toggleAllKeys">{{ keysShowAll ? t('keys.own') : t('keys.showAll') }}</GnButton>
                  </div>
                </div>
                <GnAlert v-if="issuedToken && issuedKey" variant="success">
                  <strong>{{ t('keys.issuedTitle') }}</strong>
                  <p>{{ t('keys.issuedText') }}</p>
                  <p class="gnb-muted">{{ issuedKey.consumer }} · …{{ issuedKey.token_hint }}</p>
                  <code class="gnb-token">{{ issuedToken }}</code>
                  <div class="gnb-actions">
                    <GnButton size="sm" icon="ph-copy" variant="secondary" @click="copyToken">{{ t('keys.copyToken') }}</GnButton>
                    <GnButton size="sm" variant="secondary" @click="dismissIssued">{{ t('common.close') }}</GnButton>
                  </div>
                </GnAlert>
                <GnAlert v-if="keysError" variant="danger">{{ keysError }}</GnAlert>
              </GnCard>

              <GnCard :title="keysShowAll ? t('keys.showAll') : t('keys.own')">
                <GnEmptyState v-if="!keys.length" :title="t('keys.noKeys')" icon="ph-key" />
                <div v-else class="gnb-keys">
                  <div v-for="key in keys" :key="key.key_id" class="gnb-key-row">
                    <div class="gnb-key-copy">
                      <strong>{{ key.name }}</strong>
                      <span class="gnb-muted">{{ key.consumer }} · {{ key.role || t('common.unknown') }} · {{ (key.scopes || []).join(', ') }} · …{{ key.token_hint }}</span>
                      <span class="gnb-muted">{{ t('common.created') }}: {{ formatDate(key.created_at) }} · {{ t('common.lastUsed') }}: {{ formatDate(key.last_used_at) }}</span>
                      <div class="gnb-badges">
                        <GnBadge v-if="key.revoked_at" variant="danger">{{ t('common.revoked') }}</GnBadge>
                        <GnBadge v-if="key.stale_at" variant="warning">{{ t('common.stale') }}</GnBadge>
                      </div>
                    </div>
                    <div class="gnb-actions">
                      <GnButton v-if="!key.revoked_at" size="sm" variant="secondary" icon="ph-arrows-clockwise" @click="rotateKey(key)">{{ t('keys.rotate') }}</GnButton>
                      <GnButton v-if="!key.revoked_at" size="sm" variant="danger" icon="ph-trash" @click="revokeKey(key)">{{ t('keys.revoke') }}</GnButton>
                    </div>
                  </div>
                </div>
              </GnCard>
            </div>
          </section>

          <section v-else-if="activePage === 'settings'" class="gnb-page">
            <div class="gnb-split">
              <GnCard :title="t('settings.language')">
                <p class="gnb-muted">{{ t('settings.languageMeta') }}</p>
                <div class="gnb-actions gnb-language-actions">
                  <GnButton v-if="authEnabled" :variant="localeOverride ? 'secondary' : 'accent'" @click="setActiveLocale('auto')">{{ t('auth.localeAuto') }}</GnButton>
                  <GnButton
                    v-for="option in localeOptions"
                    :key="option.value"
                    :variant="locale === option.value ? 'accent' : 'secondary'"
                    @click="setActiveLocale(option.value)"
                  >{{ option.label }}</GnButton>
                </div>
              </GnCard>
              <GnCard :title="t('common.details')">
                <GnDescriptionList :items="settingsItems" />
                <div v-if="authEnabled && user" class="gnb-actions">
                  <GnButton variant="danger" icon="ph-sign-out" @click="logout">{{ t('nav.logout') }}</GnButton>
                </div>
              </GnCard>
            </div>
          </section>
        </section>
      </section>

      <GnConfirmDialog
        v-model:open="confirmState.open"
        :title="confirmState.title"
        :message="confirmState.message"
        :confirm-text="confirmState.confirmText || t('common.confirm')"
        :cancel-text="t('common.cancel')"
        :confirm-variant="confirmState.variant"
        @confirm="runConfirm"
        @cancel="clearConfirm"
      />
    </main>
  `
};

const App = {
  components: {
    AppScreen,
    GnToastProvider
  },
  template: `
    <GnToastProvider>
      <AppScreen />
    </GnToastProvider>
  `
};

createApp(App).mount("#app");