import { MeshBuilder, StandardMaterial, Color3, Vector3 } from '@babylonjs/core';

const STATIONS = [
  { id: 'pylon', name: 'Pylon Diameter', y: 1.59, d: 0.5, badge: '01' },
  { id: 'cover-lower', name: 'Cover Lower Circumference', y: 2.0, d: 1.0, badge: '02' },
  { id: 'socket-distal', name: 'Socket Distal Circumference', y: 2.95, d: 0.9, badge: '03' },
  { id: 'socket-middle', name: 'Socket Middle Circumference', y: 3.95, d: 1.15, badge: '04' },
  { id: 'cover-widest', name: 'Widest Cover / Calf Region', y: 4.5, d: 2.05, badge: '05' },
  { id: 'socket-upper', name: 'Socket Upper Circumference', y: 5.0, d: 1.3, badge: '06' },
  { id: 'socket-proximal', name: 'Socket Proximal Boundary', y: 5.45, d: 1.35, badge: '07' },
];

const FOOT_DIMS = [
  { id: 'length', a: [-0.75, 0.04, 0], b: [2.05, 0.04, 0], label: [0.65, 0.04, 0.48], text: 'Foot length' },
  { id: 'width', a: [-0.55, 0.26, 1.0], b: [0.55, 0.26, 1.0], label: [0.0, 0.44, 1.0], text: 'Forefoot width' },
  { id: 'heel', a: [-0.75, 0.04, 0], b: [-0.75, 0.58, 0], label: [-0.75, 0.32, 0.34], text: 'Heel height' },
];

export function buildMeasurementStations(scene) {
  const ringMat = new StandardMaterial('ringMat', scene);
  ringMat.diffuseColor = Color3.FromHexString('#7E3FF2');
  ringMat.emissiveColor = Color3.FromHexString('#4B1FAF');
  ringMat.specularColor = new Color3(0.3, 0.3, 0.3);

  const rings = [];
  const labels = [];
  STATIONS.forEach((s, i) => {
    const ring = MeshBuilder.CreateTorus(`station-${s.id}`, { diameter: s.d, thickness: 0.05, tessellation: 48 }, scene);
    ring.position.y = s.y;
    ring.material = ringMat;
    ring.metadata = { type: 'measurementStation', stationId: s.id, stationName: s.name, value: null, index: i };
    rings.push(ring);
    labels.push({ id: `station-${s.id}`, position: [s.d / 2 + 0.12, s.y, 0], text: s.name, badge: s.badge, kind: 'station', tone: 'purple' });
  });

  const dimMeshes = [];
  FOOT_DIMS.forEach((d) => {
    const line = MeshBuilder.CreateLines(`dim-${d.id}`, { points: [new Vector3(...d.a), new Vector3(...d.b)] }, scene);
    line.color = Color3.FromHexString('#A56BFF');
    line.isPickable = false;
    dimMeshes.push(line);
    labels.push({ id: `dim-${d.id}`, position: d.label, text: d.text, kind: 'dim', tone: 'purple' });
  });

  const all = [...rings, ...dimMeshes];

  return {
    rings,
    labels,
    setVisible: (v) => all.forEach((m) => { try { m.setEnabled(v ? 1 : 0); } catch (_) {} }),
    dispose: () => {
      all.forEach((m) => { try { m.dispose(); } catch (_) {} });
      try { ringMat.dispose(); } catch (_) {}
    },
  };
}