import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useMemo, useCallback } from "react";
import { Box, Text, useInput } from "ink";
import { readFileSync, existsSync } from "node:fs";
import { homedir } from "node:os";
import { activityStore as defaultActivityStore } from "../state/activity-store-instance.js";
import { semantic } from "../theme/palette.js";
function expandHome(path) {
  if (path === "~") return homedir();
  if (path.startsWith("~/")) return homedir() + path.slice(1);
  return path;
}
function readAndValidate(path, knownKeys) {
  const resolved = expandHome(path.trim());
  if (resolved.length === 0) {
    return { ok: false, error: "Path is empty" };
  }
  if (!existsSync(resolved)) {
    return { ok: false, error: `File not found: ${resolved}` };
  }
  let raw;
  try {
    raw = readFileSync(resolved, "utf-8");
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err.message : String(err) };
  }
  let parsed;
  try {
    parsed = JSON.parse(raw);
  } catch {
    return { ok: false, error: "Import file is not valid JSON" };
  }
  if (typeof parsed !== "object" || parsed === null) {
    return { ok: false, error: "Import file root is not a JSON object" };
  }
  const envelope = parsed;
  let settings;
  if (typeof envelope.settings === "object" && envelope.settings !== null && !Array.isArray(envelope.settings)) {
    settings = envelope.settings;
  } else {
    settings = envelope;
  }
  const known = [];
  const unknown = [];
  let total = 0;
  for (const [k, v] of Object.entries(settings)) {
    total++;
    if (knownKeys.has(k)) {
      known.push({ key: k, value: v });
    } else {
      unknown.push(k);
    }
  }
  return { ok: true, result: { known, unknown, total } };
}
function ImportScreen({
  store,
  catalog,
  onBack,
  activityStore = defaultActivityStore
}) {
  const [phase, setPhase] = useState("prompt");
  const [buffer, setBuffer] = useState("~/wigolo-config-export.json");
  const [parsed, setParsed] = useState(null);
  const [errorMsg, setErrorMsg] = useState("");
  const [stagedCount, setStagedCount] = useState(0);
  const knownKeys = useMemo(() => {
    const set = /* @__PURE__ */ new Set();
    for (const cat of catalog) {
      for (const field of cat.fields) {
        set.add(field.settingsPath);
      }
    }
    return set;
  }, [catalog]);
  const handleSubmitPath = useCallback(() => {
    const r = readAndValidate(buffer, knownKeys);
    if (!r.ok) {
      setErrorMsg(r.error);
      setPhase("error");
      return;
    }
    setParsed(r.result);
    setPhase("review");
  }, [buffer, knownKeys]);
  const handleConfirmStage = useCallback(() => {
    if (!parsed) return;
    const end = activityStore.begin("import");
    try {
      for (const { key, value } of parsed.known) {
        store.set(key, value);
      }
      setStagedCount(parsed.known.length);
      setPhase("done");
    } finally {
      end();
    }
  }, [parsed, store, activityStore]);
  useInput(useCallback((input, key) => {
    if (phase === "prompt") {
      if (key.escape) {
        onBack();
        return;
      }
      if (key.return) {
        handleSubmitPath();
        return;
      }
      if (key.backspace || key.delete) {
        setBuffer((b) => b.slice(0, -1));
        return;
      }
      if (input && !key.ctrl && !key.meta) {
        setBuffer((b) => b + input);
        return;
      }
      return;
    }
    if (phase === "review") {
      if (key.escape || input === "n" || input === "N") {
        onBack();
        return;
      }
      if (input === "y" || input === "Y" || key.return) {
        handleConfirmStage();
        return;
      }
      return;
    }
    if (phase === "error") {
      if (key.escape || input === "q") {
        onBack();
        return;
      }
      if (key.return) {
        setErrorMsg("");
        setPhase("prompt");
        return;
      }
      return;
    }
    if (key.escape || input === "q" || key.return) {
      onBack();
    }
  }, [phase, handleSubmitPath, handleConfirmStage, onBack]));
  if (phase === "prompt") {
    return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 2, children: [
      /* @__PURE__ */ jsx(Text, { bold: true, children: "Import config" }),
      /* @__PURE__ */ jsxs(Box, { marginTop: 1, children: [
        /* @__PURE__ */ jsx(Text, { children: "Path: " }),
        /* @__PURE__ */ jsx(Text, { children: buffer }),
        /* @__PURE__ */ jsx(Text, { color: semantic.accent, children: "_" })
      ] }),
      /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Enter the path to an exported config file. ~/ is expanded." }) }),
      /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "enter load \xB7 esc cancel" }) })
    ] });
  }
  if (phase === "error") {
    return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 2, children: [
      /* @__PURE__ */ jsx(Text, { bold: true, color: semantic.err, children: "Import error" }),
      /* @__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: "enter retry \xB7 q/esc back" }) })
    ] });
  }
  if (phase === "review" && parsed) {
    return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 2, children: [
      /* @__PURE__ */ jsx(Text, { bold: true, children: "Import: review" }),
      /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
        /* @__PURE__ */ jsxs(Text, { children: [
          /* @__PURE__ */ jsx(Text, { color: semantic.ok, children: parsed.known.length }),
          " known key",
          parsed.known.length === 1 ? "" : "s",
          " will be staged into pending."
        ] }),
        parsed.unknown.length > 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ jsxs(Text, { color: semantic.warn, children: [
            parsed.unknown.length,
            " unknown key",
            parsed.unknown.length === 1 ? "" : "s",
            " ignored:"
          ] }),
          parsed.unknown.slice(0, 10).map((k) => /* @__PURE__ */ jsx(Box, { paddingLeft: 2, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: k }) }, k)),
          parsed.unknown.length > 10 ? /* @__PURE__ */ jsx(Box, { paddingLeft: 2, children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
            "\u2026 and ",
            parsed.unknown.length - 10,
            " more"
          ] }) }) : null
        ] }) : null
      ] }),
      /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsxs(Text, { color: semantic.warn, children: [
        "Stage ",
        parsed.known.length,
        " change",
        parsed.known.length === 1 ? "" : "s",
        " into pending? (y/N)"
      ] }) }),
      /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Staged values appear as the (N pending) marker on the Settings screen until you commit them." }) })
    ] });
  }
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 2, children: [
    /* @__PURE__ */ jsxs(Text, { bold: true, color: semantic.ok, children: [
      "Staged ",
      stagedCount,
      " pending change",
      stagedCount === 1 ? "" : "s"
    ] }),
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Open the affected categories on Settings to review or discard." }) }),
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press enter or q/esc to return" }) })
  ] });
}
export {
  ImportScreen
};
//# sourceMappingURL=ImportScreen.js.map