import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

// Antialiasing and responsiveness
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

// Orbit Controls for better interaction
const controls = new OrbitControls(camera, renderer.domElement);
controls.autoRotate = true; // Enable auto-rotate initially
controls.enableDamping = true;

// Camera initial position
camera.position.set(0, 0, 10);
controls.update();

// Create Sphere geometry
const sphereGeometry = new THREE.SphereGeometry(5.6, 32, 32);
const sphereMaterial = new THREE.PointsMaterial({
  color: 0x888888,
  size: 0.05,
});
const sphere = new THREE.Points(sphereGeometry, sphereMaterial);

scene.add(sphere);

// Create Globe geometry
const globeGeometry = new THREE.SphereGeometry(5, 180, 90);

// Load map texture (earth texture)
const textureLoader = new THREE.TextureLoader();
const earthTexture = textureLoader.load("/map.jpg");
const pointTexture = textureLoader.load("/circle.png"); // Particle shape texture

// Material for the Points (using ShaderMaterial)
const globeMaterial = new THREE.ShaderMaterial({
  uniforms: {
    visibilityTexture: { value: earthTexture }, // Earth texture map
    pointTexture: { value: pointTexture }, // Particle circular texture
    pointSize: { value: 0.1 }, // Size of particles
    scale: { value: window.innerHeight / 2 }, // Scale relative to screen
  },
  vertexShader: `
    uniform float scale;
    uniform float pointSize;
    varying vec2 vUv; // Pass UVs to fragment shader for texture lookup

    void main() {
      vUv = uv; // Pass uv coordinates to fragment shader
      vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); // Transform vertex
      gl_PointSize = pointSize * (scale / length(mvPosition.xyz)); // Set size of particles
      gl_Position = projectionMatrix * mvPosition; // Final position
    }
  `,
  fragmentShader: `
    uniform sampler2D visibilityTexture; // Texture for visibility
    uniform sampler2D pointTexture; // Shape of the particles
    varying vec2 vUv;

    void main() {
      // Sample from the visibility texture (earth texture)
      vec4 visibility = texture2D(visibilityTexture, vUv);

      // Discard invisible pixels (based on earth texture brightness)
      if (visibility.r < 0.1) discard;

      // Sample the particle shape texture
      vec4 shape = texture2D(pointTexture, gl_PointCoord);

      // Discard based on alpha channel of shape
      if (shape.a < 0.1) discard;

      // Final color
      gl_FragColor = vec4(visibility.rgb, 1.0) * shape;
    }
  `,
  transparent: true,
});

// Create particle-based globe using Points
const globePoints = new THREE.Points(globeGeometry, globeMaterial);

// Group to apply levitation animation
const globeGroup = new THREE.Group();
globeGroup.add(globePoints);
scene.add(globeGroup);

// Create an invisible globe (for hover detection)
const globeBasicMaterial = new THREE.MeshBasicMaterial({
  transparent: true,
  opacity: 0, // Fully invisible
});

const globe = new THREE.Mesh(globeGeometry, globeBasicMaterial);
globeGroup.add(globe);

// Create markers using PlaneGeometry or Sprite
const markers = [];
const markerData = [
  { lat: 37.7749, lon: -122.4194, label: "San Francisco" },
  { lat: 48.8566, lon: 2.3522, label: "Paris" },
  { lat: 20, lon: -100, label: "Tokyo" },
  { lat: -33.8688, lon: 151.2093, label: "Sydney" },
];

// Function to convert lat/lon to 3D position on sphere
function latLonToVector3(lat, lon, radius = 5) {
  const phi = (90 - lat) * (Math.PI / 180); // Convert latitude to radians
  const theta = (lon + 180) * (Math.PI / 180); // Convert longitude to radians
  const x = -(radius * Math.sin(phi) * Math.cos(theta));
  const y = radius * Math.cos(phi);
  const z = radius * Math.sin(phi) * Math.sin(theta);
  return new THREE.Vector3(x, y, z);
}

// Add markers to the globe
markerData.forEach((data) => {
  const markerGeometry = new THREE.RingGeometry(0.08, 0.15, 50);
  const markerMaterial = new THREE.MeshBasicMaterial({
    color: 0xffffff,
  });
  const marker = new THREE.Mesh(markerGeometry, markerMaterial);

  // Position marker using lat/lon
  const position = latLonToVector3(data.lat, data.lon);
  marker.position.copy(position);

  // Store label data in marker's userData
  marker.userData.label = data.label;

  // Face the marker outward (towards the outside of the sphere)
  marker.lookAt(marker.position.clone().normalize().multiplyScalar(10));

  globeGroup.add(marker);
  markers.push(marker);
});

// Raycaster for mouse interaction
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let isHovering = false;

// Create a DOM element for displaying text on hover

const hoverLabel = document.createElement("div");
hoverLabel.style.position = "absolute";
hoverLabel.style.padding = "8px";
hoverLabel.style.fontFamily = "system-ui";
hoverLabel.style.background = "rgba(255, 255, 255, 0.2)";
hoverLabel.style.color = "#fff";
hoverLabel.style.borderWidth = "1px";
hoverLabel.style.borderStyle = "solid";
hoverLabel.style.borderColor = "rgba(255, 255, 255, 0.3)";
hoverLabel.style.borderRadius = "16px";
hoverLabel.style.padding = "14px 18px";
hoverLabel.style.fontSize = "1.25rem";
hoverLabel.style.boxShadow = "0 4px 30px rgba(0, 0, 0, 0.1)";
hoverLabel.style.backdropFilter = "blur(5px)";
hoverLabel.style.transform = "translateY(0px) translateX(0px)";
hoverLabel.style.display = "none";
document.body.appendChild(hoverLabel);

// Event listeners for mouse movement
const onMouseMove = (event) => {
  // Calculate mouse position in normalized device coordinates (-1 to +1)
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  // Update the raycaster
  raycaster.setFromCamera(mouse, camera);

  // Check for intersection with the invisible globe
  const intersects = raycaster.intersectObject(globe);
  const intersectsMarkers = raycaster.intersectObjects(markers);

  if (intersects.length > 0) {
    // Mouse is hovering over the globe
    if (!isHovering) {
      isHovering = true;
      controls.autoRotate = false; // Disable auto-rotate
    }
  } else {
    // Mouse is not hovering over the globe
    if (isHovering) {
      isHovering = false;
      controls.autoRotate = true; // Re-enable auto-rotate
    }
  }
  if (intersectsMarkers.length > 0) {
    const marker = intersectsMarkers[0].object; // <-- Fix: Now referencing the correct array

    // Display hover label with the marker's label
    hoverLabel.style.display = "block";

    hoverLabel.style.left = `${event.clientX + 10}px`; // Adjust position to avoid mouse overlapping
    hoverLabel.style.top = `${event.clientY + 10}px`;
    hoverLabel.textContent = marker.userData.label; // Get the label from userData
  } else {
    hoverLabel.style.display = "none";
  }
};

window.addEventListener("mousemove", onMouseMove);

// Responsive resizing
window.addEventListener("resize", () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});

// Clock for animation
const clock = new THREE.Clock();

// Animation loop
function animate() {
  // Get elapsed time
  const elapsedTime = clock.getElapsedTime();

  // Smooth levitation using a sine wave
  const levitationHeight = 0.2; // Adjust for how high it levitates
  globeGroup.position.y = Math.sin(elapsedTime * 2) * levitationHeight;

  // Update Orbit Controls
  controls.update();

  // Render the Scene
  renderer.render(scene, camera);
}

renderer.setAnimationLoop(animate);


convert to react three fiber