"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState, } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage } from "@stigmer/sdk";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { RunnerPhase } from "@stigmer/protos/ai/stigmer/agentic/runner/v1/enum_pb";
import { useRunnerList } from "./useRunnerList";
import { useStopRunner } from "./useStopRunner";
import { useDeleteRunner } from "./useDeleteRunner";
import { isActivePhase, isTransitionalPhase, phaseLabel, phaseDotColor, PHASE_SORT_ORDER, } from "./phase";
const SYSTEM_MANAGED_LABEL = "stigmer.ai/system-managed";
const TRANSITIONAL_POLL_MS = 5_000;
/**
 * Panel that displays runners in an organization with lifecycle
 * management actions.
 *
 * Each runner is rendered as a card row showing name, phase indicator,
 * machine information, and operational metadata. Non-system-managed
 * runners include an action menu for stop and delete operations with
 * inline confirmation — no modals or portals.
 *
 * Rows are sorted by phase (active runners first) then alphabetically
 * by name. System-managed runners (when included) display a "System"
 * badge and have no action affordances.
 *
 * By default only user-created runners are shown. Pass
 * `includeSystemManaged={true}` for admin views that need full fleet
 * visibility.
 *
 * Designed for the Settings > Runners page but embeddable in any
 * context that needs runner fleet management. Fetches data via
 * {@link useRunnerList} and performs mutations via {@link useStopRunner}
 * and {@link useDeleteRunner} — no Console-specific dependencies.
 *
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <RunnerListPanel org="acme" />
 *
 * <RunnerListPanel
 *   org="acme"
 *   includeSystemManaged
 *   onStopped={(runner) => toast(`${runner.metadata?.name} stopped`)}
 *   onDeleted={(runner) => toast(`${runner.metadata?.name} deleted`)}
 *   onRefetchRef={(refetch) => { refetchRef.current = refetch; }}
 * />
 * ```
 */
