"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { memo, useCallback, useMemo, useState } from "react";
import { cn } from "@stigmer/theme";
import { deriveFailureAnalysis } from "./derive-failure-analysis";
/**
 * Collapsible panel showing failures grouped by failing task name.
 *
 * Derives failure groups from the provided execution list using
 * {@link deriveFailureAnalysis}. Each group shows the task name,
 * failure count, latest error, and expandable individual failure links.
 *
 * Renders nothing when there are no failures (no empty state).
 *
 * @example
 * ```tsx
 * <FailureAnalysisPanel
 *   executions={allExecutions}
 *   onExecutionClick={(id) => navigate(`/executions/${id}`)}
 * />
 * ```
 */
export const FailureAnalysisPanel = memo(function FailureAnalysisPanel({ executions, onExecutionClick, initialVisibleGroups = 5, className, }) {
    const groups = useMemo(() => deriveFailureAnalysis(executions), [executions]);
    const [expandedGroups, setExpandedGroups] = useState(new Set());
    const toggleGroup = useCallback((taskName) => {
        setExpandedGroups((prev) => {
            const next = new Set(prev);
            if (next.has(taskName)) {
                next.delete(taskName);
            }
            else {
                next.add(taskName);
            }
            return next;
        });
    }, []);
    const [showAll, setShowAll] = useState(false);
    if (groups.length === 0)
        return null;
    const visibleGroups = showAll ? groups : groups.slice(0, initialVisibleGroups);
    const hiddenCount = groups.length - initialVisibleGroups;
    return (_jsxs("section", { "aria-label": "Failure analysis", className: cn("rounded-lg border border-[var(--stgm-border,#d4d4d8)] bg-[var(--stgm-background,#fff)]", className), children: [_jsxs("div", { className: "flex items-center justify-between border-b border-[var(--stgm-border,#d4d4d8)] px-4 py-2.5", children: [_jsx("h3", { className: "text-xs font-semibold uppercase tracking-wider text-[var(--stgm-muted-foreground,#737373)]", children: "Recent Failures" }), _jsxs("span", { className: "text-xs tabular-nums text-[var(--stgm-destructive,#ef4444)]", children: [groups.reduce((sum, g) => sum + g.count, 0), " failed"] })] }), _jsx("div", { className: "divide-y divide-[var(--stgm-border-muted,#e5e5e5)]", children: visibleGroups.map((group) => (_jsx(FailureGroupRow, { group: group, isExpanded: expandedGroups.has(group.taskName), onToggle: toggleGroup, onExecutionClick: onExecutionClick }, group.taskName))) }), hiddenCount > 0 && !showAll && (_jsxs("button", { type: "button", onClick: () => setShowAll(true), className: "w-full border-t border-[var(--stgm-border,#d4d4d8)] px-4 py-2 text-xs font-medium text-[var(--stgm-primary,#6366f1)] transition-colors hover:bg-[var(--stgm-accent,#f5f5f5)]", children: ["Show ", hiddenCount, " more failing task", hiddenCount > 1 ? "s" : ""] }))] }));
});
// ---------------------------------------------------------------------------
// FailureGroupRow
// ---------------------------------------------------------------------------
function FailureGroupRow({ group, isExpanded, onToggle, onExecutionClick, }) {
    return (_jsxs("div", { children: [_jsxs("button", { type: "button", onClick: () => onToggle(group.taskName), "aria-expanded": isExpanded, className: "flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-[var(--stgm-accent,#f5f5f5)]", children: [_jsx(ChevronIcon, { expanded: isExpanded }), _jsxs("span", { className: "flex-1 min-w-0", children: [_jsx("span", { className: "block text-sm font-medium text-[var(--stgm-foreground,#1a1a2e)] truncate", children: group.taskName }), _jsx("span", { className: "block text-xs text-[var(--stgm-muted-foreground,#737373)] truncate", children: group.latestError || "No error message" })] }), _jsx("span", { className: "shrink-0 rounded-full bg-[var(--stgm-destructive,#ef4444)]/10 px-2 py-0.5 text-xs font-medium tabular-nums text-[var(--stgm-destructive,#ef4444)]", children: group.count })] }), isExpanded && group.instances.length > 0 && (_jsx("div", { className: "border-t border-[var(--stgm-border-muted,#e5e5e5)] bg-[var(--stgm-muted,#f4f4f5)]/30", children: group.instances.map((inst) => (_jsxs("div", { className: cn("flex items-center gap-3 px-4 py-1.5 pl-10 text-xs", onExecutionClick && "cursor-pointer hover:bg-[var(--stgm-accent-hover,#f5f5f5)]"), role: onExecutionClick ? "link" : undefined, tabIndex: onExecutionClick ? 0 : undefined, onClick: onExecutionClick ? () => onExecutionClick(inst.executionId) : undefined, onKeyDown: onExecutionClick
                        ? (e) => {
                            if (e.key === "Enter" || e.key === " ") {
                                e.preventDefault();
                                onExecutionClick(inst.executionId);
                            }
                        }
                        : undefined, children: [_jsx("span", { className: "text-[var(--stgm-foreground,#1a1a2e)] truncate flex-1", children: inst.executionName || inst.executionId }), inst.failedAt && (_jsx("time", { className: "shrink-0 text-[var(--stgm-muted-foreground,#737373)]", dateTime: inst.failedAt.toISOString(), children: inst.failedAt.toLocaleDateString() }))] }, inst.executionId))) }))] }));
}
// ---------------------------------------------------------------------------
// Chevron icon
// ---------------------------------------------------------------------------
function ChevronIcon({ expanded }) {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", className: cn("shrink-0 text-[var(--stgm-muted-foreground,#737373)] transition-transform duration-150", expanded && "rotate-90"), children: _jsx("path", { d: "M4.5 2.5L8 6L4.5 9.5" }) }));
}
//# sourceMappingURL=FailureAnalysisPanel.js.map