'use client';

import * as React from 'react';
import {
  BaseEdge,
  getBezierPath,
  type EdgeProps,
} from '@xyflow/react';
import type { NodeStatus } from './types';

/**
 * Data payload carried on an xyflow edge rendered by {@link WorkflowEdge}.
 * `sourceStatus` is layered on by the canvas status overlay so the edge can
 * animate while its source node is running (or has just succeeded).
 */
export interface WorkflowEdgeData {
  connectionType?: string;
  /** Runtime status of the source node (drives the animated flow). */
  sourceStatus?: NodeStatus;
  [key: string]: unknown;
}

const ANIMATED: ReadonlySet<NodeStatus> = new Set(['running', 'success']);

/**
 * Custom workflow edge: a bezier connector that animates a dashed flow when
 * its source node is running or has succeeded (so live runs visibly "flow").
 */
export function WorkflowEdge({
  id,
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  data,
  markerEnd,
  selected,
}: EdgeProps) {
  const [edgePath] = getBezierPath({
    sourceX,
    sourceY,
    targetX,
    targetY,
    sourcePosition,
    targetPosition,
  });

  const d = data as WorkflowEdgeData | undefined;
  const animated = d?.sourceStatus ? ANIMATED.has(d.sourceStatus) : false;

  return (
    <BaseEdge
      id={id}
      path={edgePath}
      markerEnd={markerEnd}
      className={animated ? 'workflow-edge--animated' : undefined}
      style={{
        strokeWidth: selected ? 2.5 : 1.5,
        stroke: selected ? '#2563eb' : '#94a3b8',
      }}
    />
  );
}
