"use client";

import { useTranslations } from "next-intl";

import { getNodeColor } from "../../lib/node-summary";

interface AnchorNodeSelectorProps {
  t: ReturnType<typeof useTranslations>;
  anchorableNodes: { id: string; title: string; type: string }[];
  hasSelectedNode: boolean;
  onPickNode: (nodeId: string) => void;
  onCreateNew: () => void;
}

/**
 * 锚点节点选择器（P1-1 完善）
 * - 渲染可锚定的教学节点列表（点击即关联到该节点）
 * - 提供"关联到当前选中节点"快捷项（仅当有选中节点时）
 * - 提供"创建新节点并关联"选项（触发 onCreateNew 回调）
 */
export function AnchorNodeSelector({
  t,
  anchorableNodes,
  hasSelectedNode,
  onPickNode,
  onCreateNew,
}: AnchorNodeSelectorProps) {
  return (
    <div className="space-y-1">
      {hasSelectedNode && (
        <button
          className="w-full text-left px-2 py-1 text-sm hover:bg-surface-container-highest rounded font-medium"
          onClick={() => onPickNode("__selected__")}
        >
          {t("editor.anchorToSelectedNode")}
        </button>
      )}
      {anchorableNodes.length > 0 && (
        <>
          <div className="text-[10px] uppercase tracking-wide text-on-surface-variant/70 px-2 pt-1">
            {t("editor.selectNodeForAnchor")}
          </div>
          <div className="max-h-[200px] overflow-y-auto">
            {anchorableNodes.map((n) => (
              <button
                key={n.id}
                className="w-full text-left px-2 py-1 text-sm hover:bg-surface-container-highest rounded flex items-center gap-2"
                onClick={() => onPickNode(n.id)}
              >
                <span
                  className="inline-block w-2 h-2 rounded-full flex-shrink-0"
                  style={{ backgroundColor: getNodeColor(n.type) }}
                />
                <span className="truncate">{n.title}</span>
              </button>
            ))}
          </div>
        </>
      )}
      <div className="border-t border-outline-variant mt-1 pt-1">
        <button
          className="w-full text-left px-2 py-1 text-sm hover:bg-surface-container-highest rounded text-primary"
          onClick={onCreateNew}
        >
          + {t("editor.createNewNode")}
        </button>
      </div>
    </div>
  );
}
