import type { ReactNode, CSSProperties, KeyboardEvent } from "react";

import type { NodeAnchor } from "../../types";
import {
  parseAnchoredText,
  toCircledNumber,
} from "../../lib/anchor-injector";

interface RenderSegmentsParams {
  segments: ReturnType<typeof parseAnchoredText>;
  activeAnchorIds: Set<string>;
  getAnchorNodeColor: (anchorId: string) => string;
  onSelectNode?: (id: string | null) => void;
  anchors?: NodeAnchor[];
}

/**
 * 键盘激活回调：Enter / Space 触发与点击同等的选中逻辑（V4 P0-3 修复 a11y）。
 */
function handleAnchorKeyDown(
  e: KeyboardEvent<HTMLSpanElement>,
  anchor: NodeAnchor | undefined,
  onSelectNode: ((id: string | null) => void) | undefined,
): void {
  if (!anchor || !onSelectNode) return;
  if (e.key === "Enter" || e.key === " ") {
    e.preventDefault();
    e.stopPropagation();
    onSelectNode(anchor.nodeId);
  }
}

/**
 * 渲染锚点段落数组（简化版：直接遍历 segments，不使用 ReactMarkdown）
 * 解决问题 7：避免每个段落重复渲染整个文档内容
 */
export function renderSegments({
  segments,
  activeAnchorIds,
  getAnchorNodeColor,
  onSelectNode,
  anchors,
}: RenderSegmentsParams): ReactNode {
  return segments.map((seg, idx) => {
    if (seg.type === "text") {
      return <span key={idx}>{seg.content}</span>;
    }
    if (seg.type === "anchor-range") {
      const isActive = seg.anchorId ? activeAnchorIds.has(seg.anchorId) : false;
      const color = seg.anchorId ? getAnchorNodeColor(seg.anchorId) : "#9e9e9e";
      const anchor = anchors?.find((a) => a.id === seg.anchorId);
      // V4 P0-3 修复：锚点 span 添加 role/tabIndex/onKeyDown/aria-label，支持键盘导航与读屏
      return (
        <span
          key={idx}
          role={anchor ? "button" : undefined}
          tabIndex={anchor ? 0 : undefined}
          aria-label={anchor ? `跳转到关联节点 ${anchor.nodeId}` : undefined}
          aria-pressed={anchor ? isActive : undefined}
          className={`range-anchor ${isActive ? "active" : ""}`}
          // CSS 自定义属性需要断言，因为 TS 的 CSSProperties 不包含 --* 变量
          style={
            {
              backgroundColor: color,
              "--node-color": color,
            } as CSSProperties
          }
          onClick={(e) => {
            e.stopPropagation();
            if (anchor && onSelectNode) {
              onSelectNode(anchor.nodeId);
            }
          }}
          onKeyDown={(e) => handleAnchorKeyDown(e, anchor, onSelectNode)}
        >
          {seg.content}
        </span>
      );
    }
    // point anchor
    const isActive = seg.anchorId ? activeAnchorIds.has(seg.anchorId) : false;
    const color = seg.anchorId ? getAnchorNodeColor(seg.anchorId) : "#9e9e9e";
    const anchor = anchors?.find((a) => a.id === seg.anchorId);
    const pointIndex = anchor
      ? (anchors?.filter((a) => a.type === "point").indexOf(anchor) ?? -1) + 1
      : 1;
    // V4 P0-3 修复：point anchor 同样补齐 a11y 属性
    return (
      <span
        key={idx}
        role={anchor ? "button" : undefined}
        tabIndex={anchor ? 0 : undefined}
        aria-label={anchor ? `跳转到关联节点 ${anchor.nodeId}` : undefined}
        aria-pressed={anchor ? isActive : undefined}
        className={`point-anchor ${isActive ? "active" : ""}`}
        // CSS 自定义属性需要断言，因为 TS 的 CSSProperties 不包含 --* 变量
        style={
          {
            backgroundColor: color,
            "--node-color": color,
          } as CSSProperties
        }
        onClick={(e) => {
          e.stopPropagation();
          if (anchor && onSelectNode) {
            onSelectNode(anchor.nodeId);
          }
        }}
        onKeyDown={(e) => handleAnchorKeyDown(e, anchor, onSelectNode)}
      >
        {toCircledNumber(pointIndex ?? 1)}
      </span>
    );
  });
}
