const $ = (id) => document.getElementById(id);
let session = new URLSearchParams(location.hash.slice(1)).get("session") || "";
history.replaceState(null, "", location.pathname);
let savedId = "",
  running = false;
async function api(path, body = {}) {
  const r = await fetch("/api/" + path, {
    method: "POST",
    headers: {
      authorization: "Bearer " + session,
      "content-type": "application/json",
    },
    body: JSON.stringify(body),
    cache: "no-store",
  });
  const value = await r.json();
  if (!r.ok) throw Error(value.error || `HTTP ${r.status}`);
  return value;
}
async function task(fn) {
  if (running) return;
  running = true;
  $("error").textContent = "";
  $("notice").textContent = "正在处理，请留意 macOS 确认窗口…";
  document.querySelectorAll("button").forEach((x) => (x.disabled = true));
  try {
    await fn();
    $("notice").textContent = "已完成。";
  } catch (e) {
    $("error").textContent = e.message;
    $("notice").textContent = "操作未完成，可以检查后重试。";
  } finally {
    running = false;
    document.querySelectorAll("button").forEach((x) => (x.disabled = false));
  }
}
async function refresh() {
  const s = await api("status");
  $("api").value = s.defaults.api;
  $("node").value ||= s.defaults.node;
  $("wrangler").value ||= s.defaults.wrangler;
  $("bootstrap").hidden = !s.bootstrapAvailable || s.connected;
  $("connect").hidden = s.connected;
  $("connected").hidden = !s.connected;
  $("enroll").hidden = !!s.device || !s.connected;
  $("device-status").textContent = s.device
    ? `${s.device.id} · 已登记（${s.device.api}）`
    : "请连接云端后登记此 Mac。";
  $("credentials").hidden = $("deployment").hidden = !(s.device && s.connected);
  $("broker-status").textContent = s.broker
    ? "本机 Broker 正在运行。"
    : s.brokerError || "Broker 尚未启动。";
  if (s.connected) {
    const data = await api("overview");
    const secrets = data.secrets.filter((x) => x.device_id === s.device?.id);
    $("secret-ref").replaceChildren(
      ...secrets.map((x) => {
        const o = document.createElement("option");
        o.value = x.id;
        o.textContent = "vault://" + x.id;
        return o;
      }),
    );
    $("secret-list").textContent = secrets.length
      ? "已保存：" + secrets.map((x) => "vault://" + x.id).join("、")
      : "尚未添加凭据。";
    const caps = data.capabilities.filter(
      (x) => x.device_id === s.device?.id && x.enabled,
    );
    if (!savedId && caps.length)
      $("notice").textContent =
        `已登记 ${caps.length} 个操作。可在云端后台查看；修改配置后重新检查并保存。`;
  }
}
$("connect").onsubmit = (e) => {
  e.preventDefault();
  const adminToken = $("admin").value;
  $("admin").value = "";
  void task(async () => {
    await api("connect", { api: $("api").value, adminToken });
    await refresh();
  });
};
$("bootstrap").onclick = () =>
  task(async () => {
    await api("connect", { bootstrap: true });
    await refresh();
  });
$("disconnect").onclick = () =>
  task(async () => {
    await api("disconnect");
    savedId = "";
    $("ready").hidden = $("review").hidden = true;
    await refresh();
  });
$("console").onclick = () => task(() => api("open-console"));
$("enroll").onsubmit = (e) => {
  e.preventDefault();
  void task(async () => {
    await api("enroll", { deviceId: $("device").value });
    await refresh();
  });
};
$("secret").onsubmit = (e) => {
  e.preventDefault();
  void task(async () => {
    await api("secret", { id: $("secret-id").value });
    await refresh();
  });
};
for (const kind of ["workspace", "config"])
  $("choose-" + kind).onclick = () =>
    task(async () => {
      $(kind === "workspace" ? "workspace" : "config-file").value = (
        await api("choose", { kind })
      ).path;
      invalidate();
    });
function invalidate() {
  $("review").hidden = true;
}
$("plan").oninput = invalidate;
$("plan").onsubmit = (e) => {
  e.preventDefault();
  void task(async () => {
    const p = await api("plan", {
      id: $("cap-id").value,
      workspace: $("workspace").value,
      node: $("node").value,
      wrangler: $("wrangler").value,
      configFile: $("config-file").value,
      secretId: $("secret-ref").value,
    });
    $("policy").textContent = JSON.stringify(p, null, 2);
    $("review").hidden = false;
  });
};
$("save").onclick = () =>
  task(async () => {
    const r = await api("save");
    savedId = r.id;
    $("instructions").textContent = r.instructions;
    $("ready").hidden = false;
    $("review").hidden = true;
    await refresh();
  });
$("integration").onclick = () =>
  task(async () => {
    const r = await api("integration", { id: savedId });
    $("integration-result").textContent = "已配置：" + r.path;
  });
void task(refresh);
