import { Handle, Position, type NodeProps } from "@xyflow/react";
import { NODE_KINDS } from "./nodeCatalog";

export type NodeStatus = "idle" | "running" | "done" | "error";

// 自定义节点卡：左色条按类型、状态点、类型徽标 + 摘要。
export function TypedNode({ data, selected }: NodeProps) {
  const d = data as { kind: string; label?: string; status?: NodeStatus; summary?: string };
  const k = NODE_KINDS[d.kind] ?? NODE_KINDS.output;
  const status = d.status ?? "idle";
  const dot =
    status === "running"
      ? "bg-amber-400 animate-pulse"
      : status === "done"
        ? "bg-emerald-500"
        : status === "error"
          ? "bg-rose-500"
          : "bg-gray-300";

  return (
    <div
      className={`relative min-w-[180px] rounded-lg border border-l-[3px] bg-ink-850 shadow-card transition ${k.accent} ${
        selected ? "ring-2 ring-brand/60 border-line" : "border-line hover:border-ink-600"
      }`}
    >
      <Handle type="target" position={Position.Left} className="!h-2 !w-2 !border-0 !bg-slate-400" />
      <div className="flex items-center justify-between gap-2 px-3 py-2">
        <span className={`rounded px-1.5 py-0.5 text-[10px] font-medium ${k.badge}`}>{k.label}</span>
        <span className={`h-2 w-2 rounded-full ${dot}`} />
      </div>
      <div className="px-3 pb-2">
        <div className="text-xs font-medium text-slate-200">{d.label || k.desc}</div>
        {d.summary && <div className="mt-0.5 truncate text-[10px] text-slate-500">{d.summary}</div>}
      </div>
      {d.kind === "branch" ? (
        // 分支节点：两个出口手柄 —— 真(绿)/假(红)，连线时各自带 sourceHandle，引擎据此精确选路。
        <>
          <Handle id="true" type="source" position={Position.Right} style={{ top: "38%" }} className="!h-2.5 !w-2.5 !border-0 !bg-emerald-500" />
          <span className="pointer-events-none absolute right-3 top-[32%] text-[9px] font-medium text-emerald-400">真</span>
          <Handle id="false" type="source" position={Position.Right} style={{ top: "72%" }} className="!h-2.5 !w-2.5 !border-0 !bg-rose-500" />
          <span className="pointer-events-none absolute right-3 top-[66%] text-[9px] font-medium text-rose-400">假</span>
        </>
      ) : (
        <Handle type="source" position={Position.Right} className="!h-2 !w-2 !border-0 !bg-slate-400" />
      )}
    </div>
  );
}

export const nodeTypes = { typed: TypedNode };
