#!/usr/bin/env node
import {
  cliTheme
} from "./chunk-HKRLWERR.js";
import {
  useTextInput
} from "./chunk-U3IGFMCY.js";
import {
  CLI_COLORS,
  UI_LAYOUT,
  UI_SYMBOLS
} from "./chunk-FVN5PFFY.js";
import {
  init_esm_shims
} from "./chunk-DHET7RCE.js";

// src/cli/components/skill-search/skill-search.tsx
init_esm_shims();
import { useState as useState2, useCallback as useCallback2 } from "react";
import { Box, Text, useApp, useInput } from "ink";
import { ThemeProvider } from "@inkjs/ui";

// src/cli/components/hooks/use-filtered-results.ts
init_esm_shims();
import { useState, useMemo, useEffect, useCallback, useRef } from "react";
function useFilteredResults({
  items,
  query,
  filterFn,
  maxVisible
}) {
  const [focusedIndex, setFocusedIndex] = useState(0);
  const [scrollOffset, setScrollOffset] = useState(0);
  useEffect(() => {
    setFocusedIndex(0);
    setScrollOffset(0);
  }, [query]);
  const filteredResults = useMemo(() => {
    return items.filter((item) => filterFn(item, query));
  }, [items, query, filterFn]);
  const safeFocusedIndex = Math.min(focusedIndex, Math.max(0, filteredResults.length - 1));
  const focusedItem = filteredResults[safeFocusedIndex];
  const safeFocusedIndexRef = useRef(safeFocusedIndex);
  const scrollOffsetRef = useRef(scrollOffset);
  const resultCountRef = useRef(filteredResults.length);
  useEffect(() => {
    safeFocusedIndexRef.current = safeFocusedIndex;
  }, [safeFocusedIndex]);
  useEffect(() => {
    scrollOffsetRef.current = scrollOffset;
  }, [scrollOffset]);
  useEffect(() => {
    resultCountRef.current = filteredResults.length;
  }, [filteredResults.length]);
  const moveUp = useCallback(() => {
    const current = safeFocusedIndexRef.current;
    if (current <= 0) return;
    const newIndex = current - 1;
    setFocusedIndex(newIndex);
    if (newIndex < scrollOffsetRef.current) {
      setScrollOffset(newIndex);
    }
  }, []);
  const moveDown = useCallback(() => {
    const current = safeFocusedIndexRef.current;
    if (current >= resultCountRef.current - 1) return;
    const newIndex = current + 1;
    setFocusedIndex(newIndex);
    if (newIndex >= scrollOffsetRef.current + maxVisible) {
      setScrollOffset(newIndex - maxVisible + 1);
    }
  }, [maxVisible]);
  return {
    filteredResults,
    safeFocusedIndex,
    focusedItem,
    scrollOffset,
    moveUp,
    moveDown
  };
}

