/**
 * Connections.tsx — 阶段间CatmullRom管道连接 + 数据流转标注
 * 每段管道旁标注数据变化摘要，帮助理解每一步的输入输出
 */
import { useMemo } from 'react';
import { Text } from '@react-three/drei';
import * as THREE from 'three';
import type { StageIndex } from '../types';
import { STAGE_POSITIONS, CN_FONT } from '../types';

// 管道上方的数据流转标注
const PIPE_LABELS = [
  '1048字段',       // 原始数据 → 赋分
  '20个原始分',     // 赋分 → PCA
  '20个标准化分',   // PCA → 分布
  '20个水平等级',   // 分布 → 水平
  '7维度 → 1总分',  // 水平 → 维度
];

interface Props {
  currentStep: StageIndex;
}

export default function Connections({ currentStep }: Props) {
  const tubes = useMemo(() => {
    const result: Array<{
      geometry: THREE.TubeGeometry;
      from: number;
      to: number;
      midX: number;
    }> = [];

    for (let i = 0; i < STAGE_POSITIONS.length - 1; i++) {
      const x1 = STAGE_POSITIONS[i] + 5;
      const x2 = STAGE_POSITIONS[i + 1] - 5;
      const curve = new THREE.CatmullRomCurve3([
        new THREE.Vector3(x1, 6, 0),
        new THREE.Vector3((x1 + x2) / 2, 8, 0),
        new THREE.Vector3(x2, 6, 0),
      ]);
      const geo = new THREE.TubeGeometry(curve, 20, 0.08, 6, false);
      result.push({ geometry: geo, from: i, to: i + 1, midX: (x1 + x2) / 2 });
    }
    return result;
  }, []);

  return (
    <group>
      {tubes.map((tube, i) => {
        const active = tube.to <= currentStep;
        return (
          <group key={i}>
            {/* 管道 */}
            <mesh geometry={tube.geometry}>
              <meshBasicMaterial
                color={active ? '#4fc3f7' : '#334466'}
                transparent
                opacity={active ? 0.6 : 0.25}
              />
            </mesh>
            {/* 数据流转标注 — 管道上方 */}
            {active && PIPE_LABELS[i] && (
              <Text
                position={[tube.midX, 9.5, 0]}
                fontSize={0.3}
                color="#667788"
                anchorX="center"
                anchorY="middle"
                font={CN_FONT}
              >
                {PIPE_LABELS[i]}
              </Text>
            )}
          </group>
        );
      })}
    </group>
  );
}
