"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Popover } from "@base-ui/react/popover";
import { cn } from "@stigmer/theme";
import { useModelRegistry } from "./useModelRegistry";
import { modelKey } from "./registry";
import { HARNESS_LABELS } from "./harness";
const COST_TIER_LABEL = {
    economy: "$",
    standard: "$$",
    premium: "$$$",
};
/**
 * Cursor-style model picker: a flat searchable list inside a popover.
 *
 * Shows a curated list of featured models by default. The user can
 * expand via "Show All Models" or type to search the full catalog.
 *
 * Each model row shows the display name, an engine tag
 * ("Stigmer" / "Cursor"), and a cost-tier indicator.
 *
 * In unified mode (no `harness` prop), selecting a model implicitly
 * resolves the harness via {@link ModelSelectorProps.onHarnessResolved}.
 *
 * @example
 * ```tsx
 * <ModelSelector
 *   value={selectedModelId}
 *   onValueChange={setSelectedModelId}
 *   onHarnessResolved={setHarness}
 * />
 * ```
 */
export function ModelSelector({ value, onValueChange, harness, onHarnessResolved, className, disabled, }) {
    const isUnified = harness === undefined;
    const { models, featured, defaultModel, getModel, getByKey } = useModelRegistry(isUnified ? undefined : { harness });
    const [open, setOpen] = useState(false);
    const [searchQuery, setSearchQuery] = useState("");
    const [showAll, setShowAll] = useState(false);
    const [highlightIdx, setHighlightIdx] = useState(-1);
    const searchRef = useRef(null);
    const listRef = useRef(null);
    const resolveSelected = useCallback(() => {
        if (!value)
            return undefined;
        if (isUnified) {
            const byKey = getByKey(value);
            if (byKey)
                return byKey;
        }
        return getModel(value);
    }, [value, isUnified, getByKey, getModel]);
    const selectedModel = resolveSelected() ?? defaultModel;
    const isSearching = searchQuery.length > 0;
    const lowerQuery = searchQuery.toLowerCase();
    const visibleModels = useMemo(() => {
        if (isSearching) {
            return models.filter((m) => m.displayName.toLowerCase().includes(lowerQuery)
                || m.modelId.toLowerCase().includes(lowerQuery)
                || HARNESS_LABELS[m.harness].toLowerCase().includes(lowerQuery));
        }
        if (showAll)
            return models;
        return featured.length > 0 ? featured : models;
    }, [models, featured, isSearching, showAll, lowerQuery]);
    useEffect(() => {
        setHighlightIdx(-1);
    }, [visibleModels]);
    useEffect(() => {
        if (!open) {
            setSearchQuery("");
            setShowAll(false);
            setHighlightIdx(-1);
        }
    }, [open]);
    useEffect(() => {
        if (open) {
            requestAnimationFrame(() => searchRef.current?.focus());
        }
    }, [open]);
    const selectModel = useCallback((model) => {
        const key = isUnified ? modelKey(model.harness, model.modelId) : model.modelId;
        onValueChange(key);
        if (isUnified && onHarnessResolved && model.harness !== selectedModel?.harness) {
            onHarnessResolved(model.harness);
        }
        setOpen(false);
    }, [isUnified, onValueChange, onHarnessResolved, selectedModel]);
    const scrollHighlightIntoView = useCallback((idx) => {
        const container = listRef.current;
        if (!container)
            return;
        const items = container.querySelectorAll("[data-model-option]");
        items[idx]?.scrollIntoView({ block: "nearest" });
    }, []);
    const handleKeyDown = useCallback((e) => {
        const len = visibleModels.length;
        if (len === 0)
            return;
        switch (e.key) {
            case "ArrowDown": {
                e.preventDefault();
                const next = highlightIdx < len - 1 ? highlightIdx + 1 : 0;
                setHighlightIdx(next);
                scrollHighlightIntoView(next);
                break;
            }
            case "ArrowUp": {
                e.preventDefault();
                const prev = highlightIdx > 0 ? highlightIdx - 1 : len - 1;
                setHighlightIdx(prev);
                scrollHighlightIntoView(prev);
                break;
            }
            case "Enter": {
                e.preventDefault();
                const target = highlightIdx >= 0 ? visibleModels[highlightIdx] : visibleModels[0];
                if (target)
                    selectModel(target);
                break;
            }
            case "Escape":
                e.preventDefault();
                setOpen(false);
                break;
        }
    }, [visibleModels, highlightIdx, selectModel, scrollHighlightIntoView]);
    const showShowAllButton = !isSearching && !showAll && featured.length > 0 && featured.length < models.length;
    const triggerLabel = selectedModel.displayName;
    const triggerHarness = isUnified ? HARNESS_LABELS[selectedModel.harness] : undefined;
    const triggerCost = COST_TIER_LABEL[selectedModel.costTier];
    return (_jsxs(Popover.Root, { open: open, onOpenChange: setOpen, children: [_jsxs(Popover.Trigger, { disabled: disabled, className: cn("inline-flex items-center gap-1.5 rounded-md border border-border", "bg-background px-2.5 py-1.5 text-xs text-foreground", "hover:bg-accent-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50", "transition-colors max-w-[18rem] max-sm:max-w-[10rem]", className), children: [_jsx("span", { className: "truncate", children: triggerLabel }), triggerHarness && (_jsx("span", { className: "shrink-0 rounded bg-muted px-1 py-0.5 text-[0.6rem] font-medium text-muted-foreground", children: triggerHarness })), _jsx("span", { className: "shrink-0 text-[0.6rem] text-muted-foreground", children: triggerCost }), _jsx(ChevronIcon, {})] }), _jsx(Popover.Portal, { children: _jsx(Popover.Positioner, { sideOffset: 4, children: _jsxs(Popover.Popup, { role: "dialog", "aria-label": "Model selector", className: cn("z-popover w-72 rounded-lg border border-border bg-popover shadow-md", "text-popover-foreground"), children: [_jsx("div", { className: "border-b border-border px-2 py-1.5", children: _jsx("input", { ref: searchRef, role: "searchbox", "aria-label": "Search models", placeholder: "Search models\u2026", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), onKeyDown: handleKeyDown, className: cn("w-full bg-transparent text-xs text-foreground placeholder:text-muted-foreground", "outline-none") }) }), _jsxs("div", { ref: listRef, role: "listbox", "aria-label": "Available models", className: "max-h-64 overflow-y-auto p-1", children: [visibleModels.length === 0 && (_jsx("div", { className: "px-2 py-3 text-center text-xs text-muted-foreground", children: "No models found" })), visibleModels.map((model, idx) => {
                                        const key = modelKey(model.harness, model.modelId);
                                        const isSelected = selectedModel
                                            ? model.harness === selectedModel.harness && model.modelId === selectedModel.modelId
                                            : false;
                                        const isHighlighted = idx === highlightIdx;
                                        return (_jsxs("button", { "data-model-option": "", role: "option", "aria-selected": isSelected, type: "button", className: cn("flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs outline-none", "transition-colors", isHighlighted && "bg-accent text-accent-foreground", !isHighlighted && "hover:bg-accent-hover", isSelected && "font-medium"), onClick: () => selectModel(model), onMouseEnter: () => setHighlightIdx(idx), children: [_jsx("span", { className: "flex-1 truncate text-left", children: model.displayName }), isUnified && (_jsx("span", { className: "shrink-0 rounded bg-muted px-1 py-0.5 text-[0.55rem] font-medium text-muted-foreground", children: HARNESS_LABELS[model.harness] })), _jsx("span", { className: "shrink-0 text-[0.6rem] text-muted-foreground", children: COST_TIER_LABEL[model.costTier] }), isSelected && (_jsx(CheckIcon, { className: "shrink-0 text-primary" }))] }, key));
                                    }), showShowAllButton && (_jsx("button", { type: "button", className: cn("mt-1 flex w-full items-center justify-center rounded-md border border-dashed border-border", "px-2 py-1.5 text-xs text-muted-foreground", "hover:bg-accent-hover hover:text-foreground transition-colors cursor-pointer"), onClick: () => setShowAll(true), children: "Show All Models" }))] })] }) }) })] }));
}
function ChevronIcon() {
    return (_jsx("svg", { className: "shrink-0 text-muted-foreground", width: "10", height: "10", viewBox: "0 0 10 10", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M2.5 3.75L5 6.25L7.5 3.75" }) }));
}
function CheckIcon({ className }) {
    return (_jsx("svg", { className: className, width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M2 6L5 9L10 3" }) }));
}
//# sourceMappingURL=ModelSelector.js.map