// src/cli/components/skill-search/skill-search.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var {
  MAX_VISIBLE_RESULTS,
  DESCRIPTION_WIDTH,
  COPIED_MESSAGE_TIMEOUT_MS,
  FALLBACK_MESSAGE_TIMEOUT_MS
} = UI_LAYOUT;
var { CHECKBOX_CHECKED, CHECKBOX_UNCHECKED } = UI_SYMBOLS;
function matchesQuery(skill, query) {
  if (!query.trim()) return true;
  const lowerQuery = query.toLowerCase();
  if (skill.id.toLowerCase().includes(lowerQuery)) return true;
  if (skill.displayName?.toLowerCase().includes(lowerQuery)) return true;
  if (skill.description.toLowerCase().includes(lowerQuery)) return true;
  if (skill.category.toLowerCase().includes(lowerQuery)) return true;
  if (skill.tags.some((tag) => tag.toLowerCase().includes(lowerQuery))) return true;
  return skill.sourceName.toLowerCase().includes(lowerQuery);
}
function truncate(text, maxLength) {
  if (text.length <= maxLength) return text;
  return `${text.slice(0, maxLength - 3)}...`;
}
var Header = ({ sourceCount }) => {
  return /* @__PURE__ */ jsxs(
    Box,
    {
      flexDirection: "row",
      justifyContent: "space-between",
      borderStyle: "single",
      borderBottom: false,
      borderLeft: false,
      borderRight: false,
      paddingX: 1,
      children: [
        /* @__PURE__ */ jsx(Text, { bold: true, color: CLI_COLORS.PRIMARY, children: "Search Skills" }),
        /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
          sourceCount,
          " source",
          sourceCount !== 1 ? "s" : ""
        ] })
      ]
    }
  );
};
var SearchInput = ({ value }) => {
  return /* @__PURE__ */ jsxs(Box, { paddingX: 1, paddingY: 1, children: [
    /* @__PURE__ */ jsxs(Text, { color: CLI_COLORS.FOCUS, children: [
      ">",
      " "
    ] }),
    /* @__PURE__ */ jsx(Text, { children: value }),
    /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.FOCUS, children: "_" })
  ] });
};
var ResultItem = ({ skill, isSelected, isFocused }) => {
  const checkbox = isSelected ? CHECKBOX_CHECKED : CHECKBOX_UNCHECKED;
  const displayName = skill.displayName || skill.id;
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
    /* @__PURE__ */ jsxs(
      Text,
      {
        color: isFocused ? CLI_COLORS.FOCUS : isSelected ? CLI_COLORS.SUCCESS : void 0,
        bold: isFocused,
        backgroundColor: isFocused ? "#333333" : void 0,
        children: [
          " ",
          checkbox,
          " "
        ]
      }
    ),
    /* @__PURE__ */ jsx(Box, { width: 14, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncate(skill.sourceName, 12) }) }),
    /* @__PURE__ */ jsx(Box, { width: 24, children: /* @__PURE__ */ jsx(Text, { color: isFocused ? CLI_COLORS.FOCUS : void 0, bold: isFocused || isSelected, children: truncate(displayName, 22) }) }),
    /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncate(skill.description, DESCRIPTION_WIDTH) })
  ] });
};
var ResultsList = ({
  results,
  selectedIds,
  focusedIndex,
  scrollOffset
}) => {
  const visibleResults = results.slice(scrollOffset, scrollOffset + MAX_VISIBLE_RESULTS);
  if (results.length === 0) {
    return /* @__PURE__ */ jsx(Box, { paddingX: 1, paddingY: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "No skills found matching your search." }) });
  }
  return /* @__PURE__ */ jsx(
    Box,
    {
      flexDirection: "column",
      borderStyle: "single",
      borderTop: false,
      borderBottom: false,
      paddingX: 1,
      children: visibleResults.map((skill, index) => {
        const actualIndex = scrollOffset + index;
        return /* @__PURE__ */ jsx(
          ResultItem,
          {
            skill,
            isSelected: selectedIds.has(skill.id),
            isFocused: actualIndex === focusedIndex
          },
          skill.id
        );
      })
    }
  );
};
var StatusBar = ({ resultCount, selectedCount }) => {
  return /* @__PURE__ */ jsx(Box, { paddingX: 1, children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
    resultCount,
    " result",
    resultCount !== 1 ? "s" : "",
    selectedCount > 0 && /* @__PURE__ */ jsxs(Text, { color: CLI_COLORS.SUCCESS, children: [
      " | ",
      selectedCount,
      " selected"
    ] })
  ] }) });
};
var Footer = ({ hasSelection }) => {
  return /* @__PURE__ */ jsxs(
    Box,
    {
      flexDirection: "row",
      justifyContent: "center",
      gap: 2,
      borderStyle: "single",
      borderTop: false,
      borderLeft: false,
      borderRight: false,
      paddingX: 1,
      marginTop: 1,
      children: [
        /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
          /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.UNFOCUSED, children: "j/k" }),
          " navigate"
        ] }),
        /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
          /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.UNFOCUSED, children: "SPACE" }),
          " select"
        ] }),
        hasSelection && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
          /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.SUCCESS, children: "ENTER" }),
          " import"
        ] }),
        /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
          /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.UNFOCUSED, children: "c" }),
          " copy link"
        ] }),
        /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
          /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.WARNING, children: "ESC" }),
          " cancel"
        ] })
      ]
    }
  );
};
var SkillSearch = ({
  skills,
  sourceCount,
  initialQuery = "",
  onComplete,
  onCancel
}) => {
  const { exit } = useApp();
  const { value: query, handleInput: handleTextInput } = useTextInput(initialQuery);
  const [selectedIds, setSelectedIds] = useState2(/* @__PURE__ */ new Set());
  const [copiedMessage, setCopiedMessage] = useState2(null);
  const {
    filteredResults,
    safeFocusedIndex,
    focusedItem: focusedSkill,
    scrollOffset,
    moveUp,
    moveDown
  } = useFilteredResults({
    items: skills,
    query,
    filterFn: matchesQuery,
    maxVisible: MAX_VISIBLE_RESULTS
  });
  const toggleSelection = useCallback2((skillId) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(skillId)) {
        next.delete(skillId);
      } else {
        next.add(skillId);
      }
      return next;
    });
  }, []);
  const copySkillLink = useCallback2(async (skill) => {
    const link = skill.sourceUrl ? `${skill.sourceUrl}/${skill.id}` : skill.id;
    try {
      const encoded = Buffer.from(link).toString("base64");
      process.stdout.write(`\x1B]52;c;${encoded}\x07`);
      setCopiedMessage(`Copied: ${link}`);
      setTimeout(() => setCopiedMessage(null), COPIED_MESSAGE_TIMEOUT_MS);
    } catch {
      setCopiedMessage(`Link: ${link}`);
      setTimeout(() => setCopiedMessage(null), FALLBACK_MESSAGE_TIMEOUT_MS);
    }
  }, []);
  useInput((input, key) => {
    if (key.escape) {
      onCancel();
      exit();
      return;
    }
    if (key.return) {
      if (selectedIds.size > 0) {
        const selectedSkills = filteredResults.filter((s) => selectedIds.has(s.id));
        onComplete({
          selectedSkills,
          cancelled: false
        });
        exit();
      }
      return;
    }
    if (input === " " && focusedSkill) {
      toggleSelection(focusedSkill.id);
      return;
    }
    if ((input === "c" || input === "C") && focusedSkill) {
      void copySkillLink(focusedSkill);
      return;
    }
    const isUp = key.upArrow || input === "k";
    const isDown = key.downArrow || input === "j";
    if (isUp) {
      moveUp();
    }
    if (isDown) {
      moveDown();
    }
    handleTextInput(input, key);
  });
  return /* @__PURE__ */ jsx(ThemeProvider, { theme: cliTheme, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx(Header, { sourceCount }),
    /* @__PURE__ */ jsx(SearchInput, { value: query }),
    /* @__PURE__ */ jsx(
      ResultsList,
      {
        results: filteredResults,
        selectedIds,
        focusedIndex: safeFocusedIndex,
        scrollOffset
      }
    ),
    /* @__PURE__ */ jsx(StatusBar, { resultCount: filteredResults.length, selectedCount: selectedIds.size }),
    copiedMessage && /* @__PURE__ */ jsx(Box, { paddingX: 1, children: /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.SUCCESS, children: copiedMessage }) }),
    /* @__PURE__ */ jsx(Footer, { hasSelection: selectedIds.size > 0 })
  ] }) });
};

export {
  SkillSearch
};
//# sourceMappingURL=chunk-ARET3NYO.js.map