"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { memo, useMemo, useState } from "react";
import { MessageType, SubAgentStatus, } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
import { useRenderTracer } from "../internal/dev";
import { cn } from "@stigmer/theme";
import { formatDuration } from "./ToolCallDetail";
import { MessageEntry } from "./MessageEntry";
import { ToolCallGroup } from "./ToolCallGroup";
import { TodoList, TodoInProgressIcon, findActiveTodo, todoCompletionSummary, } from "./TodoList";
/**
 * Renders a sub-agent execution as a nested mini-thread inside the
 * parent conversation.
 *
 * When `collapsible` is `true` (default), the component renders as a
 * bordered card with a clickable summary row. Cards start collapsed
 * — the summary row shows status, subject, and duration at a glance.
 * Users click to expand and see the nested messages and tool calls.
 *
 * Visually distinguished from {@link ToolCallGroup} via a left
 * accent border and bot icon, signaling delegated sub-agent work.
 *
 * When `collapsible` is `false`, the component renders flat content
 * without a toggle — suitable for embedding inside a parent that
 * already provides expand/collapse (e.g. {@link ToolCallItem}).
 *
 * Composes {@link MessageEntry} and {@link ToolCallGroup} to display
 * the sub-agent's internal messages and tool calls — the same
 * building blocks used by the top-level {@link MessageThread}.
 *
 * Wrapped in `React.memo` — structural sharing (T04) preserves the
 * `SubAgentExecution` reference when the sub-agent's state is
 * unchanged, so completed sub-agents skip re-renders entirely.
 *
 * @example
 * ```tsx
 * // Standalone collapsible card (default)
 * <SubAgentSection subAgentExecution={sub} />
 *
 * // Flat layout inside a parent expand/collapse
 * <SubAgentSection subAgentExecution={sub} collapsible={false} />
 * ```
 */
