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

const ACCESS_COLOR = '#f59e0b';
const KEEPOUT_COLOR = '#ef4444';
const SENSITIVE_COLORS = {
  'No contact': '#ef4444',
  'Extra clearance': '#f97316',
  'Raised scar': '#eab308',
  'Pinch spot': '#a855f7',
  'Painful area': '#eab308',
  'Moving skin': '#a855f7',
  'Skin fold': '#a855f7',
  'Heat-sensitive area': '#ef4444',
  'Mechanical keep-out': '#6b7280',
  'Safe attachment zone': '#3b82f6',
  'Custom': '#22d3ee',
};

function ZoneBox({ id, zone, color, y, selected, onSelect, label }) {
  const w = zone.width_mm || 35;
  const h = zone.height_mm || 35;
  const d = zone.depth_mm || 35;
  const boxGeom = useMemo(() => new THREE.BoxGeometry(w, h, d), [w, h, d]);
  useLabels([{ id, position: [w / 2 + 4, y + h / 2, 0], title: label || zone.name, tone: color === ACCESS_COLOR ? 'amber' : color === KEEPOUT_COLOR ? 'red' : 'purple' }]);
  return (
    <group position={[0, y, 0]}>
      <mesh geometry={boxGeom} onClick={(e) => { e.stopPropagation(); onSelect(); }}>
        <meshStandardMaterial
          color={color}
          transparent
          opacity={selected ? 0.5 : 0.26}
          emissive={selected ? color : '#000000'}
          emissiveIntensity={selected ? 0.3 : 0}
          depthWrite={false}
        />
        <EdgeLines geometry={boxGeom} color={color} opacity={0.9} />
      </mesh>
    </group>
  );
}

export default function ZoneMeshes({ accessPoints = [], keepOutZones = [], sensitiveZones = [], showAccess = true, showKeepOut = true, showSensitive = true, selectedId, onSelect }) {
  return (
    <group>
      {showAccess && accessPoints.map((z, i) => (
        <ZoneBox key={`a-${i}`} id={`lbl-access-${i}`} zone={z} color={ACCESS_COLOR} y={90 - i * 32} selected={selectedId === `access-${i}`} onSelect={() => onSelect?.('access', i, z)} label={z.name} />
      ))}
      {showKeepOut && keepOutZones.map((z, i) => (
        <ZoneBox key={`k-${i}`} id={`lbl-keepout-${i}`} zone={z} color={KEEPOUT_COLOR} y={40 - i * 32} selected={selectedId === `keepout-${i}`} onSelect={() => onSelect?.('keepout', i, z)} label={z.name} />
      ))}
      {showSensitive && sensitiveZones.map((z, i) => {
        const color = SENSITIVE_COLORS[z.type] || '#22d3ee';
        return (
          <mesh key={`s-${i}`} position={z.position || [0, 0, 0]} onClick={(e) => { e.stopPropagation(); onSelect?.('sensitive', i, z); }}>
            <sphereGeometry args={[z.brushSize || 15, 16, 16]} />
            <meshStandardMaterial color={color} transparent opacity={selectedId === `sensitive-${i}` ? 0.6 : 0.35} emissive={color} emissiveIntensity={0.2} depthWrite={false} />
          </mesh>
        );
      })}
    </group>
  );
}