"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 SearchOverlay_exports = {};
__export(SearchOverlay_exports, {
  default: () => SearchOverlay_default
});
module.exports = __toCommonJS(SearchOverlay_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
const MAX_VISIBLE_RESULTS = 6;
const SEARCH_DEBOUNCE_MS = 300;
const SearchOverlay = (0, import_react.forwardRef)(function SearchOverlay2({ isVisible, onClose, onSelectResult, agent }, ref) {
  const [state, setState] = (0, import_react.useState)({
    query: "",
    results: [],
    isLoading: false,
    selectedIndex: 0,
    total: 0,
    hasMore: false,
    error: null
  });
  const searchTimeoutRef = (0, import_react.useRef)(null);
  const scrollOffset = (0, import_react.useRef)(0);
  const searchSeqRef = (0, import_react.useRef)(0);
  (0, import_react.useEffect)(() => {
    if (isVisible) {
      setState({
        query: "",
        results: [],
        isLoading: false,
        selectedIndex: 0,
        total: 0,
        hasMore: false,
        error: null
      });
      scrollOffset.current = 0;
    }
  }, [isVisible]);
  const performSearch = (0, import_react.useCallback)(
    async (query) => {
      const seq = ++searchSeqRef.current;
      if (!query.trim()) {
        setState((prev) => ({
          ...prev,
          results: [],
          total: 0,
          hasMore: false,
          isLoading: false,
          error: null
        }));
        return;
      }
      setState((prev) => ({ ...prev, isLoading: true, error: null }));
      try {
        const response = await agent.searchMessages(query, { limit: 20 });
        if (seq !== searchSeqRef.current) return;
        setState((prev) => ({
          ...prev,
          results: response.results,
          total: response.total,
          hasMore: response.hasMore,
          isLoading: false,
          selectedIndex: 0
        }));
        scrollOffset.current = 0;
      } catch (error) {
        if (seq !== searchSeqRef.current) return;
        setState((prev) => ({
          ...prev,
          results: [],
          total: 0,
          hasMore: false,
          isLoading: false,
          error: error instanceof Error ? error.message : "Search failed"
        }));
      }
    },
    [agent]
  );
  const updateQuery = (0, import_react.useCallback)(
    (newQuery) => {
      setState((prev) => ({ ...prev, query: newQuery }));
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
      searchTimeoutRef.current = setTimeout(() => {
        void performSearch(newQuery);
      }, SEARCH_DEBOUNCE_MS);
    },
    [performSearch]
  );
  (0, import_react.useEffect)(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      handleInput: (input, key) => {
        if (!isVisible) return false;
        if (key.escape) {
          onClose();
          return true;
        }
        if (key.return && state.results.length > 0) {
          const selectedResult = state.results[state.selectedIndex];
          if (selectedResult && onSelectResult) {
            onSelectResult(selectedResult);
          }
          onClose();
          return true;
        }
        if (key.upArrow) {
          setState((prev) => {
            const newIndex = Math.max(0, prev.selectedIndex - 1);
            if (newIndex < scrollOffset.current) {
              scrollOffset.current = newIndex;
            }
            return { ...prev, selectedIndex: newIndex };
          });
          return true;
        }
        if (key.downArrow) {
          setState((prev) => {
            const newIndex = Math.min(prev.results.length - 1, prev.selectedIndex + 1);
            if (newIndex >= scrollOffset.current + MAX_VISIBLE_RESULTS) {
              scrollOffset.current = newIndex - MAX_VISIBLE_RESULTS + 1;
            }
            return { ...prev, selectedIndex: newIndex };
          });
          return true;
        }
        if (key.backspace || key.delete) {
          updateQuery(state.query.slice(0, -1));
          return true;
        }
        if (input && !key.ctrl && !key.meta) {
          updateQuery(state.query + input);
          return true;
        }
        return false;
      }
    }),
    [isVisible, onClose, onSelectResult, state, updateQuery]
  );
  if (!isVisible) return null;
  const visibleResults = state.results.slice(
    scrollOffset.current,
    scrollOffset.current + MAX_VISIBLE_RESULTS
  );
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: true, color: "cyan", children: "Search Messages" }),
      state.total > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
        " ",
        "(",
        state.total,
        " result",
        state.total !== 1 ? "s" : "",
        ")"
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", children: "> " }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: state.query }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", children: "_" })
    ] }),
    state.isLoading && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellowBright", children: "Searching..." }) }),
    state.error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "red", children: state.error }) }),
    !state.isLoading && state.results.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", marginTop: 1, children: [
      visibleResults.map((result, idx) => {
        const actualIndex = scrollOffset.current + idx;
        const isSelected = actualIndex === state.selectedIndex;
        const roleColor = result.message.role === "user" ? "blue" : result.message.role === "assistant" ? "green" : "yellowBright";
        return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
          import_ink.Box,
          {
            flexDirection: "column",
            paddingLeft: isSelected ? 0 : 2,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { children: [
                isSelected && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", bold: true, children: "> " }),
                /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: result.sessionId.slice(0, 8) }),
                /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " }),
                /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: roleColor, bold: isSelected, children: [
                  "[",
                  result.message.role,
                  "]"
                ] })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingLeft: isSelected ? 2 : 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: isSelected ? "white" : "gray", children: [
                "  ",
                truncateContext(result.context, 60)
              ] }) })
            ]
          },
          `${result.sessionId}-${result.messageIndex}`
        );
      }),
      state.results.length > MAX_VISIBLE_RESULTS && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
        "Showing ",
        scrollOffset.current + 1,
        "-",
        Math.min(
          scrollOffset.current + MAX_VISIBLE_RESULTS,
          state.results.length
        ),
        " ",
        "of ",
        state.results.length,
        state.hasMore ? "+" : ""
      ] }) })
    ] }),
    !state.isLoading && state.query && state.results.length === 0 && !state.error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
      'No results found for "',
      state.query,
      '"'
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2191\u2193 navigate \u2022 Enter select \u2022 Esc close" }) })
  ] });
});
function truncateContext(context, maxLength) {
  const cleaned = context.replace(/\s+/g, " ").trim();
  if (cleaned.length <= maxLength) {
    return cleaned;
  }
  return cleaned.slice(0, maxLength - 3) + "...";
}
var SearchOverlay_default = SearchOverlay;
