import { useMemo } from 'react';
import { useLabels } from './useViewportLabels';
import { normalizeStations } from './limbGeometry';

export default function StationRings({ stations, selectedId, onSelect, visible = true, highlightedIndex = -1 }) {
  const normalized = normalizeStations(stations);
  const minHeight = normalized[0]?.height || 0;
  const maxHeight = normalized[normalized.length - 1]?.height || 300;
  const mid = (minHeight + maxHeight) / 2;

  const domLabels = visible ? normalized.map((s, i) => {
    const y = s.height - mid;
    const radius = Math.max(s.width, s.depth) / 2 + 4;
    const isSelected = selectedId === `station-${i}` || highlightedIndex === i;
    const num = String(i + 1).padStart(2, '0');
    const subtitle = s.fictional
      ? `Ø ${s.width.toFixed(0)} × ${s.depth.toFixed(0)} mm · visual test data`
      : s.hasValue
        ? `Ø ${s.width.toFixed(0)} × ${s.depth.toFixed(0)} mm`
        : 'Measurement required';
    return { id: `ring-${i}`, position: [radius + 26, y, 0], badge: num, title: s.name || `Station ${num}`, subtitle, tone: isSelected ? 'cyan' : 'slate' };
  }) : [];
  useLabels(domLabels);

  if (!visible) return null;

  return (
    <group>
      {normalized.map((s, i) => {
        const y = s.height - mid;
        const radius = Math.max(s.width, s.depth) / 2 + 4;
        const isSelected = selectedId === `station-${i}` || highlightedIndex === i;
        const num = String(i + 1).padStart(2, '0');
        const labelX = radius + 6;
        const badgeX = radius + 3;

        return (
          <group key={i} position={[0, y, 0]}>
            {/* Circumference ring — native TorusGeometry */}
            <mesh
              rotation={[Math.PI / 2, 0, 0]}
              onClick={(e) => { e.stopPropagation(); onSelect?.('station', i, { ...normalized[i], index: i }); }}
            >
              <torusGeometry args={[radius, isSelected ? 2.6 : 1.8, 12, 80]} />
              <meshStandardMaterial
                color={isSelected ? '#22d3ee' : '#0e7490'}
                emissive={isSelected ? '#22d3ee' : '#0e7490'}
                emissiveIntensity={isSelected ? 1.5 : 0.45}
                transparent
                opacity={isSelected ? 0.98 : 0.8}
              />
            </mesh>

            {/* Diameter cross line */}
            <mesh rotation={[Math.PI / 2, 0, 0]} raycast={() => null}>
              <cylinderGeometry args={[0.7, 0.7, radius * 2, 6]} />
              <meshBasicMaterial color={isSelected ? '#22d3ee' : '#0e7490'} transparent opacity={isSelected ? 0.6 : 0.35} />
            </mesh>

            {/* Numbered badge sphere */}
            <mesh position={[badgeX, 0, 0]} onClick={(e) => { e.stopPropagation(); onSelect?.('station', i, { ...normalized[i], index: i }); }}>
              <sphereGeometry args={[isSelected ? 5 : 4, 18, 18]} />
              <meshStandardMaterial
                color={isSelected ? '#22d3ee' : '#0b4a5a'}
                emissive={isSelected ? '#22d3ee' : '#0e7490'}
                emissiveIntensity={isSelected ? 1.2 : 0.5}
              />
            </mesh>

            {/* Leader line from badge toward the DOM label */}
            <mesh position={[labelX + 6, 0, 0]} rotation={[0, 0, Math.PI / 2]} raycast={() => null}>
              <cylinderGeometry args={[0.5, 0.5, 14, 6]} />
              <meshBasicMaterial color={isSelected ? '#22d3ee' : '#3a4550'} transparent opacity={0.7} />
            </mesh>
          </group>
        );
      })}
    </group>
  );
}