"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo } from "react";
import { Select } from "@base-ui/react/select";
import { RunnerPhase } from "@stigmer/protos/ai/stigmer/agentic/runner/v1/enum_pb";
import { useRunnerList } from "./useRunnerList";
import { isActivePhase, phaseLabel, phaseDotColor, PHASE_SORT_ORDER, } from "./phase";
/**
 * Sentinel value representing "Auto" (let the backend decide).
 *
 * Base UI Select requires a non-null string value for every item,
 * so we use this internal sentinel and map to/from `null` at the
 * component boundary.
 */
const AUTO_VALUE = "__auto__";
/**
 * Theme-able runner picker built on `@base-ui/react` Select.
 *
 * Fetches available runners via {@link useRunnerList} and renders
 * them in a dropdown grouped by operational phase. READY runners
 * appear first, then BUSY (selectable), then inactive runners
 * (STOPPED/PENDING/FAILED — visible but disabled).
 *
 * Includes an "Auto" option (default) that lets the backend decide
 * which runner to use. Platform builders who manage runner assignment
 * programmatically can disable this via `showAutoOption={false}`.
 *
 * All visual properties flow through `--stgm-*` tokens — no
 * hardcoded colors or sizes.
 *
 * Platform builders who need different rendering use
 * {@link useRunnerList} directly.
 *
 * @example
 * ```tsx
 * const [runnerId, setRunnerId] = useState<string | null>(null);
 *
 * <RunnerPicker
 *   org="acme"
 *   value={runnerId}
 *   onChange={setRunnerId}
 * />
 * ```
 */
