"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 MarketplaceBrowser_exports = {};
__export(MarketplaceBrowser_exports, {
  default: () => MarketplaceBrowser_default
});
module.exports = __toCommonJS(MarketplaceBrowser_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_agent_management = require("@dexto/agent-management");
var import_core = require("@dexto/core");
var import_BaseSelector = require("../base/BaseSelector.js");
function getSourceIcon(type) {
  switch (type) {
    case "github":
      return "\u{1F419}";
    case "git":
      return "\u{1F4E6}";
    case "local":
      return "\u{1F4C1}";
    default:
      return "\u{1F4E6}";
  }
}
const MarketplaceBrowser = (0, import_react.forwardRef)(
  function MarketplaceBrowser2({ isVisible, onAction, onClose }, ref) {
    const baseSelectorRef = (0, import_react.useRef)(null);
    const [selectedIndex, setSelectedIndex] = (0, import_react.useState)(0);
    const [isLoading, setIsLoading] = (0, import_react.useState)(true);
    const [loadError, setLoadError] = (0, import_react.useState)(null);
    const [view, setView] = (0, import_react.useState)("marketplaces");
    const [marketplaces, setMarketplaces] = (0, import_react.useState)([]);
    const [plugins, setPlugins] = (0, import_react.useState)([]);
    const [selectedMarketplace, setSelectedMarketplace] = (0, import_react.useState)(null);
    const [isInstalling, setIsInstalling] = (0, import_react.useState)(false);
    const [uninstalledDefaults, setUninstalledDefaults] = (0, import_react.useState)([]);
    const [pendingPlugin, setPendingPlugin] = (0, import_react.useState)(null);
    const [installedPluginNames, setInstalledPluginNames] = (0, import_react.useState)(/* @__PURE__ */ new Set());
    (0, import_react.useImperativeHandle)(
      ref,
      () => ({
        handleInput: (input, key) => {
          return baseSelectorRef.current?.handleInput(input, key) ?? false;
        }
      }),
      []
    );
    (0, import_react.useEffect)(() => {
      if (isVisible) {
        loadMarketplaces();
      }
    }, [isVisible]);
    const loadMarketplaces = () => {
      setIsLoading(true);
      setLoadError(null);
      setView("marketplaces");
      setSelectedMarketplace(null);
      setSelectedIndex(0);
      try {
        const mktplaces = (0, import_agent_management.listMarketplaces)();
        setMarketplaces(mktplaces);
        const allPlugins = (0, import_agent_management.listAllMarketplacePlugins)();
        setPlugins(allPlugins);
        const defaults = (0, import_agent_management.getUninstalledDefaults)();
        setUninstalledDefaults(defaults);
        const installed = (0, import_agent_management.listInstalledPlugins)();
        setInstalledPluginNames(new Set(installed.map((p) => p.name.toLowerCase())));
      } catch (error) {
        setLoadError(
          `Failed to load: ${error instanceof Error ? error.message : String(error)}`
        );
        setMarketplaces([]);
        setPlugins([]);
        setUninstalledDefaults([]);
        setInstalledPluginNames(/* @__PURE__ */ new Set());
      } finally {
        setIsLoading(false);
      }
    };
    const showMarketplacePlugins = (marketplaceName) => {
      setSelectedMarketplace(marketplaceName);
      setView("plugins");
      setSelectedIndex(0);
    };
    const goBackToMarketplaces = () => {
      setView("marketplaces");
      setSelectedMarketplace(null);
      setSelectedIndex(0);
    };
    const showScopeSelection = (plugin) => {
      setPendingPlugin(plugin);
      setView("scope-select");
      setSelectedIndex(0);
    };
    const goBackToPlugins = () => {
      setPendingPlugin(null);
      setView("plugins");
      setSelectedIndex(0);
    };
    const items = (0, import_react.useMemo)(() => {
      if (view === "marketplaces") {
        const list = [];
        list.push({ type: "back" });
        for (const def of uninstalledDefaults) {
          list.push({
            type: "default-marketplace",
            name: def.name,
            sourceValue: def.source.value,
            sourceType: def.source.type
          });
        }
        for (const m of marketplaces) {
          const pluginCount = plugins.filter((p) => p.marketplace === m.name).length;
          list.push({
            type: "marketplace",
            marketplace: m,
            pluginCount
          });
        }
        list.push({ type: "add-new" });
        return list;
      } else if (view === "scope-select") {
        const list = [{ type: "back" }];
        list.push({
          type: "scope",
          scope: "user",
          label: "Global (user)",
          description: "Available in all projects",
          icon: "\u{1F310}"
        });
        list.push({
          type: "scope",
          scope: "project",
          label: "Project only",
          description: "Only in current project, can be committed to git",
          icon: "\u{1F4C1}"
        });
        return list;
      } else {
        const filteredPlugins = selectedMarketplace ? plugins.filter((p) => p.marketplace === selectedMarketplace) : plugins;
        const list = [{ type: "back" }];
        for (const plugin of filteredPlugins) {
          const isInstalled = installedPluginNames.has(plugin.name.toLowerCase());
          list.push({
            type: "plugin",
            plugin,
            isInstalled
          });
        }
        return list;
      }
    }, [
      view,
      marketplaces,
      plugins,
      selectedMarketplace,
      uninstalledDefaults,
      installedPluginNames
    ]);
    const formatItem = (item, isSelected) => {
      if (item.type === "back") {
        const label = view === "scope-select" ? "Back to plugins" : view === "plugins" ? "Back to marketplaces" : "Back to menu";
        return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2190 " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "white" : "gray", children: label })
        ] });
      }
      if (item.type === "scope") {
        return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { children: [
              item.icon,
              " "
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: item.label })
          ] }),
          isSelected && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", dimColor: true, children: item.description }) })
        ] });
      }
      if (item.type === "add-new") {
        return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "green" : "gray", children: "+ " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "green" : "gray", children: "Add custom marketplace" })
        ] });
      }
      if (item.type === "default-marketplace") {
        const icon = getSourceIcon(item.sourceType);
        return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { children: [
              icon,
              " "
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: item.name }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", children: " (not installed)" })
          ] }),
          isSelected && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", dimColor: true, children: item.sourceValue }) })
        ] });
      }
      if (item.type === "marketplace") {
        const m = item.marketplace;
        const icon = getSourceIcon(m.source.type);
        return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { children: [
              icon,
              " "
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: m.name }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", dimColor: true, children: [
              " ",
              "(",
              item.pluginCount,
              " plugins)"
            ] })
          ] }),
          isSelected && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", dimColor: true, children: m.source.value }) })
        ] });
      }
      const p = item.plugin;
      const statusBadge = item.isInstalled ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "green", children: " \u2713" }) : null;
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "gray", children: isSelected ? "\u25B8 " : "  " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "white" : "gray", children: "\u{1F4E6} " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: p.name }),
          p.version && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", dimColor: true, children: [
            "@",
            p.version
          ] }),
          p.category && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "magenta", dimColor: true, children: [
            " ",
            "[",
            p.category,
            "]"
          ] }),
          statusBadge
        ] }),
        isSelected && p.description && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: p.description }) }),
        isSelected && item.isInstalled && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", dimColor: true, children: "Already installed" }) })
      ] });
    };
    const handleSelect = async (item) => {
      if (item.type === "back") {
        if (view === "scope-select") {
          goBackToPlugins();
        } else if (view === "plugins") {
          goBackToMarketplaces();
        } else {
          onClose();
        }
        return;
      }
      if (item.type === "add-new") {
        onAction({ type: "add-marketplace" });
        return;
      }
      if (item.type === "default-marketplace" && !isInstalling) {
        setIsInstalling(true);
        try {
          await (0, import_agent_management.addMarketplace)(item.sourceValue, { name: item.name });
          onAction({ type: "marketplace-added", marketplaceName: item.name });
          loadMarketplaces();
        } catch (error) {
          import_core.logger.error(
            `Failed to add marketplace ${item.name}: ${error instanceof Error ? error.message : String(error)}`
          );
        } finally {
          setIsInstalling(false);
        }
        return;
      }
      if (item.type === "marketplace") {
        showMarketplacePlugins(item.marketplace.name);
        return;
      }
      if (item.type === "plugin" && !item.isInstalled) {
        showScopeSelection(item.plugin);
        return;
      }
      if (item.type === "scope" && pendingPlugin && !isInstalling) {
        setIsInstalling(true);
        try {
          const result = await (0, import_agent_management.installPluginFromMarketplace)(
            `${pendingPlugin.name}@${pendingPlugin.marketplace}`,
            { scope: item.scope }
          );
          setInstalledPluginNames((prev) => {
            const next = new Set(prev);
            next.add(result.pluginName.toLowerCase());
            return next;
          });
          onAction({
            type: "plugin-installed",
            pluginName: result.pluginName,
            marketplace: result.marketplace
          });
          goBackToPlugins();
        } catch (error) {
          import_core.logger.error(
            `Failed to install ${pendingPlugin.name}: ${error instanceof Error ? error.message : String(error)}`
          );
        } finally {
          setIsInstalling(false);
        }
      }
    };
    const getTitle = () => {
      if (view === "scope-select" && pendingPlugin) {
        return `Install ${pendingPlugin.name} \u203A Choose Scope`;
      }
      if (view === "plugins" && selectedMarketplace) {
        return `${selectedMarketplace} \u203A Plugins`;
      }
      return "Marketplace";
    };
    const getEmptyMessage = () => {
      if (loadError) return loadError;
      if (view === "plugins") return "No plugins found in this marketplace";
      return "No marketplaces. Add one to browse plugins.";
    };
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_BaseSelector.BaseSelector,
      {
        ref: baseSelectorRef,
        items,
        isVisible,
        isLoading: isLoading || isInstalling,
        selectedIndex,
        onSelectIndex: setSelectedIndex,
        onSelect: handleSelect,
        onClose,
        formatItem,
        title: getTitle(),
        borderColor: "green",
        emptyMessage: getEmptyMessage(),
        loadingMessage: isInstalling ? "Installing..." : "Loading..."
      }
    );
  }
);
var MarketplaceBrowser_default = MarketplaceBrowser;
