import React from "react";
import { createRoot } from "react-dom/client";
import { CodeQueuePage } from "./code-queue";

type AnyRecord = Record<string, any>;

const h = React.createElement;
const useState: any = React.useState;

const rootElement = document.getElementById("root");
if (rootElement === null) throw new Error("root element not found");
const root = rootElement as HTMLElement;

function readJsonAttr(name: string, fallback: any): any {
  const raw = root.getAttribute(name);
  if (!raw) return fallback;
  try {
    const parsed = JSON.parse(raw) as unknown;
    return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed as AnyRecord : fallback;
  } catch {
    return fallback;
  }
}

const clientConfig = readJsonAttr("data-config", { apiBaseUrl: "/api" });
const initialOverview = readJsonAttr("data-codex-overview", null);
const apiBaseUrl = String(clientConfig.apiBaseUrl || "/api");

const standaloneCodeQueueService = {
  id: "code-queue",
  name: "Code Queue",
  providerId: "D601",
  description: "Code Queue 独立入口，使用 k3sctl-adapter 单一路径访问 active service。",
  repository: { containerName: "k3s:code-queue" },
  backend: {
    nodeBaseUrl: "k3s://code-queue",
    nodeBindHost: "k3s://unidesk/code-queue",
    nodePort: 4222,
    proxyMode: "k3sctl-adapter-http",
    public: false,
  },
  deployment: {
    mode: "k3sctl-managed",
    adapterServiceId: "k3sctl-adapter",
    k3sServiceId: "code-queue",
  },
  runtime: {
    orchestrator: "k3sctl",
    providerStatus: "online",
    providerName: "D601",
  },
};

function RawDialog({ raw, onClose }: AnyRecord) {
  if (!raw) return null;
  return h("div", { className: "modal-backdrop" },
    h("section", { className: "raw-dialog", role: "dialog", "aria-modal": "true", "aria-label": raw.title || "Raw JSON" },
      h("div", { className: "raw-dialog-head" },
        h("strong", null, raw.title || "Raw JSON"),
        h("button", { type: "button", className: "ghost-btn", onClick: onClose }, "关闭"),
      ),
      h("pre", { className: "raw-json" }, JSON.stringify(raw.data, null, 2)),
    ),
  );
}

function StandaloneCodeQueueApp() {
  const [raw, setRaw] = useState(null);
  return h("div", { className: "shell codex-standalone-shell", "data-testid": "code-queue-standalone" },
    h("main", { className: "workspace codex-standalone-workspace" },
      h("div", { className: "topbar codex-standalone-topbar" },
        h("div", null,
          h("strong", null, "Code Queue"),
          h("span", { className: "muted" }, "Standalone progressive loader"),
        ),
        h("div", { className: "topbar-actions" },
          h("a", { className: "ghost-btn", href: "/ops/performance/" }, "性能面板"),
          h("a", { className: "ghost-btn", href: "/" }, "完整工作台"),
        ),
      ),
      h(CodeQueuePage, {
        microservices: [standaloneCodeQueueService],
        apiBaseUrl,
        initialTasksData: initialOverview,
        standalone: true,
        onRaw: (title: string, data: any) => setRaw({ title, data }),
      }),
    ),
    h(RawDialog, { raw, onClose: () => setRaw(null) }),
  );
}

createRoot(root).render(h(StandaloneCodeQueueApp));
