"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { memo, useCallback, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { Tabs } from "../../tabs/Tabs.js";
import { useExecutionTaskDetail } from "./useExecutionTaskDetail.js";
import { formatDuration, formatMicroUsd, formatTokenCount } from "../format-utils.js";
import { SummaryTab } from "./SummaryTab.js";
import { InputOutputTab } from "./InputOutputTab.js";
import { ErrorTab } from "./ErrorTab.js";
import { RetriesTab } from "./RetriesTab.js";
import { AgentCallTab } from "./AgentCallTab.js";
import { EventLogTab } from "./EventLogTab.js";
import { WorkflowExecutionApprovalCard } from "../WorkflowExecutionApprovalCard.js";
import { WorkflowTaskApprovalCard } from "../WorkflowTaskApprovalCard.js";
import { WorkflowTaskApprovalSummary } from "../WorkflowTaskApprovalSummary.js";
/** Compute the system-suggested tab from the current task detail (DD-003). */
function deriveAutoTab(detail) {
    if (!detail)
        return "summary";
    if (detail.status === "failed" && detail.error)
        return "error";
    if (detail.status === "waiting_approval")
        return "approval";
    return "summary";
}
/**
 * Runtime inspector panel for workflow execution tasks.
 *
 * Displays rich per-task detail in a tabbed interface when a task node
 * is selected in the execution graph. Tabs are shown contextually based
 * on available data.
 *
 * Designed for embedding in both the Stigmer Console and third-party
 * dashboards — no routing, auth, or app-shell dependencies (DD-004).
 *
 * @example
 * ```tsx
 * <ExecutionInspector
 *   selectedTaskName={selectedTask}
 *   events={events}
 *   taskStates={taskStates}
 *   taskSnapshots={execution?.status?.tasks}
 *   onNavigateToAgentExecution={(id) => router.push(`/sessions/${id}`)}
 * />
 * ```
 */
