import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Box, Text, useInput } from "ink";
import { FieldRenderer } from "./FieldRenderer.js";
import { ActionBar } from "./ActionBar.js";
import { createLogger } from "../../../logger.js";
const logger = createLogger("cli");
function CategoryScreen(props) {
  const { category, store, onBack, onEditBufferChange, initialFocusKey } = props;
  const [, setTick] = useState(0);
  useEffect(() => {
    const unsub = store.subscribe(() => setTick((t) => t + 1));
    return unsub;
  }, [store]);
  const current = store.getCurrent();
  const pending = store.getPending();
  const ctx = { current, pending };
  const visibleFields = useMemo(
    () => category.fields.filter((f) => f.visible ? f.visible(ctx) : true),
    // ctx is rebuilt every render; recompute whenever store contents change.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [category, JSON.stringify(current), JSON.stringify(pending)]
  );
  const [focusedIndex, setFocusedIndex] = useState(() => {
    if (!initialFocusKey) return 0;
    const idx = category.fields.findIndex((f) => f.key === initialFocusKey);
    return idx >= 0 ? idx : 0;
  });
  const [editing, setEditing] = useState(false);
  const [savedAtByPath, setSavedAtByPath] = useState({});
  const applyEditing = useCallback((next) => {
    setEditing(next);
    onEditBufferChange?.(next);
  }, [onEditBufferChange]);
  useEffect(() => {
    return () => {
      onEditBufferChange?.(false);
    };
  }, []);
  useEffect(() => {
    if (focusedIndex >= visibleFields.length && visibleFields.length > 0) {
      setFocusedIndex(visibleFields.length - 1);
    }
  }, [visibleFields.length, focusedIndex]);
  const pendingCount = store.dirtyKeys().length;
  useInput((input, key) => {
    if (editing) return;
    if (key.upArrow) {
      setFocusedIndex((i) => Math.max(0, i - 1));
      return;
    }
    if (key.downArrow) {
      setFocusedIndex(
        (i) => visibleFields.length === 0 ? 0 : Math.min(visibleFields.length - 1, i + 1)
      );
      return;
    }
    if (key.return) {
      if (visibleFields.length === 0) return;
      const focused = visibleFields[focusedIndex];
      if (!focused) return;
      if (focused.kind === "text" || focused.kind === "number" || focused.kind === "path") {
        applyEditing(true);
      }
      return;
    }
    if (key.escape) {
      onBack();
      return;
    }
  });
  const hotkeys = [
    { key: "\u2191\u2193", label: "field" },
    { key: "\u23CE", label: "edit \xB7 autosave" },
    { key: "esc", label: "back" },
    { key: "q", label: "quit" }
  ];
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ jsx(Text, { bold: true, children: category.label }),
      category.description ? /* @__PURE__ */ jsx(Text, { dimColor: true, children: category.description }) : null
    ] }),
    /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: visibleFields.map((field, idx) => {
      const focused = idx === focusedIndex;
      const settingsPath = field.settingsPath;
      const pendingVal = pending[settingsPath];
      const currentVal = current[settingsPath];
      const value = pendingVal !== void 0 ? pendingVal : currentVal !== void 0 ? currentVal : field.default;
      const currentForRenderer = currentVal !== void 0 ? currentVal : field.default;
      return /* @__PURE__ */ jsx(
        FieldRenderer,
        {
          field,
          value,
          current: currentForRenderer,
          focused,
          editing: focused && editing,
          onChange: (next) => {
            store.set(settingsPath, next);
          },
          onEditStart: () => applyEditing(true),
          onEditDone: () => {
            applyEditing(false);
            void store.blur(settingsPath).then(() => {
              setSavedAtByPath((prev) => ({ ...prev, [settingsPath]: Date.now() }));
            }).catch((err) => {
              logger.error("blur failed", { path: settingsPath, err: String(err) });
            });
          },
          onEditCancel: () => applyEditing(false),
          savedAt: savedAtByPath[settingsPath] ?? null
        },
        field.key
      );
    }) }),
    /* @__PURE__ */ jsx(ActionBar, { pendingCount, hotkeys })
  ] });
}
export {
  CategoryScreen
};
//# sourceMappingURL=CategoryScreen.js.map