"use client";

import { BaseEdge, getSmoothStepPath, type EdgeProps } from "@xyflow/react";
import { buildTraceFlowCorridorPath } from "./traceFlowEdgeLayout";

export type TraceFlowEdgeData = {
  offset?: number;
  pathMode?: "smooth" | "corridor";
  corridorY?: number;
  corridorEntryOffset?: number;
  corridorExitOffset?: number;
  corridorBranchOffset?: number;
};

export const TraceFlowEdge = ({
  id,
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  style,
  markerEnd,
  data,
}: EdgeProps) => {
  const edgeData = data as TraceFlowEdgeData | undefined;
  const offset = edgeData?.offset ?? 0;

  const path =
    edgeData?.pathMode === "corridor" && edgeData.corridorY != null
      ? buildTraceFlowCorridorPath(
          sourceX,
          sourceY,
          targetX,
          targetY,
          edgeData.corridorY,
          edgeData.corridorEntryOffset,
          edgeData.corridorExitOffset,
          edgeData.corridorBranchOffset,
        )
      : getSmoothStepPath({
          sourceX,
          sourceY,
          sourcePosition,
          targetX,
          targetY,
          targetPosition,
          borderRadius: 8,
          offset,
        })[0];

  return <BaseEdge id={id} path={path} style={style} markerEnd={markerEnd} />;
};

export const traceFlowEdgeTypes = {
  traceFlow: TraceFlowEdge,
};