export function RunnerPicker({ org, value, onChange, showAutoOption = true, className, disabled, }) {
    const { runners, isLoading } = useRunnerList(org);
    const { active, inactive } = useMemo(() => {
        const act = [];
        const inact = [];
        for (const r of runners) {
            if (isActivePhase(r.status?.phase ?? RunnerPhase.UNSPECIFIED)) {
                act.push(r);
            }
            else {
                inact.push(r);
            }
        }
        act.sort(phaseThenName);
        inact.sort(phaseThenName);
        return { active: act, inactive: inact };
    }, [runners]);
    const selectValue = value ?? AUTO_VALUE;
    const handleChange = (v) => {
        if (v === null)
            return;
        onChange(v === AUTO_VALUE ? null : v);
    };
    const triggerLabel = useMemo(() => {
        if (!value)
            return "Auto";
        const runner = runners.find((r) => r.metadata?.id === value);
        return runner?.metadata?.name ?? "Runner";
    }, [value, runners]);
    return (_jsxs(Select.Root, { value: selectValue, onValueChange: handleChange, disabled: disabled || isLoading, children: [_jsxs(Select.Trigger, { className: [
                    "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",
                    className,
                ]
                    .filter(Boolean)
                    .join(" "), children: [_jsx(RunnerIcon, {}), _jsx("span", { className: "max-w-[10rem] max-sm:max-w-[5rem] truncate", children: triggerLabel }), _jsx(ChevronIcon, {})] }), _jsx(Select.Portal, { children: _jsx(Select.Positioner, { sideOffset: 4, children: _jsxs(Select.Popup, { className: [
                            "z-popover max-h-72 min-w-[var(--anchor-width)] overflow-auto",
                            "rounded-lg border border-border bg-popover p-1 shadow-md",
                            "text-popover-foreground",
                        ].join(" "), children: [showAutoOption && (_jsxs(Select.Item, { value: AUTO_VALUE, className: [
                                    "flex cursor-pointer items-center gap-2",
                                    "rounded-md px-2 py-1.5 text-xs outline-none",
                                    "data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",
                                    "data-[selected]:font-medium",
                                ].join(" "), children: [_jsx(Select.ItemText, { children: "Auto" }), _jsx("span", { className: "text-[0.6rem] text-muted-foreground", children: "default" })] })), (showAutoOption && (active.length > 0 || inactive.length > 0)) && (_jsx("div", { className: "my-1 h-px bg-border/50", role: "separator" })), active.length > 0 && (_jsxs(Select.Group, { children: [_jsx(Select.GroupLabel, { className: "px-2 py-1.5 text-[0.65rem] font-medium uppercase tracking-wider text-muted-foreground", children: "Available" }), active.map((r) => (_jsx(RunnerItem, { runner: r }, r.metadata.id)))] })), inactive.length > 0 && (_jsxs(Select.Group, { children: [_jsx(Select.GroupLabel, { className: "px-2 py-1.5 text-[0.65rem] font-medium uppercase tracking-wider text-muted-foreground", children: "Offline" }), inactive.map((r) => (_jsx(RunnerItem, { runner: r, disabled: true }, r.metadata.id)))] })), runners.length === 0 && !isLoading && (_jsx("div", { className: "px-2 py-3 text-center text-xs text-muted-foreground", children: "No runners found" }))] }) }) })] }));
}
// ---------------------------------------------------------------------------
// Internal components
// ---------------------------------------------------------------------------
function RunnerItem({ runner, disabled, }) {
    const id = runner.metadata.id;
    const name = runner.metadata?.name ?? "Unnamed";
    const phase = runner.status?.phase ?? RunnerPhase.UNSPECIFIED;
    const hostname = runner.status?.connectionInfo?.hostname;
    return (_jsxs(Select.Item, { value: id, disabled: disabled, className: [
            "flex cursor-pointer items-center gap-2",
            "rounded-md px-2 py-1.5 text-xs outline-none",
            "data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",
            "data-[selected]:font-medium",
            "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
        ].join(" "), children: [_jsx(PhaseDot, { phase: phase }), _jsxs("div", { className: "flex min-w-0 flex-col", children: [_jsx(Select.ItemText, { children: _jsx("span", { className: "truncate", children: name }) }), hostname && (_jsx("span", { className: "truncate text-[0.6rem] leading-tight text-muted-foreground", children: hostname }))] }), _jsx("span", { className: "ml-auto shrink-0 text-[0.6rem] lowercase text-muted-foreground", children: phaseLabel(phase) })] }));
}
function PhaseDot({ phase }) {
    return (_jsx("span", { className: `inline-block h-1.5 w-1.5 shrink-0 rounded-full ${phaseDotColor(phase)}`, "aria-hidden": "true" }));
}
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
function phaseThenName(a, b) {
    const pa = a.status?.phase ?? RunnerPhase.UNSPECIFIED;
    const pb = b.status?.phase ?? RunnerPhase.UNSPECIFIED;
    const phaseOrder = PHASE_SORT_ORDER[pa] - PHASE_SORT_ORDER[pb];
    if (phaseOrder !== 0)
        return phaseOrder;
    return (a.metadata?.name ?? "").localeCompare(b.metadata?.name ?? "");
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function RunnerIcon() {
    return (_jsxs("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", className: "text-muted-foreground", children: [_jsx("rect", { x: "4", y: "4", width: "16", height: "16", rx: "2" }), _jsx("rect", { x: "9", y: "9", width: "6", height: "6" }), _jsx("path", { d: "M15 2v2" }), _jsx("path", { d: "M15 20v2" }), _jsx("path", { d: "M2 15h2" }), _jsx("path", { d: "M2 9h2" }), _jsx("path", { d: "M20 15h2" }), _jsx("path", { d: "M20 9h2" }), _jsx("path", { d: "M9 2v2" }), _jsx("path", { d: "M9 20v2" })] }));
}
function ChevronIcon() {
    return (_jsx("svg", { width: "10", height: "10", viewBox: "0 0 10 10", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: "text-muted-foreground", children: _jsx("path", { d: "M2.5 3.75L5 6.25L7.5 3.75" }) }));
}
//# sourceMappingURL=RunnerPicker.js.map