export const ExecutionInspector = memo(function ExecutionInspector({ selectedTaskName, events, taskStates, taskSnapshots, onNavigateToAgentExecution, pendingApprovals, onSubmitApproval, approvalSubmittingToolCallIds, approvalErrorsByToolCallId, onSubmitTaskApproval, taskApprovalSubmittingTaskNames, taskApprovalErrorsByTaskName, className, }) {
    const { detail } = useExecutionTaskDetail({
        selectedTaskName,
        events,
        taskStates,
        taskSnapshots,
    });
    const [activeTab, setActiveTab] = useState(() => deriveAutoTab(detail));
    const [prevSelectedTask, setPrevSelectedTask] = useState(selectedTaskName);
    const [prevStatus, setPrevStatus] = useState(detail?.status);
    const userPickedTabRef = useRef(false);
    // Synchronous tab reset when the selected task changes.
    // React's "adjusting state when a prop changes" pattern — runs during
    // render so the correct tab is committed to the DOM on the first paint.
    if (selectedTaskName !== prevSelectedTask) {
        setPrevSelectedTask(selectedTaskName);
        setPrevStatus(detail?.status);
        userPickedTabRef.current = false;
        setActiveTab(deriveAutoTab(detail));
    }
    // Synchronous auto-select on status transition (same task only).
    // Navigates to Error/Approval when a live execution transitions.
    if (selectedTaskName === prevSelectedTask && detail?.status !== prevStatus) {
        setPrevStatus(detail?.status);
        if (!userPickedTabRef.current) {
            if (detail?.status === "failed" && detail.error) {
                setActiveTab("error");
            }
            else if (detail?.status === "waiting_approval") {
                setActiveTab("approval");
            }
        }
    }
    const handleTabChange = useCallback((tabId) => {
        userPickedTabRef.current = true;
        setActiveTab(tabId);
    }, []);
    if (!selectedTaskName || !detail) {
        return (_jsxs("div", { className: cn("flex flex-1 flex-col items-center justify-center px-4 py-6 text-center", className), children: [_jsx(SelectNodeIcon, {}), _jsx("p", { className: "mt-2 text-xs text-[var(--stgm-muted-foreground,#737373)]", children: "Click a node to view execution details" })] }));
    }
    // Filter pending approvals relevant to the selected task (match by childExecutionId)
    const taskApprovals = pendingApprovals?.filter((pa) => pa.childAgentExecutionId === detail.agentCall?.childExecutionId) ?? [];
    const tabs = buildVisibleTabs(detail, taskApprovals.length);
    const effectiveTab = tabs.some((t) => t.id === activeTab) ? activeTab : "summary";
    const BZ = BigInt(0);
    return (_jsxs("div", { className: cn("flex h-full flex-col", className), children: [_jsxs("div", { className: "flex flex-col gap-1 border-b border-[var(--stgm-border,#e5e5e5)] px-3 py-2.5", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("h3", { className: "min-w-0 flex-1 truncate text-sm font-semibold text-[var(--stgm-foreground,#1a1a2e)]", children: detail.taskName }), _jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: detail.displayName })] }), _jsxs("div", { className: "flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px]", children: [_jsx(StatusBadge, { status: detail.status }), detail.summary.durationMs > 0 && (_jsx("span", { className: "tabular-nums text-muted-foreground", children: formatDuration(detail.summary.durationMs) })), detail.summary.costMicros > BZ && (_jsx("span", { className: "tabular-nums text-muted-foreground", children: formatMicroUsd(detail.summary.costMicros) })), detail.summary.totalTokens > BZ && (_jsxs("span", { className: "tabular-nums text-muted-foreground", children: [formatTokenCount(detail.summary.totalTokens), " tok"] }))] })] }), _jsx(Tabs, { tabs: tabs, activeTab: effectiveTab, onTabChange: handleTabChange, "aria-label": "Task execution details", className: "min-h-0 flex-1", children: _jsxs("div", { className: "h-full min-h-0 overflow-y-auto px-3 py-3", children: [effectiveTab === "summary" && _jsx(SummaryTab, { summary: detail.summary }), effectiveTab === "input" && _jsx(InputOutputTab, { data: detail.input, label: "Input" }), effectiveTab === "output" && _jsx(InputOutputTab, { data: detail.output, label: "Output" }), effectiveTab === "error" && detail.error && (_jsx(ErrorTab, { error: detail.error, childExecutionId: detail.agentCall?.childExecutionId, onNavigateToAgentExecution: onNavigateToAgentExecution })), effectiveTab === "retries" && detail.retries && _jsx(RetriesTab, { retries: detail.retries }), effectiveTab === "agent" && detail.agentCall && (_jsx(AgentCallTab, { agentCall: detail.agentCall, taskStatus: detail.status, isTabActive: effectiveTab === "agent", onNavigateToAgentExecution: onNavigateToAgentExecution })), effectiveTab === "approval" && taskApprovals.length > 0 && onSubmitApproval && (_jsx("div", { className: "space-y-2", children: taskApprovals.map((pa) => {
                                const toolCallId = pa.approval?.toolCallId ?? "";
                                return (_jsx(WorkflowExecutionApprovalCard, { prompt: pa.approval?.message || `Tool "${pa.approval?.toolName}" requires approval`, toolCallId: toolCallId, approvers: [], timeoutSeconds: 0, onSubmitApproval: onSubmitApproval, isSubmitting: approvalSubmittingToolCallIds?.has(toolCallId) ?? false, error: approvalErrorsByToolCallId?.get(toolCallId) ?? null }, toolCallId || pa.childAgentExecutionId));
                            }) })), effectiveTab === "approval" && detail.approval && (detail.status === "waiting_approval" && onSubmitTaskApproval ? (
                        // Gate still awaiting a decision — collect one.
                        _jsx(WorkflowTaskApprovalCard, { taskName: detail.taskName, prompt: detail.approval.prompt, outcomes: detail.approval.outcomes, formSchema: detail.approval.formSchema ?? undefined, onSubmit: onSubmitTaskApproval, isSubmitting: taskApprovalSubmittingTaskNames?.has(detail.taskName) ?? false, error: taskApprovalErrorsByTaskName?.get(detail.taskName) ?? null })) : (
                        // Gate resolved — present the captured decision read-only so a
                        // settled gate is never offered for a second decision.
                        _jsx(WorkflowTaskApprovalSummary, { taskName: detail.taskName, prompt: detail.approval.prompt, outcomes: detail.approval.outcomes, decision: detail.approval.decision }))), effectiveTab === "events" && _jsx(EventLogTab, { events: detail.eventLog })] }) })] }));
});
// ---------------------------------------------------------------------------
// Tab visibility
// ---------------------------------------------------------------------------
function buildVisibleTabs(detail, approvalCount) {
    const tabs = [{ id: "summary", label: "Summary" }];
    if (detail.input)
        tabs.push({ id: "input", label: "Input" });
    if (detail.output)
        tabs.push({ id: "output", label: "Output" });
    if (detail.error)
        tabs.push({ id: "error", label: "Error" });
    if (detail.retries && detail.retries.attempts.length > 1) {
        tabs.push({ id: "retries", label: "Retries", badge: detail.retries.attempts.length });
    }
    if (detail.agentCall)
        tabs.push({ id: "agent", label: "Agent" });
    if (approvalCount > 0 || detail.approval) {
        tabs.push({ id: "approval", label: "Approval", badge: approvalCount || undefined });
    }
    tabs.push({ id: "events", label: "Events", badge: detail.eventLog.length });
    return tabs;
}
// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------
const STATUS_COLORS = {
    pending: "bg-[var(--stgm-muted,#e5e5e5)] text-[var(--stgm-muted-foreground,#737373)]",
    running: "bg-[var(--stgm-primary,#6366f1)]/10 text-[var(--stgm-primary,#6366f1)]",
    completed: "bg-[var(--stgm-success,#22c55e)]/10 text-[var(--stgm-success,#22c55e)]",
    failed: "bg-[var(--stgm-destructive,#ef4444)]/10 text-[var(--stgm-destructive,#ef4444)]",
    skipped: "bg-[var(--stgm-muted,#e5e5e5)] text-[var(--stgm-muted-foreground,#737373)]",
    retrying: "bg-[var(--stgm-muted,#e5e5e5)] text-[var(--stgm-muted-foreground,#737373)]",
    waiting_approval: "bg-[var(--stgm-warning,#f59e0b)]/10 text-[var(--stgm-warning,#f59e0b)]",
};
function StatusBadge({ status }) {
    return (_jsx("span", { className: cn("rounded-full px-2 py-0.5 text-[10px] font-medium", STATUS_COLORS[status]), children: status.replace(/_/g, " ") }));
}
function SelectNodeIcon() {
    return (_jsxs("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", className: "text-[var(--stgm-muted-foreground,#737373)]", "aria-hidden": "true", children: [_jsx("rect", { x: "2", y: "2", width: "16", height: "16", rx: "3" }), _jsx("path", { d: "M7 10h6M10 7v6" })] }));
}
//# sourceMappingURL=ExecutionInspector.js.map