"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { StatusBadge } from "@open-mercato/ui/primitives/status-badge";
import { ErrorMessage } from "@open-mercato/ui/backend/detail";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
const API_PATH = "/api/configs/system-status";
const ENV_GUIDE_URL = "https://docs.openmercato.com/docs/framework/operations/system-status#managing-variables";
const STATUS_LABEL_KEYS = {
  enabled: "configs.systemStatus.state.enabled",
  disabled: "configs.systemStatus.state.disabled",
  set: "configs.systemStatus.state.set",
  unset: "configs.systemStatus.state.unset",
  unknown: "configs.systemStatus.state.unknown"
};
const STATUS_BADGE_VARIANTS = {
  enabled: "success",
  disabled: "neutral",
  set: "info",
  unset: "neutral",
  unknown: "warning"
};
const RUNTIME_MODE_LABEL_KEYS = {
  development: "configs.systemStatus.runtime.development",
  production: "configs.systemStatus.runtime.production",
  test: "configs.systemStatus.runtime.test",
  unknown: "configs.systemStatus.runtime.unknown"
};
const KNOWN_RUNTIME_MODES = /* @__PURE__ */ new Set(["development", "production", "test", "unknown"]);
function isSystemStatusSnapshot(payload) {
  if (!payload || typeof payload !== "object") return false;
  const value = payload;
  if (!Array.isArray(value.categories)) return false;
  if (typeof value.runtimeMode !== "string") return false;
  if (!KNOWN_RUNTIME_MODES.has(value.runtimeMode)) return false;
  return value.categories.every((category) => {
    if (!category || typeof category !== "object") return false;
    const entry = category;
    if (typeof entry.key !== "string") return false;
    if (!Array.isArray(entry.items)) return false;
    return entry.items.every((item) => {
      if (!item || typeof item !== "object") return false;
      const asItem = item;
      return typeof asItem.key === "string" && typeof asItem.state === "string";
    });
  });
}
function renderEnvAssignment(item, rawValue, translate) {
  const value = typeof rawValue === "string" ? rawValue : "";
  const hasValue = value.trim().length > 0;
  const codeClass = "block w-full break-all whitespace-pre-wrap rounded bg-muted px-1.5 py-0.5 font-mono text-xs sm:text-sm";
  if (!hasValue) {
    const notSet = translate("configs.systemStatus.value.notSet", "Not set");
    return /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("code", { className: codeClass, children: item.key }),
      /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground sm:text-sm", children: [
        "(",
        notSet,
        ")"
      ] })
    ] });
  }
  return /* @__PURE__ */ jsx("code", { className: codeClass, children: `${item.key}=${value}` });
}
function SystemStatusPanel() {
  const t = useT();
  const [state, setState] = React.useState({ loading: true, error: null, snapshot: null });
  const loadSnapshot = React.useCallback(async () => {
    setState((current) => ({ ...current, loading: true, error: null }));
    try {
      const payload = await readApiResultOrThrow(API_PATH, void 0, {
        errorMessage: t("configs.systemStatus.error", "Failed to load system status")
      });
      if (!isSystemStatusSnapshot(payload)) {
        setState({
          loading: false,
          error: t("configs.systemStatus.invalidResponse", "Unexpected response when loading system status"),
          snapshot: null
        });
        return;
      }
      setState({ loading: false, error: null, snapshot: payload });
    } catch (error) {
      const message = error instanceof Error && error.message ? error.message : t("configs.systemStatus.error", "Failed to load system status");
      setState({ loading: false, error: message, snapshot: null });
    }
  }, [t]);
  React.useEffect(() => {
    loadSnapshot().catch(() => {
    });
  }, [loadSnapshot]);
  if (state.loading) {
    return /* @__PURE__ */ jsxs("section", { className: "space-y-3 rounded-lg border bg-background p-6", children: [
      /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.systemStatus.title", "System status") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
          "configs.systemStatus.description",
          "Review debugging, cache, and logging flags that shape backend behaviour."
        ) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Spinner, { className: "h-4 w-4" }),
        t("configs.systemStatus.loading", "Loading status snapshot\u2026")
      ] })
    ] });
  }
  if (state.error) {
    return /* @__PURE__ */ jsxs("section", { className: "space-y-3 rounded-lg border bg-background p-6", children: [
      /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.systemStatus.title", "System status") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
          "configs.systemStatus.description",
          "Review debugging, cache, and logging flags that shape backend behaviour."
        ) })
      ] }),
      /* @__PURE__ */ jsx(ErrorMessage, { label: state.error }),
      /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => loadSnapshot().catch(() => {
      }), children: t("configs.systemStatus.retry", "Retry") })
    ] });
  }
  const snapshot = state.snapshot;
  if (!snapshot) return null;
  return /* @__PURE__ */ jsxs("section", { className: "space-y-6 rounded-lg border bg-background p-6", children: [
    /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.systemStatus.title", "System status") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("configs.systemStatus.description", "Review debugging, cache, and logging flags that shape backend behaviour.") }),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
        "configs.systemStatus.runtimeMode",
        "Runtime mode: {{mode}}",
        { mode: t(RUNTIME_MODE_LABEL_KEYS[snapshot.runtimeMode]) }
      ) }),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
        "configs.systemStatus.generatedAt",
        "Snapshot generated {{timestamp}}",
        { timestamp: new Date(snapshot.generatedAt).toLocaleString() }
      ) })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "space-y-6", children: snapshot.categories.map((category) => /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h3", { className: "text-base font-semibold", children: t(category.labelKey) }),
        category.descriptionKey ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(category.descriptionKey) }) : null
      ] }),
      /* @__PURE__ */ jsx("div", { className: "grid gap-4 lg:grid-cols-2", children: category.items.map((item) => /* @__PURE__ */ jsxs("article", { className: "flex flex-col gap-4 rounded-lg border bg-card p-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx("h4", { className: "text-sm font-semibold", children: t(item.labelKey) }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(item.descriptionKey) })
          ] }),
          /* @__PURE__ */ jsx(StatusBadge, { variant: STATUS_BADGE_VARIANTS[item.state], children: t(STATUS_LABEL_KEYS[item.state]) })
        ] }),
        /* @__PURE__ */ jsxs("dl", { className: "grid gap-3 text-sm sm:grid-cols-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx("dt", { className: "text-xs uppercase tracking-wide text-muted-foreground", children: t("configs.systemStatus.details.currentValue", "Current value") }),
            /* @__PURE__ */ jsx("dd", { className: "text-sm font-medium", children: renderEnvAssignment(item, item.value, t) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx("dt", { className: "text-xs uppercase tracking-wide text-muted-foreground", children: t("configs.systemStatus.details.defaultValue", "Default") }),
            /* @__PURE__ */ jsx("dd", { className: "text-sm font-medium", children: renderEnvAssignment(item, item.defaultValue, t) })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
          t(
            "configs.systemStatus.details.updateHint",
            "Update by running `export {{key}}=value` or editing `.env`, then restart the app.",
            { key: item.key }
          ),
          " ",
          /* @__PURE__ */ jsx(
            "a",
            {
              href: ENV_GUIDE_URL,
              className: "font-medium text-primary hover:underline",
              target: "_blank",
              rel: "noreferrer",
              children: t("configs.systemStatus.details.updateDocs", "Environment configuration guide")
            }
          )
        ] }),
        item.docUrl ? /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(
          "a",
          {
            href: item.docUrl,
            className: "text-sm font-medium text-primary hover:underline",
            target: "_blank",
            rel: "noreferrer",
            children: t("configs.systemStatus.viewDocs", "View documentation")
          }
        ) }) : null
      ] }, item.key)) })
    ] }, category.key)) })
  ] });
}
var SystemStatusPanel_default = SystemStatusPanel;
export {
  SystemStatusPanel,
  SystemStatusPanel_default as default
};
//# sourceMappingURL=SystemStatusPanel.js.map
