"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import "@xyflow/react/dist/style.css";
import { useCallback, useMemo, useEffect, useRef, useState } from "react";
import {
  ReactFlow,
  Controls,
  Background,
  BackgroundVariant,
  MiniMap,
  Panel,
  useNodesState,
  useEdgesState,
  addEdge,
  applyNodeChanges,
  applyEdgeChanges,
  ConnectionMode,
  MarkerType
} from "@xyflow/react";
import { StartNode, EndNode, UserTaskNode, AutomatedNode, SubWorkflowNode, WaitForSignalNode, WaitForTimerNode, ParallelForkNode, ParallelJoinNode } from "./nodes/index.js";
import { WorkflowTransitionEdge } from "./WorkflowTransitionEdge.js";
import { STATUS_COLORS } from "../lib/status-colors.js";
import { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
import { Edit3 } from "lucide-react";
import { useTheme } from "@open-mercato/ui/theme";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function WorkflowGraphImpl({
  initialNodes = [],
  initialEdges = [],
  onNodesChange: onNodesChangeProp,
  onEdgesChange: onEdgesChangeProp,
  onNodeClick: onNodeClickProp,
  onEdgeClick: onEdgeClickProp,
  onConnect: onConnectProp,
  editable = false,
  className = "",
  height = "600px"
}) {
  const t = useT();
  const [nodes, setNodes] = useNodesState(initialNodes);
  const [edges, setEdges] = useEdgesState(initialEdges);
  const latestNodesRef = useRef(nodes);
  latestNodesRef.current = nodes;
  const latestEdgesRef = useRef(edges);
  latestEdgesRef.current = edges;
  const { resolvedTheme } = useTheme();
  const isDark = resolvedTheme === "dark";
  const backgroundDotColor = isDark ? "#374151" : "#e5e7eb";
  const [isCompactViewport, setIsCompactViewport] = useState(false);
  useEffect(() => {
    if (typeof window === "undefined") return;
    const mediaQuery = window.matchMedia("(max-width: 1279px)");
    const updateViewportMode = () => setIsCompactViewport(mediaQuery.matches);
    updateViewportMode();
    mediaQuery.addEventListener("change", updateViewportMode);
    return () => {
      mediaQuery.removeEventListener("change", updateViewportMode);
    };
  }, []);
  useEffect(() => {
    setNodes(initialNodes);
  }, [initialNodes, setNodes]);
  useEffect(() => {
    setEdges(initialEdges);
  }, [initialEdges, setEdges]);
  const onConnect = useCallback(
    (connection) => {
      if (onConnectProp) {
        onConnectProp(connection);
      } else {
        const newEdge = {
          ...connection,
          type: "workflowTransition",
          animated: false,
          markerEnd: {
            type: MarkerType.ArrowClosed,
            width: 16,
            height: 16,
            color: "#9ca3af"
          }
        };
        setEdges((eds) => addEdge(newEdge, eds));
      }
    },
    [setEdges, onConnectProp]
  );
  const handleNodesChange = useCallback(
    (changes) => {
      const nextNodes = applyNodeChanges(changes, latestNodesRef.current);
      setNodes(nextNodes);
      if (onNodesChangeProp) {
        onNodesChangeProp(nextNodes);
      }
    },
    [setNodes, onNodesChangeProp]
  );
  const handleEdgesChange = useCallback(
    (changes) => {
      const nextEdges = applyEdgeChanges(changes, latestEdgesRef.current);
      setEdges(nextEdges);
      if (onEdgesChangeProp) {
        onEdgesChangeProp(nextEdges);
      }
    },
    [setEdges, onEdgesChangeProp]
  );
  const nodeTypes = useMemo(
    () => ({
      start: StartNode,
      end: EndNode,
      userTask: UserTaskNode,
      automated: AutomatedNode,
      subWorkflow: SubWorkflowNode,
      waitForSignal: WaitForSignalNode,
      waitForTimer: WaitForTimerNode,
      parallelFork: ParallelForkNode,
      parallelJoin: ParallelJoinNode
    }),
    []
  );
  const edgeTypes = useMemo(
    () => ({
      workflowTransition: WorkflowTransitionEdge
    }),
    []
  );
  return /* @__PURE__ */ jsx("div", { className: `workflow-graph-container ${className}`, style: { height }, children: /* @__PURE__ */ jsxs(
    ReactFlow,
    {
      nodes,
      edges,
      nodeTypes,
      edgeTypes,
      onNodesChange: handleNodesChange,
      onEdgesChange: handleEdgesChange,
      onConnect: editable ? onConnect : void 0,
      onNodeClick: onNodeClickProp,
      onEdgeClick: onEdgeClickProp,
      connectionMode: ConnectionMode.Loose,
      fitView: true,
      fitViewOptions: {
        padding: 0.2,
        maxZoom: isCompactViewport ? 0.9 : 1
      },
      minZoom: 0.1,
      maxZoom: 2,
      defaultEdgeOptions: {
        type: "workflowTransition",
        animated: false,
        markerEnd: {
          type: MarkerType.ArrowClosed,
          width: 16,
          height: 16,
          color: "#9ca3af"
        }
      },
      nodesDraggable: editable,
      nodesConnectable: editable,
      elementsSelectable: editable,
      proOptions: { hideAttribution: true },
      children: [
        /* @__PURE__ */ jsx(
          Background,
          {
            variant: BackgroundVariant.Dots,
            gap: 16,
            size: 1,
            color: backgroundDotColor
          }
        ),
        /* @__PURE__ */ jsx(
          Controls,
          {
            showZoom: true,
            showFitView: true,
            showInteractive: false,
            position: isCompactViewport ? "bottom-right" : "top-right",
            className: `!bg-card !border-border !shadow-md [&>button]:!bg-card [&>button]:!border-border [&>button]:!fill-foreground [&>button:hover]:!bg-muted ${isCompactViewport ? "scale-90 origin-bottom-right" : ""}`
          }
        ),
        !isCompactViewport && /* @__PURE__ */ jsx(
          MiniMap,
          {
            nodeStrokeWidth: 3,
            nodeColor: (node) => {
              const status = node.data?.status || "not_started";
              return STATUS_COLORS[status]?.hex || STATUS_COLORS.not_started.hex;
            },
            maskColor: "rgba(0, 0, 0, 0.1)",
            position: "bottom-left",
            className: "!bg-card !border !border-border !rounded-lg"
          }
        ),
        !editable && !isCompactViewport && /* @__PURE__ */ jsx(Panel, { position: "top-left", style: { margin: 10 }, children: /* @__PURE__ */ jsx("div", { className: "bg-card rounded-lg shadow-sm border border-border px-4 py-2", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground font-medium", children: t("workflows.graph.visualization") }) }) }),
        editable && !isCompactViewport && /* @__PURE__ */ jsx(Panel, { position: "top-left", style: { margin: 10 }, children: /* @__PURE__ */ jsx(Alert, { variant: "info", icon: /* @__PURE__ */ jsx(Edit3, { "aria-hidden": "true" }), className: "max-w-sm", children: /* @__PURE__ */ jsx(AlertDescription, { className: "font-medium", children: t("workflows.graph.editModeInfo") }) }) })
      ]
    }
  ) });
}
export {
  WorkflowGraphImpl as default
};
//# sourceMappingURL=WorkflowGraphImpl.js.map
