import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { Box, Text, useInput } from "ink";
import { semantic } from "../theme/palette.js";
const ACTIONS = [
  { id: "verify", label: "Verify" },
  { id: "doctor", label: "Doctor" },
  { id: "export", label: "Export" },
  { id: "import", label: "Import" },
  { id: "uninstall", label: "Uninstall" }
];
function formatValue(v) {
  if (v === void 0 || v === null) return "";
  if (typeof v === "string") return v;
  if (typeof v === "number" || typeof v === "boolean") return String(v);
  if (Array.isArray(v)) return v.map((x) => String(x)).join(", ");
  try {
    return JSON.stringify(v);
  } catch {
    return String(v);
  }
}
function categoryPreview(category, current) {
  for (const field of category.fields) {
    const raw = current[field.settingsPath];
    const value = raw !== void 0 ? raw : field.default;
    if (value === void 0 || value === null) continue;
    const rendered = formatValue(value);
    if (rendered.length === 0) continue;
    return rendered;
  }
  for (const field of category.fields) {
    if (field.kind === "select" && field.options && field.options.length > 0) {
      const first = field.options[0];
      if (first) return first.value;
    }
  }
  return "";
}
function SettingsHome(props) {
  const {
    store,
    catalog,
    onSelectCategory,
    onAction,
    onQuit,
    version,
    productName
  } = props;
  const [, setTick] = useState(0);
  useEffect(() => {
    const unsub = store.subscribe(() => setTick((t) => t + 1));
    return unsub;
  }, [store]);
  const current = store.getCurrent();
  const categoryRows = useMemo(
    () => catalog.map((c) => ({
      id: c.id,
      label: c.label,
      description: c.description,
      preview: categoryPreview(c, current)
    })),
    // current is rebuilt every render; recompute when its JSON shape changes.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [catalog, JSON.stringify(current)]
  );
  const totalRows = categoryRows.length + ACTIONS.length;
  const [focusedIndex, setFocusedIndex] = useState(0);
  const [confirmQuit, setConfirmQuit] = useState(false);
  const [quitSaving, setQuitSaving] = useState(false);
  const [quitError, setQuitError] = useState(null);
  const [helpVisible, setHelpVisible] = useState(false);
  useEffect(() => {
    if (focusedIndex >= totalRows && totalRows > 0) {
      setFocusedIndex(totalRows - 1);
    }
  }, [totalRows, focusedIndex]);
  const inActionRow = focusedIndex >= categoryRows.length;
  const actionIndex = focusedIndex - categoryRows.length;
  const pendingCount = store.dirtyKeys().length;
  useInput((input, key) => {
    if (confirmQuit) {
      if (key.escape) {
        setConfirmQuit(false);
        setQuitError(null);
        return;
      }
      if (input === "d" || input === "D") {
        setConfirmQuit(false);
        setQuitError(null);
        store.discard();
        onQuit();
        return;
      }
      if (key.return && !quitSaving) {
        setQuitSaving(true);
        const keys = store.dirtyKeys();
        void Promise.all(keys.map((k) => store.blur(k))).then(() => {
          setQuitSaving(false);
          setConfirmQuit(false);
          setQuitError(null);
          onQuit();
        }).catch((err) => {
          setQuitSaving(false);
          setQuitError(err instanceof Error ? err.message : String(err));
        });
        return;
      }
      return;
    }
    if (key.upArrow) {
      setFocusedIndex((i) => Math.max(0, i - 1));
      return;
    }
    if (key.downArrow) {
      setFocusedIndex(
        (i) => totalRows === 0 ? 0 : Math.min(totalRows - 1, i + 1)
      );
      return;
    }
    if (key.return) {
      if (inActionRow) {
        const action = ACTIONS[actionIndex];
        if (action) onAction(action.id);
        return;
      }
      const row = categoryRows[focusedIndex];
      if (row) onSelectCategory(row.id);
      return;
    }
    if (input === "q") {
      if (pendingCount > 0) {
        setConfirmQuit(true);
        return;
      }
      onQuit();
      return;
    }
    if (input === "?") {
      setHelpVisible((v) => !v);
      return;
    }
  });
  const titleLine = (() => {
    const name = productName ?? "wigolo";
    return version ? `${name} ${version}` : name;
  })();
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ jsx(Text, { bold: true, children: titleLine }),
      /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Settings" })
    ] }),
    /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: categoryRows.map((row, idx) => {
      const focused = idx === focusedIndex && !inActionRow;
      return /* @__PURE__ */ jsx(Box, { flexDirection: "row", children: /* @__PURE__ */ jsxs(Text, { children: [
        focused ? /* @__PURE__ */ jsx(Text, { color: semantic.accent, children: "\u276F " }) : "  ",
        /* @__PURE__ */ jsx(Text, { bold: focused, inverse: focused, children: row.label }),
        /* @__PURE__ */ jsx(Text, { children: "  " }),
        /* @__PURE__ */ jsx(Text, { dimColor: true, children: row.preview })
      ] }) }, row.id);
    }) }),
    /* @__PURE__ */ jsx(Box, { flexDirection: "row", marginTop: 1, children: ACTIONS.map((action, idx) => {
      const focused = inActionRow && idx === actionIndex;
      return /* @__PURE__ */ jsx(Box, { flexDirection: "row", marginRight: 2, children: /* @__PURE__ */ jsxs(Text, { children: [
        focused ? /* @__PURE__ */ jsx(Text, { color: semantic.accent, children: "\u276F " }) : "  ",
        /* @__PURE__ */ jsx(Text, { bold: focused, inverse: focused, children: action.label })
      ] }) }, action.id);
    }) }),
    /* @__PURE__ */ jsx(Box, { flexDirection: "row", marginTop: 1, children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
      "\u2191\u2193 navigate \xB7 enter open \xB7 q quit \xB7 ? help",
      pendingCount > 0 ? `  (${pendingCount} pending)` : ""
    ] }) }),
    helpVisible ? /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Pick a category to edit. Bottom row runs Verify / Doctor / Export / Import / Uninstall. Press q to quit." }) }) : null,
    confirmQuit ? /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
      /* @__PURE__ */ jsx(Text, { color: semantic.warn, children: `${pendingCount} unsaved change${pendingCount === 1 ? "" : "s"}. Choose:` }),
      /* @__PURE__ */ jsx(Text, { color: semantic.ok, children: "  \u23CE  Save & exit" }),
      /* @__PURE__ */ jsx(Text, { color: semantic.warn, children: "  d  Discard & exit" }),
      /* @__PURE__ */ jsx(Text, { color: semantic.textDim, children: "  esc  Cancel" }),
      quitSaving ? /* @__PURE__ */ jsx(Text, { dimColor: true, children: "  Saving\u2026" }) : null,
      quitError !== null ? /* @__PURE__ */ jsx(Text, { color: semantic.err, children: `  Error: ${quitError}` }) : null
    ] }) : null
  ] });
}
export {
  SettingsHome
};
//# sourceMappingURL=SettingsHome.js.map