export function RunnerListPanel({ org, includeSystemManaged = false, onRefetchRef, onStopped, onDeleted, className, }) {
    const [hasTransitional, setHasTransitional] = useState(false);
    const { runners, isLoading, error, refetch } = useRunnerList(org, {
        includeSystemManaged,
        refetchInterval: hasTransitional ? TRANSITIONAL_POLL_MS : false,
    });
    const [confirming, setConfirming] = useState(null);
    useEffect(() => {
        setHasTransitional(runners.some((r) => isTransitionalPhase(r.status?.phase ?? RunnerPhase.UNSPECIFIED)));
    }, [runners]);
    if (onRefetchRef) {
        onRefetchRef(refetch);
    }
    const sorted = useMemo(() => [...runners].sort(phaseThenName), [runners]);
    const handleRequestConfirm = useCallback((runnerId, action) => {
        setConfirming({ runnerId, action });
    }, []);
    const handleCancelConfirm = useCallback(() => {
        setConfirming(null);
    }, []);
    const handleActionComplete = useCallback((runner, action) => {
        setConfirming(null);
        refetch();
        if (action === "stop")
            onStopped?.(runner);
        else
            onDeleted?.(runner);
    }, [refetch, onStopped, onDeleted]);
    if (isLoading) {
        return (_jsx("div", { className: cn("space-y-2", className), "aria-busy": "true", "aria-label": "Loading runners", children: Array.from({ length: 3 }, (_, i) => (_jsx("div", { className: "bg-muted-subtle h-[4.25rem] animate-pulse rounded-lg" }, i))) }));
    }
    if (error) {
        return (_jsx("p", { className: cn("text-destructive text-xs", className), role: "alert", children: getUserMessage(error) }));
    }
    if (sorted.length === 0) {
        return (_jsxs("div", { className: cn("flex flex-col items-center gap-2 py-8 text-center", className), children: [_jsx(RunnerIcon, { size: 24 }), _jsx("p", { className: "text-muted-foreground text-xs", children: "No runners registered." }), _jsxs("p", { className: "text-muted-foreground-subtle max-w-xs text-[0.65rem]", children: ["Start a runner with", " ", _jsx("code", { className: "bg-muted rounded px-1 py-0.5 font-mono text-[0.6rem]", children: "stigmer up" }), " ", "or launch one from your browser with the button above."] })] }));
    }
    return (_jsx("div", { className: cn("space-y-2", className), role: "list", "aria-label": "Runners", children: sorted.map((runner) => {
            const id = runner.metadata.id;
            return (_jsx(RunnerRow, { runner: runner, confirmingAction: confirming?.runnerId === id ? confirming.action : null, onRequestConfirm: (action) => handleRequestConfirm(id, action), onCancelConfirm: handleCancelConfirm, onActionComplete: handleActionComplete }, id));
        }) }));
}
// ---------------------------------------------------------------------------
// RunnerRow (internal)
// ---------------------------------------------------------------------------
function RunnerRow({ runner, confirmingAction, onRequestConfirm, onCancelConfirm, onActionComplete, }) {
    const { stop, isStopping, error: stopError, clearError: clearStopError, } = useStopRunner();
    const { deleteRunner, isDeleting, error: deleteError, clearError: clearDeleteError, } = useDeleteRunner();
    const name = runner.metadata?.name ?? "Unnamed";
    const id = runner.metadata?.id ?? "";
    const phase = runner.status?.phase ?? RunnerPhase.UNSPECIFIED;
    const active = isActivePhase(phase);
    const systemManaged = runner.metadata?.labels[SYSTEM_MANAGED_LABEL] === "true";
    const hasActions = !systemManaged;
    const canStop = active;
    const info = runner.status?.connectionInfo;
    const hostname = info?.hostname;
    const osArch = info?.os && info?.arch ? `${info.os}/${info.arch}` : undefined;
    const version = info?.runnerVersion;
    const executions = runner.status?.currentExecutions ?? 0;
    const lastHeartbeat = runner.status?.lastHeartbeatAt;
    useEffect(() => {
        if (confirmingAction) {
            clearStopError();
            clearDeleteError();
        }
    }, [confirmingAction, clearStopError, clearDeleteError]);
    const handleStop = useCallback(async () => {
        try {
            const updated = await stop({
                runnerId: id,
                reason: "stopped via web console",
            });
            onActionComplete(updated, "stop");
        }
        catch {
            // error state surfaced via useStopRunner hook
        }
    }, [id, stop, onActionComplete]);
    const handleDelete = useCallback(async () => {
        try {
            const deleted = await deleteRunner(id);
            onActionComplete(deleted, "delete");
        }
        catch {
            // error state surfaced via useDeleteRunner hook
        }
    }, [id, deleteRunner, onActionComplete]);
    if (confirmingAction === "stop") {
        return (_jsx(ConfirmationRow, { message: _jsxs(_Fragment, { children: ["Stop ", _jsx("span", { className: "font-medium", children: name }), "?"] }), description: "Active executions on this runner will be interrupted.", confirmLabel: "Stop runner", isMutating: isStopping, error: stopError, onConfirm: handleStop, onCancel: onCancelConfirm }));
    }
    if (confirmingAction === "delete") {
        return (_jsx(ConfirmationRow, { message: _jsxs(_Fragment, { children: ["Delete ", _jsx("span", { className: "font-medium", children: name }), "?"] }), description: "This action is permanent. Sessions bound to this runner will fall back to auto-provisioning.", confirmLabel: "Delete permanently", isMutating: isDeleting, error: deleteError, onConfirm: handleDelete, onCancel: onCancelConfirm }));
    }
    const metaSegments = [];
    if (hostname)
        metaSegments.push(hostname);
    if (osArch)
        metaSegments.push(osArch);
    if (active)
        metaSegments.push(`${executions} exec${executions !== 1 ? "s" : ""}`);
    if (lastHeartbeat) {
        metaSegments.push(formatRelativeTime(timestampDate(lastHeartbeat)));
    }
    return (_jsxs("div", { role: "listitem", className: cn("flex items-start gap-3 rounded-lg border border-border-muted px-3 py-2.5", "hover:border-border transition-colors", !active && "opacity-60"), children: [_jsx(RunnerIcon, { size: 16, className: "mt-0.5" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "truncate text-sm font-medium text-foreground", children: name }), systemManaged && (_jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-[0.6rem] font-medium text-muted-foreground", children: "System" })), _jsx(PhaseBadge, { phase: phase })] }), metaSegments.length > 0 && (_jsx("p", { className: "mt-0.5 truncate text-[0.65rem] text-muted-foreground", children: metaSegments.join(" \u00b7 ") }))] }), hasActions && (_jsx(ActionMenu, { canStop: canStop, onStop: () => onRequestConfirm("stop"), onDelete: () => onRequestConfirm("delete"), runnerName: name }))] }));
}
// ---------------------------------------------------------------------------
// ConfirmationRow (internal)
// ---------------------------------------------------------------------------
function ConfirmationRow({ message, description, confirmLabel, isMutating, error, onConfirm, onCancel, }) {
    return (_jsxs("div", { role: "listitem", className: "rounded-lg border border-destructive/30 bg-destructive-subtle px-3 py-2.5", children: [_jsx("p", { className: "text-xs text-foreground", children: message }), _jsx("p", { className: "mt-0.5 text-[0.65rem] text-muted-foreground", children: description }), error && (_jsx("p", { className: "mt-1 text-[0.65rem] text-destructive", role: "alert", children: getUserMessage(error) })), _jsxs("div", { className: "mt-2 flex items-center gap-1.5", children: [_jsxs("button", { type: "button", onClick: onConfirm, disabled: isMutating, className: cn("inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-xs font-medium", "bg-destructive text-destructive-foreground hover:bg-destructive-hover", "disabled:pointer-events-none disabled:opacity-50"), children: [isMutating && _jsx(SpinnerIcon, {}), confirmLabel] }), _jsx("button", { type: "button", onClick: onCancel, disabled: isMutating, className: cn("rounded-md px-2.5 py-1 text-xs", "text-muted-foreground hover:text-foreground hover:bg-accent-hover", "disabled:pointer-events-none disabled:opacity-50"), children: "Cancel" })] })] }));
}
// ---------------------------------------------------------------------------
// ActionMenu (internal)
// ---------------------------------------------------------------------------
function ActionMenu({ canStop, onStop, onDelete, runnerName, }) {
    const [open, setOpen] = useState(false);
    const containerRef = useRef(null);
    const triggerRef = useRef(null);
    useEffect(() => {
        if (!open)
            return;
        function handlePointerDown(e) {
            if (containerRef.current &&
                !containerRef.current.contains(e.target)) {
                setOpen(false);
            }
        }
        function handleKeyDown(e) {
            if (e.key === "Escape") {
                setOpen(false);
                triggerRef.current?.focus();
            }
        }
        document.addEventListener("mousedown", handlePointerDown);
        document.addEventListener("keydown", handleKeyDown);
        return () => {
            document.removeEventListener("mousedown", handlePointerDown);
            document.removeEventListener("keydown", handleKeyDown);
        };
    }, [open]);
    return (_jsxs("div", { ref: containerRef, className: "relative", children: [_jsx("button", { ref: triggerRef, type: "button", onClick: () => setOpen((prev) => !prev), "aria-label": `Actions for ${runnerName}`, "aria-haspopup": "menu", "aria-expanded": open, className: cn("shrink-0 rounded p-1", "text-muted-foreground hover:text-foreground hover:bg-accent-hover", "transition-colors"), children: _jsx(MoreVerticalIcon, {}) }), open && (_jsxs("div", { role: "menu", "aria-label": `Actions for ${runnerName}`, className: cn("absolute right-0 top-full z-10 mt-1", "min-w-[10rem] rounded-md border border-border bg-popover py-1 shadow-md"), children: [canStop && (_jsxs("button", { type: "button", role: "menuitem", onClick: () => {
                            setOpen(false);
                            onStop();
                        }, className: cn("flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs", "text-foreground hover:bg-accent-hover transition-colors"), children: [_jsx(StopIcon, {}), "Stop runner"] })), _jsxs("button", { type: "button", role: "menuitem", onClick: () => {
                            setOpen(false);
                            onDelete();
                        }, className: cn("flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs", "text-destructive-muted hover:text-destructive hover:bg-destructive-subtle", "transition-colors"), children: [_jsx(TrashIcon, {}), "Delete runner"] })] }))] }));
}
// ---------------------------------------------------------------------------
// PhaseBadge (internal)
// ---------------------------------------------------------------------------
function PhaseBadge({ phase }) {
    const starting = phase === RunnerPhase.STARTING;
    return (_jsxs("span", { className: "inline-flex shrink-0 items-center gap-1", children: [starting ? (_jsx("span", { className: "inline-block h-2.5 w-2.5 animate-spin rounded-full border border-primary border-t-transparent", "aria-hidden": "true" })) : (_jsx("span", { className: `inline-block h-1.5 w-1.5 rounded-full ${phaseDotColor(phase)}`, "aria-hidden": "true" })), _jsx("span", { className: cn("text-[0.65rem]", starting ? "text-primary" : "text-muted-foreground"), children: phaseLabel(phase) })] }));
}
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
function phaseThenName(a, b) {
    const pa = a.status?.phase ?? RunnerPhase.UNSPECIFIED;
    const pb = b.status?.phase ?? RunnerPhase.UNSPECIFIED;
    const order = PHASE_SORT_ORDER[pa] - PHASE_SORT_ORDER[pb];
    if (order !== 0)
        return order;
    return (a.metadata?.name ?? "").localeCompare(b.metadata?.name ?? "");
}
function formatRelativeTime(date) {
    const diffMs = Date.now() - date.getTime();
    if (diffMs < 0)
        return "just now";
    const seconds = Math.floor(diffMs / 1000);
    if (seconds < 60)
        return "just now";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60)
        return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24)
        return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    if (days < 30)
        return `${days}d ago`;
    return date.toLocaleDateString(undefined, {
        month: "short",
        day: "numeric",
        year: "numeric",
    });
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function RunnerIcon({ size = 14, className, }) {
    return (_jsxs("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", className: cn("shrink-0 text-muted-foreground", className), 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 MoreVerticalIcon() {
    return (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true", children: [_jsx("circle", { cx: "8", cy: "3", r: "1.5" }), _jsx("circle", { cx: "8", cy: "8", r: "1.5" }), _jsx("circle", { cx: "8", cy: "13", r: "1.5" })] }));
}
function StopIcon() {
    return (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("circle", { cx: "8", cy: "8", r: "6" }), _jsx("rect", { x: "5.5", y: "5.5", width: "5", height: "5", rx: "0.5" })] }));
}
function TrashIcon() {
    return (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M2.5 4h11M5.5 4V2.5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1V4" }), _jsx("path", { d: "M12.5 4v9a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1V4" }), _jsx("line", { x1: "6.5", y1: "7", x2: "6.5", y2: "11" }), _jsx("line", { x1: "9.5", y1: "7", x2: "9.5", y2: "11" })] }));
}
function SpinnerIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "animate-spin", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
//# sourceMappingURL=RunnerListPanel.js.map