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

export default function DimensionLabels({ dimensions, stations, visible = true }) {
  const { labels, mid } = useMemo(() => {
    const norm = normalizeStations(stations);
    const minHeight = norm[0]?.height || 0;
    const maxHeight = norm[norm.length - 1]?.height || 300;
    const midHeight = (minHeight + maxHeight) / 2;
    const envDims = (dimensions || []).filter(d => d.value_mm != null && d.category === 'External envelope').slice(0, 6);
    return { labels: envDims, mid: midHeight };
  }, [dimensions, stations]);

  const heightLabel = labels.find(d => d.dimension_key === 'overall_height');
  const widthLabel = labels.find(d => d.dimension_key === 'overall_max_width');
  const depthLabel = labels.find(d => d.dimension_key === 'overall_max_depth');

  const domLabels = [];
  if (visible) {
    if (heightLabel) domLabels.push({ id: 'dim-h', position: [-100, mid + 130, 0], title: 'H ' + heightLabel.value_mm.toFixed(0) + ' mm', tone: 'cyan' });
    if (widthLabel) domLabels.push({ id: 'dim-w', position: [60, mid + 120, 0], title: 'W ' + widthLabel.value_mm.toFixed(0) + ' mm', tone: 'cyan' });
    if (depthLabel) domLabels.push({ id: 'dim-d', position: [0, mid - 120, 55], title: 'D ' + depthLabel.value_mm.toFixed(0) + ' mm', tone: 'cyan' });
  }
  useLabels(domLabels);

  if (!visible || labels.length === 0) return null;

  return (
    <group>
      {heightLabel && (
        <group position={[-100, mid, 0]}>
          <DimLine start={[0, -120, 0]} end={[0, 120, 0]} color="#22d3ee" radius={0.8} />
        </group>
      )}
      {widthLabel && (
        <group position={[0, mid + 120, 0]}>
          <DimLine start={[-50, 0, 0]} end={[50, 0, 0]} color="#22d3ee" radius={0.8} />
        </group>
      )}
      {depthLabel && (
        <group position={[0, mid - 120, 0]}>
          <DimLine start={[0, 0, -45]} end={[0, 0, 45]} color="#22d3ee" radius={0.8} />
        </group>
      )}
    </group>
  );
}