import { useMemo } from 'react';
import * as THREE from 'three';
import { useLabels } from './useViewportLabels';

/**
 * Visual movement envelope from real MovementPosition records.
 * Pure THREE.Line (strip) — no Drei Line. No Drei Html; labels render in the
 * DOM overlay. Shows nothing when no real data exists.
 */
export default function MovementPath({ positions, visible = true, selectedAngle, onSelect, envelopeOnly = false }) {
  const hasRealData = positions && positions.length > 0;

  const { angles, maxAngle, maxRadius, arcGeom, markers } = useMemo(() => {
    const angs = (positions || []).map(p => p.angle_degrees ?? 0).sort((a, b) => a - b);
    const mA = Math.max(...angs, 90);
    const mR = Math.max(...(positions || []).map(p => p.max_width_mm || p.front_most_mm || 50), 50) + 10;

    const pts = [];
    for (let deg = 0; deg <= mA; deg += 3) {
      const rad = (deg * Math.PI) / 180;
      pts.push(new THREE.Vector3(Math.sin(rad) * mR, -Math.cos(rad) * mR + 20, 0));
    }
    const geom = new THREE.BufferGeometry().setFromPoints(pts);

    const mk = (positions || []).map((p, i) => {
      const deg = p.angle_degrees ?? 0;
      const rad = (deg * Math.PI) / 180;
      const r = (p.max_width_mm || 50) + 5;
      return { index: i, pos: [Math.sin(rad) * r, -Math.cos(rad) * r + 20, 0], deg, name: p.position_name || `${deg}°`, p };
    });

    return { angles: angs, maxAngle: mA, maxRadius: mR, arcGeom: geom, markers: mk };
  }, [positions]);

  const groupY = 40;
  const domLabels = [];
  if (visible && hasRealData) {
    for (const m of markers) {
      const isSelected = selectedAngle === m.deg;
      domLabels.push({
        id: `mv-${m.index}`,
        position: [m.pos[0], groupY + m.pos[1], m.pos[2]],
        title: m.name,
        tone: isSelected ? 'cyan' : 'slate',
      });
    }
    if (!envelopeOnly) {
      domLabels.push({ id: 'mv-summary', position: [0, groupY - maxRadius - 10, 0], title: `Movement envelope: ${angles.length} positions recorded`, tone: 'cyan' });
    }
  }
  useLabels(domLabels);

  if (!visible || !hasRealData) return null;

  return (
    <group position={[0, groupY, 0]}>
      <line geometry={arcGeom} raycast={() => null}>
        <lineBasicMaterial color="#22d3ee" transparent opacity={0.6} />
      </line>
      {markers.map((m) => {
        const isSelected = selectedAngle === m.deg;
        return (
          <group key={m.index} position={m.pos}>
            <mesh onClick={(e) => { e.stopPropagation(); onSelect?.('movement', m.index, m.p); }}>
              <sphereGeometry args={[isSelected ? 6 : 4, 16, 16]} />
              <meshStandardMaterial
                color={isSelected ? '#22d3ee' : '#0e7490'}
                emissive={isSelected ? '#22d3ee' : '#0e7490'}
                emissiveIntensity={isSelected ? 0.8 : 0.4}
              />
            </mesh>
          </group>
        );
      })}
    </group>
  );
}