import type { FC } from "react";
import * as d3 from "d3";
import type { Goal } from "../../../types/goal";
import styles from "../styles/Node.module.css";

// 目标节点：展示名称、状态样式与选中高亮
interface NodeProps {
  node: d3.HierarchyPointNode<Goal>;
  selected: boolean;
  highlighted?: boolean;
  dimmed?: boolean;
  onClick: () => void;
}

export const Node: FC<NodeProps> = ({ node, selected, highlighted, dimmed, onClick }) => {
  const { x, y, data } = node;

  const truncateMiddle = (text: string, limit: number) => {
    if (text.length <= limit) return text;
    const half = Math.floor((limit - 3) / 2);
    return `${text.slice(0, half)}...${text.slice(-half)}`;
  };

  const isEndNode = data.id === "END";

  return (
    <g
      className={`${styles.node} ${selected ? styles.selected : ""} ${dimmed ? styles.dimmed : ""} ${isEndNode ? styles.endNode : ""}`}
      transform={`translate(${x},${y})`}
      onClick={onClick}
      style={{ cursor: "pointer" }}
    >
      <rect
        x={-70}
        y={-26}
        width={140}
        height={52}
        rx={8}
        fill={isEndNode ? "#fff" : "transparent"}
        stroke={isEndNode ? "#ff4d4f" : "none"}
        strokeDasharray={isEndNode ? "4 4" : "none"}
      />
      <text
        textAnchor="middle"
        dy=".35em"
        fontSize={16}
        fill={dimmed ? "#999" : "#333"}
        fontWeight={selected || highlighted ? 600 : 400}
        style={{ opacity: dimmed ? 0.35 : 1, pointerEvents: "none" }}
      >
        {truncateMiddle(data.description || data.id, 20)}
      </text>
      {data.status === "running" && (
        <circle
          cx={58}
          cy={-16}
          r={4}
          fill="#ff9800"
          className={styles.pulse}
        />
      )}
    </g>
  );
};
