"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var PromptList_exports = {};
__export(PromptList_exports, {
  default: () => PromptList_default
});
module.exports = __toCommonJS(PromptList_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_BaseSelector = require("../base/BaseSelector.js");
function getSourceIndicator(source) {
  switch (source) {
    case "config":
      return { icon: "\u{1F4C4}", label: "config", color: "blue" };
    case "custom":
      return { icon: "\u2728", label: "custom", color: "magenta" };
    case "mcp":
      return { icon: "\u{1F50C}", label: "mcp", color: "green" };
    default:
      return { icon: "\u{1F4DD}", label: source, color: "gray" };
  }
}
function isSharedPrompt(prompt) {
  const metadata = prompt.metadata;
  if (metadata?.filePath) {
    const normalizedPath = metadata.filePath.replaceAll("\\", "/");
    return normalizedPath.includes("/commands/") || normalizedPath.includes("/.dexto/commands/");
  }
  return false;
}
const PromptList = (0, import_react.forwardRef)(function PromptList2({ isVisible, onAction, onLoadIntoInput, onClose, agent }, ref) {
  const baseSelectorRef = (0, import_react.useRef)(null);
  const [selectedIndex, setSelectedIndex] = (0, import_react.useState)(0);
  const [prompts, setPrompts] = (0, import_react.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react.useState)(true);
  const [refreshKey, setRefreshKey] = (0, import_react.useState)(0);
  const loadPrompts = (0, import_react.useCallback)(() => {
    setIsLoading(true);
    setSelectedIndex(0);
    agent.listPrompts().then((promptSet) => {
      const promptList = Object.values(promptSet);
      promptList.sort((a, b) => {
        const order = { config: 0, custom: 1, mcp: 2 };
        const aOrder = order[a.source] ?? 3;
        const bOrder = order[b.source] ?? 3;
        if (aOrder !== bOrder) return aOrder - bOrder;
        return (a.displayName || a.name).localeCompare(b.displayName || b.name);
      });
      setPrompts(promptList);
      setIsLoading(false);
    }).catch((err) => {
      agent.logger.error(
        `PromptList: Failed to load prompts: ${err instanceof Error ? err.message : String(err)}`
      );
      setPrompts([]);
      setIsLoading(false);
    });
  }, [agent]);
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      handleInput: (input, key) => {
        return baseSelectorRef.current?.handleInput(input, key) ?? false;
      },
      refresh: () => {
        setRefreshKey((k) => k + 1);
      }
    }),
    []
  );
  (0, import_react.useEffect)(() => {
    if (isVisible) {
      loadPrompts();
    }
  }, [isVisible, refreshKey, loadPrompts]);
  const items = (0, import_react.useMemo)(() => {
    return [
      // Action items at the top
      { id: "__add__", type: "add" },
      { id: "__delete__", type: "delete" },
      // Prompts list
      ...prompts.map((prompt) => ({
        id: prompt.name,
        type: "prompt",
        prompt
      }))
    ];
  }, [prompts]);
  const formatItem = (item, isSelected) => {
    if (item.type === "add") {
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "green" : "gray", bold: isSelected, children: "+ Add new prompt" }) });
    }
    if (item.type === "delete") {
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "red" : "gray", bold: isSelected, children: "- Delete a prompt" }) });
    }
    const prompt = item.prompt;
    const displayName = prompt.displayName || prompt.name;
    const metadata = prompt.metadata;
    const effectiveSource = metadata?.namespace ? String(metadata.namespace) : prompt.source;
    const sourceInfo = getSourceIndicator(effectiveSource);
    const isShared = isSharedPrompt(prompt);
    const sourceLabel = isShared ? "shared" : sourceInfo.label;
    return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: displayName }),
      prompt.title && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
        " - ",
        prompt.title
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: sourceInfo.color, children: [
        " (",
        sourceLabel,
        ")"
      ] })
    ] });
  };
  const handleSelect = (item) => {
    if (item.type === "add") {
      onAction({ type: "add-prompt" });
    } else if (item.type === "delete") {
      onAction({ type: "delete-prompt" });
    } else if (item.prompt) {
      onAction({ type: "select-prompt", prompt: item.prompt });
    }
  };
  const handleTab = (item) => {
    if (item.type === "prompt" && item.prompt) {
      const displayName = item.prompt.displayName || item.prompt.name;
      onLoadIntoInput(`/${displayName} `);
    }
  };
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    import_BaseSelector.BaseSelector,
    {
      ref: baseSelectorRef,
      items,
      isVisible,
      isLoading,
      selectedIndex,
      onSelectIndex: setSelectedIndex,
      onSelect: handleSelect,
      onClose,
      formatItem,
      onTab: handleTab,
      supportsTab: true,
      title: "Prompts",
      borderColor: "yellowBright",
      emptyMessage: "No prompts configured",
      maxVisibleItems: 12
    }
  );
});
var PromptList_default = PromptList;
