import { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
import { PLYLoader } from 'three/examples/jsm/loaders/PLYLoader.js';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
const DentalViewport = ({ file }) => {
  const ref=useRef(null);
  useEffect(()=>{const el=ref.current,scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(38,el.clientWidth/el.clientHeight,.1,100),renderer=new THREE.WebGLRenderer({antialias:true,alpha:true}),group=new THREE.Group(),mat=new THREE.MeshPhysicalMaterial({color:0xe8f4f7,roughness:.22,clearcoat:.7});renderer.setSize(el.clientWidth,el.clientHeight);renderer.setPixelRatio(Math.min(devicePixelRatio,2));el.appendChild(renderer.domElement);camera.position.set(0,1.6,8);scene.add(group);scene.add(new THREE.HemisphereLight(0x8de7ff,0x07101c,2.2));const light=new THREE.PointLight(0x36d9ff,30);light.position.set(3,4,4);scene.add(light);
    if(!file){for(let jaw of [-1,1])for(let i=0;i<14;i++){const a=(i/13-.5)*2.3,x=Math.sin(a)*2.7,z=Math.cos(a)*1.25,tooth=new THREE.Mesh(new THREE.SphereGeometry(.34,24,20),mat);tooth.scale.set(.75,1.25,.9);tooth.position.set(x,jaw*.62,z-.4);tooth.rotation.z=-a*.38;group.add(tooth)}}
    else {const ext=file.name.split('.').pop().toLowerCase();(ext==='obj'?file.text():file.arrayBuffer()).then(data=>{const model=ext==='obj'?new OBJLoader().parse(data):new THREE.Mesh((ext==='stl'?new STLLoader():new PLYLoader()).parse(data),mat);model.traverse?.(x=>{if(x.isMesh)x.material=mat});const box=new THREE.Box3().setFromObject(model),size=box.getSize(new THREE.Vector3()),center=box.getCenter(new THREE.Vector3());model.position.sub(center);model.scale.setScalar(4/Math.max(size.x,size.y,size.z));group.add(model)})}
    let id;const run=()=>{group.rotation.y+=.0025;renderer.render(scene,camera);id=requestAnimationFrame(run)};run();return()=>{cancelAnimationFrame(id);renderer.dispose();el.removeChild(renderer.domElement)};
  },[file]);
  return <div ref={ref} className="h-full min-h-72 w-full" />;
};
export default DentalViewport;