import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback } from "react";
import { Box, Text, useInput } from "ink";
import { getConfig } from "../../../config.js";
import { semantic } from "../theme/palette.js";
import { activityStore } from "../state/activity-store-instance.js";
function DoctorScreen({ onBack }) {
  const [phase, setPhase] = useState("running");
  const [exitCode, setExitCode] = useState(null);
  const [errorMsg, setErrorMsg] = useState("");
  useEffect(() => {
    let cancelled = false;
    async function run() {
      const end = activityStore.begin("doctor");
      try {
        const { runDoctor } = await import("../../doctor.js");
        const code = await runDoctor(getConfig().dataDir);
        if (cancelled) return;
        setExitCode(code);
        setPhase("done");
      } catch (err) {
        if (cancelled) return;
        setErrorMsg(err instanceof Error ? err.message : String(err));
        setPhase("error");
      } finally {
        end();
      }
    }
    void run();
    return () => {
      cancelled = true;
    };
  }, []);
  useInput(useCallback((input, key) => {
    if (phase === "running") return;
    if (key.escape || input === "q" || key.return) onBack();
  }, [phase, onBack]));
  if (phase === "running") {
    return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 2, children: [
      /* @__PURE__ */ jsx(Text, { bold: true, children: "Running doctor diagnostic\u2026" }),
      /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Output streams above this line." }) })
    ] });
  }
  if (phase === "error") {
    return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 2, children: [
      /* @__PURE__ */ jsx(Text, { color: semantic.err, bold: true, children: "Doctor failed to run" }),
      /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: semantic.err, children: errorMsg }) }),
      /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press enter or q/esc to return" }) })
    ] });
  }
  const ok = exitCode === 0;
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 2, children: [
    /* @__PURE__ */ jsx(Text, { bold: true, color: ok ? semantic.ok : semantic.warn, children: ok ? "Doctor: all required components OK" : "Doctor: degraded (see output above)" }),
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
      "Exit code: ",
      exitCode
    ] }) }),
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press enter or q/esc to return" }) })
  ] });
}
export {
  DoctorScreen
};
//# sourceMappingURL=DoctorScreen.js.map