"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useCallback, useEffect, useRef, useMemo, } from "react";
import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
import { cn } from "@stigmer/theme";
import { useSkillSearch } from "./useSkillSearch";
import { useScrollShadows } from "../internal/useScrollShadows";
import { ScrollFade } from "../internal/ScrollFade";
function refKey(ref) {
    return `${ref.org}/${ref.slug}`;
}
const LIST_ID = "stgm-skill-list";
/**
 * Searchable picker for selecting skills from the platform.
 *
 * Renders a search input and scrollable list of available skills.
 * Designed to be placed inside a popover container — this component
 * renders the picker content, not the popover shell.
 *
 * Selected skills produce `ResourceRef[]` with `kind: skill`.
 *
 * All visual properties flow through `--stgm-*` tokens.
 *
 * @example
 * ```tsx
 * function SkillSelector({ org }: { org: string }) {
 *   const [skills, setSkills] = useState<ResourceRef[]>([]);
 *
 *   return (
 *     <SkillPicker
 *       org={org}
 *       value={skills}
 *       onChange={setSkills}
 *     />
 *   );
 * }
 * ```
 */
export function SkillPicker({ org, scope, value, onChange, onDisplayNameResolved, disabled, className, }) {
    const { results, isLoading, error, query, setQuery } = useSkillSearch(org, { scope });
    const [focusIndex, setFocusIndex] = useState(-1);
    const searchRef = useRef(null);
    const results_ = useScrollShadows();
    const selected_ = useScrollShadows();
    const selectedKeys = useMemo(() => new Set(value.map(refKey)), [value]);
    const availableResults = useMemo(() => results.filter((r) => !selectedKeys.has(`${r.org}/${r.slug}`)), [results, selectedKeys]);
    useEffect(() => {
        setFocusIndex(-1);
    }, [query]);
    useEffect(() => {
        if (focusIndex >= 0) {
            results_.scrollRef.current
                ?.querySelector(`[data-idx="${focusIndex}"]`)
                ?.scrollIntoView({ block: "nearest" });
        }
    }, [focusIndex, results_.scrollRef]);
    const handleSelect = useCallback((result) => {
        const ref = {
            org: result.org,
            slug: result.slug,
            kind: ApiResourceKind.skill,
        };
        onChange([...value, ref]);
        onDisplayNameResolved?.(`${result.org}/${result.slug}`, result.name);
    }, [value, onChange, onDisplayNameResolved]);
    const handleRemove = useCallback((key) => {
        onChange(value.filter((r) => refKey(r) !== key));
    }, [value, onChange]);
    const handleSearchKeyDown = useCallback((e) => {
        if (e.key === "ArrowDown") {
            e.preventDefault();
            setFocusIndex((prev) => prev < availableResults.length - 1 ? prev + 1 : prev);
        }
        else if (e.key === "ArrowUp") {
            e.preventDefault();
            setFocusIndex((prev) => (prev > 0 ? prev - 1 : -1));
        }
        else if (e.key === "Enter" &&
            focusIndex >= 0 &&
            focusIndex < availableResults.length) {
            e.preventDefault();
            handleSelect(availableResults[focusIndex]);
        }
        else if (e.key === "Enter") {
            e.preventDefault();
        }
    }, [availableResults, focusIndex, handleSelect]);
    return (_jsxs("div", { className: ["space-y-2 w-72", className].filter(Boolean).join(" "), children: [value.length > 0 && (_jsxs("div", { className: "space-y-1", children: [_jsx("div", { className: "text-[0.65rem] font-medium text-muted-foreground", children: "Selected" }), _jsxs("div", { className: "relative", children: [selected_.canScrollUp && _jsx(ScrollFade, { position: "top" }), _jsx("div", { ref: selected_.scrollRef, className: "max-h-28 space-y-1 overflow-y-auto", children: value.map((ref) => {
                                    const key = refKey(ref);
                                    return (_jsxs("div", { className: "flex items-center gap-2 rounded-md bg-muted-faint px-2 py-1 text-xs", children: [_jsx(SkillIcon, {}), _jsx("span", { className: "min-w-0 flex-1 truncate text-foreground", children: ref.slug }), _jsx("button", { type: "button", onClick: () => handleRemove(key), disabled: disabled, className: "shrink-0 text-muted-foreground hover:text-destructive disabled:pointer-events-none", "aria-label": `Remove ${ref.slug}`, children: _jsx(XIcon, {}) })] }, key));
                                }) }), selected_.canScrollDown && _jsx(ScrollFade, { position: "bottom" })] })] })), _jsx("input", { ref: searchRef, type: "text", role: "combobox", "aria-expanded": true, "aria-controls": LIST_ID, "aria-activedescendant": focusIndex >= 0 ? `stgm-skill-${focusIndex}` : undefined, placeholder: "Search skills...", value: query, onChange: (e) => setQuery(e.target.value), onKeyDown: handleSearchKeyDown, disabled: disabled, className: "w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", autoFocus: true }), error && _jsx("p", { className: "text-xs text-destructive", children: error.message }), _jsxs("div", { className: "relative", children: [results_.canScrollUp && _jsx(ScrollFade, { position: "top" }), _jsx("div", { ref: results_.scrollRef, id: LIST_ID, role: "listbox", "aria-label": "Skills", className: "max-h-52 overflow-y-auto", children: isLoading ? (_jsx(LoadingSkeleton, {})) : availableResults.length === 0 ? (_jsx("div", { className: "py-4 text-center text-xs text-muted-foreground", children: query
                                ? "No skills match your search"
                                : value.length > 0
                                    ? "All available skills selected"
                                    : "No skills found" })) : (availableResults.map((result, idx) => (_jsxs("button", { id: `stgm-skill-${idx}`, type: "button", "data-idx": idx, onClick: () => handleSelect(result), disabled: disabled, className: cn("group flex w-full flex-col gap-0.5 rounded-md px-2 py-1.5 text-left text-xs transition-colors", "disabled:pointer-events-none disabled:opacity-50", idx === focusIndex
                                ? "bg-accent text-foreground"
                                : "text-foreground hover:bg-accent-hover"), role: "option", "aria-selected": idx === focusIndex, children: [_jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx(SkillIcon, {}), _jsx("span", { className: "truncate font-medium", children: _jsx(HighlightMatch, { text: result.name, query: query }) }), _jsx("span", { className: "ml-auto shrink-0 text-[0.6rem] text-muted-foreground", children: result.org })] }), result.description && (_jsx("span", { className: cn("pl-5 text-[0.65rem] text-muted-foreground", idx !== focusIndex &&
                                        "line-clamp-2 group-hover:line-clamp-none"), children: result.description }))] }, result.id)))) }), results_.canScrollDown && _jsx(ScrollFade, { position: "bottom" })] })] }));
}
function HighlightMatch({ text, query }) {
    if (!query)
        return _jsx(_Fragment, { children: text });
    const idx = text.toLowerCase().indexOf(query.toLowerCase());
    if (idx === -1)
        return _jsx(_Fragment, { children: text });
    return (_jsxs(_Fragment, { children: [text.slice(0, idx), _jsx("span", { className: "font-semibold", children: text.slice(idx, idx + query.length) }), text.slice(idx + query.length)] }));
}
function LoadingSkeleton() {
    return (_jsx("div", { className: "space-y-1 py-1", children: [55, 70, 45, 62].map((w, i) => (_jsxs("div", { className: "flex flex-col gap-1 px-2 py-1.5", children: [_jsx("div", { className: "h-3 rounded bg-muted animate-pulse", style: { width: `${w}%` } }), _jsx("div", { className: "h-2 rounded bg-muted-subtle animate-pulse", style: { width: `${Math.min(w + 15, 90)}%` } })] }, i))) }));
}
function SkillIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: "shrink-0 text-muted-foreground", "aria-hidden": "true", children: _jsx("path", { d: "M2 3h12M2 7h8M2 11h10M2 15h6" }) }));
}
function XIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 14 14", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M4 4L10 10M10 4L4 10" }) }));
}
//# sourceMappingURL=SkillPicker.js.map