export const SubAgentSection = memo(function SubAgentSection({ subAgentExecution: sub, collapsible = true, className, }) {
    useRenderTracer("SubAgentSection", { status: sub.status, name: sub.name });
    const duration = formatDuration(sub.startedAt, sub.completedAt);
    const statusInfo = SUB_AGENT_STATUS_MAP[sub.status];
    const StatusIcon = statusInfo.icon;
    const isFailed = sub.status === SubAgentStatus.SUB_AGENT_FAILED;
    const threadItems = buildSubAgentThreadItems(sub.id, sub.messages);
    const displayLabel = sub.subject || sub.name;
    if (!collapsible) {
        return (_jsx(FlatContent, { sub: sub, statusInfo: statusInfo, StatusIcon: StatusIcon, duration: duration, isFailed: isFailed, threadItems: threadItems, className: className }));
    }
    return (_jsx(CollapsibleCard, { sub: sub, statusInfo: statusInfo, displayLabel: displayLabel, duration: duration, isFailed: isFailed, threadItems: threadItems, className: className }));
});
function CollapsibleCard({ sub, statusInfo, displayLabel, duration, isFailed, threadItems, className, }) {
    const [expanded, setExpanded] = useState(false);
    const handleToggle = () => {
        setExpanded((v) => !v);
    };
    const hasTodos = sub.todos != null && Object.keys(sub.todos).length > 0;
    const isRunning = sub.status === SubAgentStatus.SUB_AGENT_IN_PROGRESS;
    const isCompleted = sub.status === SubAgentStatus.SUB_AGENT_COMPLETED;
    const activeTodo = useMemo(() => findActiveTodo(sub.todos), [sub.todos]);
    const completionLabel = useMemo(() => (isCompleted && hasTodos ? todoCompletionSummary(sub.todos) : null), [sub.todos, isCompleted, hasTodos]);
    const collapsedPreview = isRunning && activeTodo
        ? activeTodo.content
        : isCompleted && completionLabel
            ? completionLabel
            : null;
    const ariaLabel = `Sub-agent: ${displayLabel}, ${statusInfo.label}`;
    return (_jsxs("div", { role: "group", "aria-label": ariaLabel, className: cn("rounded-md border border-border border-l-2 border-l-primary/30 bg-muted-faint", className), children: [_jsxs("button", { type: "button", "aria-expanded": expanded, onClick: handleToggle, className: cn("flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs text-muted-foreground transition-colors", "hover:bg-muted-subtle", "cursor-pointer"), children: [_jsx("span", { className: "shrink-0 text-primary-muted", "aria-hidden": "true", children: _jsx(BotIcon, {}) }), _jsx("span", { className: "min-w-0 flex-1 truncate", children: displayLabel }), _jsx("span", { className: cn("shrink-0 rounded px-1 py-0.5 text-[10px] font-medium leading-none", statusInfo.badgeClass), children: statusInfo.label }), duration && (_jsx("span", { className: "shrink-0 tabular-nums text-muted-foreground", children: duration })), _jsx(ChevronIcon, { expanded: expanded })] }), collapsedPreview && !expanded && (_jsxs("div", { className: "flex items-center gap-1.5 px-2.5 pb-1.5 text-xs text-muted-foreground", children: [_jsx("span", { className: "ml-[20px] shrink-0", "aria-hidden": "true", children: isRunning && activeTodo ? (_jsx(TodoInProgressIcon, {})) : (_jsx(TodoCompletedSmallIcon, {})) }), _jsx("span", { className: "min-w-0 truncate", children: collapsedPreview })] })), _jsx("div", { className: cn("grid transition-[grid-template-rows] duration-150 ease-out", expanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]"), children: _jsx("div", { className: "overflow-hidden", children: expanded && (_jsx("div", { className: "border-t border-border-muted px-2.5 pb-2 pt-1.5", children: _jsx(SubAgentThreadContent, { threadItems: threadItems, todos: sub.todos, input: sub.input, isFailed: isFailed, error: sub.error }) })) }) })] }));
}
function FlatContent({ sub, statusInfo, StatusIcon, duration, isFailed, threadItems, className, }) {
    return (_jsxs("div", { className: cn("border-l-2 border-primary/20 pl-3", className), children: [_jsxs("div", { className: "flex flex-wrap items-center gap-x-2 gap-y-1 py-1.5 text-xs", children: [_jsx("span", { className: cn("shrink-0", statusInfo.colorClass), "aria-hidden": "true", children: _jsx(StatusIcon, {}) }), _jsx("span", { className: "font-medium text-foreground", children: sub.name }), sub.subject && (_jsx("span", { className: "text-muted-foreground", children: sub.subject })), duration && (_jsx("span", { className: "tabular-nums text-muted-foreground", children: duration }))] }), _jsx(SubAgentThreadContent, { threadItems: threadItems, todos: sub.todos, input: sub.input, isFailed: isFailed, error: sub.error })] }));
}
function SubAgentThreadContent({ threadItems, todos, input, isFailed, error, }) {
    const hasTodos = todos != null && Object.keys(todos).length > 0;
    return (_jsxs(_Fragment, { children: [hasTodos && _jsx(TodoList, { todos: todos, className: "pb-1" }), input && (_jsx("div", { className: "border-l-2 border-muted-foreground/25 pl-2.5 text-xs text-muted-foreground whitespace-pre-wrap mb-1", children: input })), threadItems.length > 0 && (_jsx("div", { className: "flex flex-col gap-1 pb-1", children: threadItems.map((item) => {
                    switch (item.kind) {
                        case "message":
                            return (_jsx(MessageEntry, { message: item.message }, item.key));
                        case "tool-group":
                            return (_jsx(ToolCallGroup, { toolCalls: item.toolCalls }, item.key));
                    }
                }) })), isFailed && error && (_jsx("div", { className: "rounded-md border border-destructive/20 bg-destructive-subtle px-2 py-1.5 text-xs text-destructive", children: error }))] }));
}
function buildSubAgentThreadItems(subAgentId, messages) {
    const items = [];
    for (let i = 0; i < messages.length; i++) {
        const msg = messages[i];
        if (msg.type === MessageType.MESSAGE_TOOL)
            continue;
        items.push({ kind: "message", message: msg, key: `${subAgentId}-m${i}` });
        if (msg.type === MessageType.MESSAGE_AI && msg.toolCalls.length > 0) {
            items.push({
                kind: "tool-group",
                toolCalls: msg.toolCalls,
                key: `${subAgentId}-m${i}-tc`,
            });
        }
    }
    return items;
}
const SUB_AGENT_STATUS_MAP = {
    [SubAgentStatus.SUB_AGENT_STATUS_UNSPECIFIED]: {
        label: "Unknown",
        colorClass: "text-muted-foreground",
        badgeClass: "bg-muted text-muted-foreground",
        icon: DotIcon,
    },
    [SubAgentStatus.SUB_AGENT_PENDING]: {
        label: "Pending",
        colorClass: "text-muted-foreground",
        badgeClass: "bg-muted text-muted-foreground",
        icon: DotIcon,
    },
    [SubAgentStatus.SUB_AGENT_IN_PROGRESS]: {
        label: "Running",
        colorClass: "text-foreground",
        badgeClass: "bg-muted text-foreground",
        icon: SpinnerIcon,
    },
    [SubAgentStatus.SUB_AGENT_COMPLETED]: {
        label: "Completed",
        colorClass: "text-success",
        badgeClass: "bg-success/15 text-success",
        icon: CheckCircleIcon,
    },
    [SubAgentStatus.SUB_AGENT_FAILED]: {
        label: "Failed",
        colorClass: "text-destructive",
        badgeClass: "bg-destructive/15 text-destructive",
        icon: XCircleIcon,
    },
    [SubAgentStatus.SUB_AGENT_CANCELLED]: {
        label: "Cancelled",
        colorClass: "text-muted-foreground",
        badgeClass: "bg-muted text-muted-foreground",
        icon: XCircleIcon,
    },
};
// ---------------------------------------------------------------------------
// Inline SVG icons
// ---------------------------------------------------------------------------
function SpinnerIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", className: "animate-spin", children: _jsx("path", { d: "M6 1.5A4.5 4.5 0 1 1 1.5 6", strokeLinecap: "round" }) }));
}
function CheckCircleIcon() {
    return (_jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("path", { d: "M4 6L5.5 7.5L8 4.5" })] }));
}
function XCircleIcon() {
    return (_jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("path", { d: "M4.5 4.5L7.5 7.5M7.5 4.5L4.5 7.5" })] }));
}
function DotIcon() {
    return (_jsx("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "currentColor", children: _jsx("circle", { cx: "4", cy: "4", r: "2.5" }) }));
}
function TodoCompletedSmallIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M2.5 6L5 8.5L9.5 3.5" }) }));
}
function BotIcon() {
    return (_jsxs("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: [_jsx("rect", { x: "2", y: "6", width: "12", height: "8", rx: "2" }), _jsx("path", { d: "M5.5 10H5.51M10.5 10H10.51", strokeWidth: "2" }), _jsx("path", { d: "M8 2V6" }), _jsx("circle", { cx: "8", cy: "1.5", r: "1" }), _jsx("path", { d: "M0.5 9.5H2M14 9.5H15.5" })] }));
}
function ChevronIcon({ expanded }) {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: cn("shrink-0 text-muted-foreground transition-transform duration-150", expanded && "rotate-90"), "aria-hidden": "true", children: _jsx("path", { d: "M4.5 2.5L7.5 6L4.5 9.5" }) }));
}
//# sourceMappingURL=SubAgentSection.js.map