const { useEffect, useRef } = React;

function Peak3DMap({ gpxData, paletteObj }) {
  const mountRef = useRef(null);

  useEffect(() => {
    if (!gpxData || !mountRef.current) return;

    // Three.js Setup
    const w = mountRef.current.clientWidth;
    const h = mountRef.current.clientHeight;
    
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(paletteObj.paperDeep);

    const camera = new THREE.PerspectiveCamera(45, w / h, 0.1, 100);
    camera.position.set(0, -12, 8);
    camera.up.set(0, 0, 1); // Z is up

    const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    renderer.setSize(w, h);
    renderer.setPixelRatio(window.devicePixelRatio);
    mountRef.current.appendChild(renderer.domElement);

    const controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.autoRotate = true;
    controls.autoRotateSpeed = 1.0;

    // Stylized Grid Floor
    const gridHelper = new THREE.GridHelper(15, 15, paletteObj.contourDark, paletteObj.contour);
    gridHelper.rotation.x = Math.PI / 2; // Lie flat on XY plane
    scene.add(gridHelper);

    // Render Track
    const points = gpxData.points3D;
    
    // Line geometry for the GPX track
    const lineGeo = new THREE.BufferGeometry();
    const positions = new Float32Array(points.length * 3);
    for (let i = 0; i < points.length; i++) {
      positions[i * 3] = points[i].x;
      positions[i * 3 + 1] = points[i].y;
      positions[i * 3 + 2] = points[i].z + 2; // Elevate track above grid
    }
    lineGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
    
    const lineMat = new THREE.LineBasicMaterial({
      color: paletteObj.accent,
      linewidth: 3, // WebGL limits this often to 1, but we request 3
    });
    const line = new THREE.Line(lineGeo, lineMat);
    scene.add(line);

    // "Curtain" lines dropping down
    const curtainGeo = new THREE.BufferGeometry();
    // For every Nth point, drop a line to z=0
    const curtainPositions = [];
    const step = Math.max(1, Math.floor(points.length / 50)); // ~50 lines max
    for (let i = 0; i < points.length; i += step) {
      curtainPositions.push(points[i].x, points[i].y, points[i].z + 2);
      curtainPositions.push(points[i].x, points[i].y, 0);
    }
    curtainGeo.setAttribute('position', new THREE.Float32BufferAttribute(curtainPositions, 3));
    const curtainMat = new THREE.LineBasicMaterial({
      color: paletteObj.contourDark,
      transparent: true,
      opacity: 0.3
    });
    const curtainLines = new THREE.LineSegments(curtainGeo, curtainMat);
    scene.add(curtainLines);

    // Start/End points
    const sphereGeo = new THREE.SphereGeometry(0.2);
    const startMat = new THREE.MeshBasicMaterial({ color: paletteObj.planned });
    const startSphere = new THREE.Mesh(sphereGeo, startMat);
    startSphere.position.set(points[0].x, points[0].y, points[0].z + 2);
    scene.add(startSphere);

    const coneGeo = new THREE.ConeGeometry(0.4, 0.8, 3);
    coneGeo.rotateX(Math.PI / 2); // Point up along Z axis
    const endMat = new THREE.MeshBasicMaterial({ color: paletteObj.summited });
    const endMesh = new THREE.Mesh(coneGeo, endMat);

    const edgesGeo = new THREE.EdgesGeometry(coneGeo);
    const edgesMat = new THREE.LineBasicMaterial({ color: paletteObj.paperDeep });
    const edgesMesh = new THREE.LineSegments(edgesGeo, edgesMat);
    endMesh.add(edgesMesh);

    // Inner white dot to match the 2D icon
    const dotGeo = new THREE.SphereGeometry(0.12);
    const dotMat = new THREE.MeshBasicMaterial({ color: paletteObj.paper });
    const dotMesh = new THREE.Mesh(dotGeo, dotMat);
    dotMesh.position.set(0, -0.1, -0.2); // position near the base/center
    endMesh.add(dotMesh);

    const summitPt = points[gpxData.maxEleIndex];
    endMesh.position.set(summitPt.x, summitPt.y, summitPt.z + 2 + 0.4);
    scene.add(endMesh);

    // Animation Loop
    let animationId;
    const animate = () => {
      animationId = requestAnimationFrame(animate);
      controls.update();
      renderer.render(scene, camera);
    };
    animate();

    // Resize Handler
    const handleResize = () => {
      if(!mountRef.current) return;
      const nw = mountRef.current.clientWidth;
      const nh = mountRef.current.clientHeight;
      camera.aspect = nw / nh;
      camera.updateProjectionMatrix();
      renderer.setSize(nw, nh);
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      cancelAnimationFrame(animationId);
      if(mountRef.current) mountRef.current.removeChild(renderer.domElement);
      renderer.dispose();
      scene.clear();
    };
  }, [gpxData, paletteObj]);

  return (
    <div 
      ref={mountRef} 
      style={{ width: '100%', height: '300px', borderRadius: '4px', overflow: 'hidden', border: `1px solid ${paletteObj.contour}` }}
    />
  );
}

window.Peak3DMap = Peak3DMap;
