"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ReactFlow, Controls, MiniMap, Background, BackgroundVariant, MarkerType, useReactFlow, ReactFlowProvider, } from "@xyflow/react";
import { cn } from "@stigmer/theme";
import { WorkflowNode } from "./WorkflowNode.js";
import { CanvasTransitionEdge } from "./CanvasTransitionEdge.js";
import { CANVAS_TASK_NODE_TYPE, CANVAS_TRANSITION_EDGE_TYPE } from "./workflow-graph-conversions.js";
import { WorkflowGraphModeProvider } from "./WorkflowGraphModeContext.js";
import { useWorkflowOverviewGraph } from "./useWorkflowOverviewGraph.js";
import { WorkflowNodePopover } from "./WorkflowNodePopover.js";
const nodeTypes = {
    [CANVAS_TASK_NODE_TYPE]: WorkflowNode,
};
const edgeTypes = {
    [CANVAS_TRANSITION_EDGE_TYPE]: CanvasTransitionEdge,
};
const defaultEdgeOptions = {
    markerEnd: { type: MarkerType.ArrowClosed, width: 16, height: 16 },
};
/**
 * Read-only interactive workflow graph for the overview context.
 *
 * Renders the workflow blueprint in a React Flow canvas using the unified
 * `WorkflowNode` / `CanvasTransitionEdge` rendering system in `"overview"` mode.
 * Supports pan, zoom, minimap, and a click-to-inspect popover on task nodes.
 *
 * Designed for embedding in both the Stigmer Console and third-party
 * dashboards — no routing, auth, or app-shell dependencies (DD-004).
 *
 * @example
 * ```tsx
 * <WorkflowOverviewGraph
 *   workflow={workflow}
 *   onOpenInEditor={(taskName) => switchToEditorTab(taskName)}
 * />
 * ```
 */
export const WorkflowOverviewGraph = memo(function WorkflowOverviewGraph(props) {
    return (_jsx(ReactFlowProvider, { children: _jsx(WorkflowOverviewGraphInner, { workflow: props.workflow, onOpenInEditor: props.onOpenInEditor, nodesDraggable: props.nodesDraggable, className: props.className }) }));
});
function WorkflowOverviewGraphInner({ workflow, onOpenInEditor, nodesDraggable: draggable = false, className, }) {
    const { nodes: baseNodes, nodesWithSelection, edges, selectedTaskName, setSelectedTaskName, } = useWorkflowOverviewGraph({ workflow });
    const { fitView } = useReactFlow();
    const didFitRef = useRef(false);
    // Track drag-repositioned nodes. Keyed by node ID → position.
    // Resets when the underlying graph structure changes (workflow edited).
    const [dragPositions, setDragPositions] = useState({});
    useEffect(() => {
        setDragPositions({});
    }, [baseNodes]);
    const displayNodes = useMemo(() => {
        if (!draggable || Object.keys(dragPositions).length === 0) {
            return nodesWithSelection;
        }
        return nodesWithSelection.map((n) => {
            const pos = dragPositions[n.id];
            return pos ? { ...n, position: pos } : n;
        });
    }, [nodesWithSelection, draggable, dragPositions]);
    const handleNodesChange = useCallback((changes) => {
        if (!draggable)
            return;
        const posChanges = changes.filter((c) => c.type === "position" && "position" in c && c.position != null);
        if (posChanges.length === 0)
            return;
        setDragPositions((prev) => {
            const next = { ...prev };
            for (const c of posChanges) {
                next[c.id] = c.position;
            }
            return next;
        });
    }, [draggable]);
    const [popoverAnchor, setPopoverAnchor] = useState(null);
    const containerRef = useRef(null);
    useEffect(() => {
        if (nodesWithSelection.length > 0 && !didFitRef.current) {
            didFitRef.current = true;
            setTimeout(() => fitView({ padding: 0.15, duration: 300 }), 50);
        }
    }, [nodesWithSelection.length, fitView]);
    const handleNodeClick = useCallback((event, node) => {
        const data = node.data;
        if (data.isSentinel)
            return;
        const name = data.taskName;
        const isDeselect = name === selectedTaskName;
        if (isDeselect) {
            setSelectedTaskName(null);
            setPopoverAnchor(null);
            return;
        }
        setSelectedTaskName(name);
        const rect = containerRef.current?.getBoundingClientRect();
        if (rect) {
            setPopoverAnchor({
                x: event.clientX - rect.left,
                y: event.clientY - rect.top,
                data,
            });
        }
    }, [selectedTaskName, setSelectedTaskName]);
    const handlePaneClick = useCallback(() => {
        setSelectedTaskName(null);
        setPopoverAnchor(null);
    }, [setSelectedTaskName]);
    const handlePopoverClose = useCallback(() => {
        setSelectedTaskName(null);
        setPopoverAnchor(null);
    }, [setSelectedTaskName]);
    if (!workflow?.spec?.tasks?.length) {
        return (_jsx("div", { className: cn("flex h-full items-center justify-center text-sm text-[var(--stgm-muted-foreground,#737373)]", className), children: "No tasks to visualize" }));
    }
    if (nodesWithSelection.length === 0) {
        return (_jsx("div", { className: cn("flex h-full items-center justify-center", className), children: _jsx(GraphLoadingSkeleton, {}) }));
    }
    return (_jsx(WorkflowGraphModeProvider, { mode: "overview", children: _jsxs("div", { ref: containerRef, className: cn("relative h-full w-full", className), children: [_jsxs(ReactFlow, { nodes: displayNodes, edges: edges, onNodesChange: draggable ? handleNodesChange : undefined, nodeTypes: nodeTypes, edgeTypes: edgeTypes, defaultEdgeOptions: defaultEdgeOptions, onNodeClick: handleNodeClick, onPaneClick: handlePaneClick, nodesDraggable: draggable, nodesConnectable: false, elementsSelectable: true, panOnDrag: true, zoomOnScroll: true, fitView: false, minZoom: 0.2, maxZoom: 2, proOptions: { hideAttribution: true }, children: [_jsx(Background, { variant: BackgroundVariant.Dots, gap: 16, size: 1 }), _jsx(Controls, { showInteractive: false }), _jsx(MiniMap, { pannable: true, zoomable: true })] }), popoverAnchor && (_jsx(WorkflowNodePopover, { data: popoverAnchor.data, x: popoverAnchor.x, y: popoverAnchor.y, onClose: handlePopoverClose, onOpenInEditor: onOpenInEditor }))] }) }));
}
function GraphLoadingSkeleton() {
    return (_jsxs("div", { className: "flex flex-col items-center gap-3", children: [_jsx("div", { className: "h-8 w-8 animate-pulse rounded-full bg-[var(--stgm-muted,#e5e5e5)]" }), _jsx("div", { className: "h-3 w-24 animate-pulse rounded bg-[var(--stgm-muted,#e5e5e5)]" }), _jsxs("div", { className: "mt-2 flex gap-4", children: [_jsx("div", { className: "h-10 w-32 animate-pulse rounded-md bg-[var(--stgm-muted,#e5e5e5)]" }), _jsx("div", { className: "h-10 w-32 animate-pulse rounded-md bg-[var(--stgm-muted,#e5e5e5)]" })] })] }));
}
//# sourceMappingURL=WorkflowOverviewGraph.js.map