const { useEffect, useRef } = React;

const Globe = ({ size = 460 }) => {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const w = size, h = size;
    const cx = w / 2, cy = h / 2;
    const r = size * 0.41;
    let rotation = 0;
    let mouseXOffset = 0;
    let hovering = false;
    let animId;

    const cities = [
      [40.7, -74.0], [51.5, -0.1], [1.3, 103.8],
      [35.7, 139.7], [-33.9, 18.4], [48.9, 2.35],
      [19.4, -99.1], [-23.5, -46.6], [25.2, 55.3],
      [37.6, 127.0], [6.5, 3.4], [-37.8, 144.96],
      [55.75, 37.62], [28.6, 77.2], [31.2, 121.5],
      [41.0, 28.9], [52.5, 13.4], [45.5, -73.6],
      [-4.3, 15.3], [24.7, 46.7], [30.0, 31.2],
    ];

    const project = (lat, lon, rot) => {
      const phi   = (90 - lat) * Math.PI / 180;
      const theta = (lon + rot) * Math.PI / 180;
      const x = r * Math.sin(phi) * Math.cos(theta);
      const y = r * Math.cos(phi);
      const z = r * Math.sin(phi) * Math.sin(theta);
      return { x: cx + x, y: cy - y, z };
    };

    const onMove = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouseXOffset = (e.clientX - rect.left) / rect.width - 0.5;
      hovering = true;
    };
    const onLeave = () => { hovering = false; };
    canvas.addEventListener('mousemove', onMove);
    canvas.addEventListener('mouseleave', onLeave);

    const draw = () => {
      ctx.clearRect(0, 0, w, h);

      // Ambient glow
      const grd = ctx.createRadialGradient(cx, cy, r * 0.6, cx, cy, r * 1.5);
      grd.addColorStop(0, 'rgba(123,104,238,0.05)');
      grd.addColorStop(1, 'transparent');
      ctx.fillStyle = grd;
      ctx.fillRect(0, 0, w, h);

      // Globe body
      ctx.beginPath();
      ctx.arc(cx, cy, r, 0, Math.PI * 2);
      ctx.fillStyle = 'rgba(17,14,28,0.96)';
      ctx.fill();
      ctx.strokeStyle = 'rgba(123,104,238,0.18)';
      ctx.lineWidth = 1.2;
      ctx.stroke();

      const grid = 'rgba(123,104,238,0.07)';

      // Latitude lines
      for (let lat = -60; lat <= 60; lat += 30) {
        ctx.beginPath();
        let started = false;
        for (let lon = 0; lon <= 361; lon += 2) {
          const p = project(lat, lon, rotation);
          if (p.z > 0) {
            if (!started) { ctx.moveTo(p.x, p.y); started = true; }
            else ctx.lineTo(p.x, p.y);
          } else { started = false; }
        }
        ctx.strokeStyle = lat === 0 ? 'rgba(123,104,238,0.14)' : grid;
        ctx.lineWidth = lat === 0 ? 0.9 : 0.6;
        ctx.stroke();
      }

      // Longitude lines
      for (let lon = 0; lon < 360; lon += 30) {
        ctx.beginPath();
        let started = false;
        for (let lat = -88; lat <= 88; lat += 2) {
          const p = project(lat, lon, rotation);
          if (p.z > 0) {
            if (!started) { ctx.moveTo(p.x, p.y); started = true; }
            else ctx.lineTo(p.x, p.y);
          } else { started = false; }
        }
        ctx.strokeStyle = grid;
        ctx.lineWidth = 0.6;
        ctx.stroke();
      }

      // City dots
      const t = Date.now();
      cities.forEach(([lat, lon]) => {
        const p = project(lat, lon, rotation);
        if (p.z <= 0) return;
        const alpha = 0.25 + (p.z / r) * 0.75;
        const pulse = ((t + lat * 300 + lon * 200) % 2600) / 2600;

        ctx.beginPath();
        ctx.arc(p.x, p.y, 2.5 + pulse * 6, 0, Math.PI * 2);
        ctx.strokeStyle = `rgba(0,205,160,${0.22 * (1 - pulse) * alpha})`;
        ctx.lineWidth = 0.8;
        ctx.stroke();

        ctx.beginPath();
        ctx.arc(p.x, p.y, 2.2, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(0,205,160,${alpha})`;
        ctx.fill();
      });

      // Dubai highlight (home city)
      const dubai = project(25.2, 55.3, rotation);
      if (dubai.z > 0) {
        const dp = ((t) % 1800) / 1800;
        ctx.beginPath();
        ctx.arc(dubai.x, dubai.y, 4.5 + dp * 13, 0, Math.PI * 2);
        ctx.strokeStyle = `rgba(123,104,238,${0.4 * (1 - dp)})`;
        ctx.lineWidth = 1;
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(dubai.x, dubai.y, 4.5, 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(123,104,238,0.92)';
        ctx.fill();
      }

      rotation += hovering ? mouseXOffset * 1.4 : 0.11;
      animId = requestAnimationFrame(draw);
    };

    draw();
    return () => {
      cancelAnimationFrame(animId);
      canvas.removeEventListener('mousemove', onMove);
      canvas.removeEventListener('mouseleave', onLeave);
    };
  }, [size]);

  return (
    <canvas ref={canvasRef} width={size} height={size}
      style={{ borderRadius: '50%', maxWidth: '100%', cursor: 'grab' }} />
  );
};

window.Globe = Globe;
