"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 SessionSelectorRefactored_exports = {};
__export(SessionSelectorRefactored_exports, {
  default: () => SessionSelectorRefactored_default
});
module.exports = __toCommonJS(SessionSelectorRefactored_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_core = require("@dexto/core");
var import_BaseSelector = require("../base/BaseSelector.js");
const SessionSelector = (0, import_react.forwardRef)(
  function SessionSelector2({ isVisible, onSelectSession, onClose, agent, currentSessionId }, ref) {
    const baseSelectorRef = (0, import_react.useRef)(null);
    (0, import_react.useImperativeHandle)(
      ref,
      () => ({
        handleInput: (input, key) => {
          return baseSelectorRef.current?.handleInput(input, key) ?? false;
        }
      }),
      []
    );
    const [sessions, setSessions] = (0, import_react.useState)([]);
    const [isLoading, setIsLoading] = (0, import_react.useState)(false);
    const [selectedIndex, setSelectedIndex] = (0, import_react.useState)(0);
    (0, import_react.useEffect)(() => {
      if (!isVisible) return;
      let cancelled = false;
      setIsLoading(true);
      const fetchSessions = async () => {
        try {
          const sessionIds = await agent.listSessions();
          const sessionList = await Promise.all(
            sessionIds.map(async (id) => {
              try {
                const metadata = await agent.getSessionMetadata(id);
                return {
                  id,
                  metadata,
                  isCurrent: id === currentSessionId
                };
              } catch {
                return {
                  id,
                  metadata: void 0,
                  isCurrent: id === currentSessionId
                };
              }
            })
          );
          sessionList.sort((a, b) => {
            if (a.isCurrent) return -1;
            if (b.isCurrent) return 1;
            const aTime = a.metadata?.lastActivity || 0;
            const bTime = b.metadata?.lastActivity || 0;
            return bTime - aTime;
          });
          if (!cancelled) {
            setSessions(sessionList);
            setIsLoading(false);
            setSelectedIndex(0);
          }
        } catch (error) {
          if (!cancelled) {
            import_core.logger.error(
              `Failed to fetch sessions: ${error instanceof Error ? error.message : "Unknown error"}`,
              { error }
            );
            setSessions([]);
            setIsLoading(false);
          }
        }
      };
      void fetchSessions();
      return () => {
        cancelled = true;
      };
    }, [isVisible, agent, currentSessionId]);
    const formatSession = (session) => {
      const parts = [];
      if (session.metadata?.title) {
        parts.push(session.metadata.title);
      } else {
        parts.push("New Session");
      }
      if (session.metadata?.parentSessionId) {
        parts.push(`forked from ${session.metadata.parentSessionId.slice(0, 8)}`);
      }
      parts.push(session.id.slice(0, 8));
      if (session.metadata?.lastActivity) {
        const now = Date.now();
        const diff = now - session.metadata.lastActivity;
        const minutes = Math.floor(diff / 6e4);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);
        if (days > 0) {
          parts.push(`${days}d ago`);
        } else if (hours > 0) {
          parts.push(`${hours}h ago`);
        } else if (minutes > 0) {
          parts.push(`${minutes}m ago`);
        } else {
          parts.push("just now");
        }
      }
      return parts.join(" \u2022 ");
    };
    const formatItem = (session, isSelected) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "gray", bold: isSelected, children: formatSession(session) }),
      session.isCurrent && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: isSelected ? "cyan" : "gray", bold: isSelected, children: [
        " ",
        "\u2190 Current"
      ] })
    ] });
    const handleSelect = (session) => {
      onSelectSession(session.id);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_BaseSelector.BaseSelector,
      {
        ref: baseSelectorRef,
        items: sessions,
        isVisible,
        isLoading,
        selectedIndex,
        onSelectIndex: setSelectedIndex,
        onSelect: handleSelect,
        onClose,
        formatItem,
        title: "Select Session",
        borderColor: "cyan",
        loadingMessage: "Loading sessions...",
        emptyMessage: "No sessions found"
      }
    );
  }
);
var SessionSelectorRefactored_default = SessionSelector;
