"use client";

import { useEffect, useRef, useState } from "react";
import { motion } from "framer-motion";

const MARKERS = [
  { lat: 51.5074, lng: -0.1278, label: "English",  flag: "https://flagcdn.com/w40/gb.png", isos: ["GBR"] },
  { lat: 45.9432, lng: 24.9668, label: "Romanian", flag: "https://flagcdn.com/w40/ro.png", isos: ["ROU"] },
  { lat: 36.2048, lng: 138.2529, label: "Japanese", flag: "https://flagcdn.com/w40/jp.png", isos: ["JPN"] },
];

export default function Globe() {
  const containerRef = useRef<HTMLDivElement>(null);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    if (!containerRef.current) return;
    let destroyed = false;

    const script = document.createElement("script");
    script.src = "https://unpkg.com/globe.gl@2.30.0/dist/globe.gl.min.js";
    script.async = true;

    script.onload = () => {
      if (destroyed || !containerRef.current) return;
      const GlobeGL = (window as any).Globe;
      if (!GlobeGL) return;

      const el = containerRef.current;
      const size = Math.min(el.clientWidth || 700, el.clientHeight || 700);

      const arcsData = MARKERS.map((d) => ({
        startLat: 51.5074, startLng: -0.1278,
        endLat: d.lat, endLng: d.lng,
      }));

      const globe = GlobeGL()(el)
        .globeImageUrl("https://unpkg.com/three-globe/example/img/earth-dark.jpg")
        .bumpImageUrl("https://unpkg.com/three-globe/example/img/earth-topology.png")
        .backgroundColor("rgba(0,0,0,0)")
        .showAtmosphere(true)
        .atmosphereColor("#00E5FF")
        .atmosphereAltitude(0.15)
        .width(size)
        .height(size)
        // Country fills
        .polygonCapColor((f: any) => {
          const iso = f.properties?.ISO_A3;
          return MARKERS.find((m) => m.isos.includes(iso))
            ? "rgba(0,229,255,0.35)"
            : "rgba(8,16,36,0.65)";
        })
        .polygonSideColor(() => "rgba(0,0,0,0)")
        .polygonStrokeColor((f: any) => {
          const iso = f.properties?.ISO_A3;
          return MARKERS.find((m) => m.isos.includes(iso))
            ? "rgba(0,229,255,0.85)"
            : "rgba(0,229,255,0.08)";
        })
        .polygonAltitude(0.012)
        // Pulsing rings on the 3 countries
        .ringsData(MARKERS)
        .ringColor(() => "rgba(0,229,255,0.9)")
        .ringMaxRadius(6)
        .ringPropagationSpeed(3)
        .ringRepeatPeriod(900)
        // Animated arcs between countries
        .arcsData(arcsData)
        .arcColor(() => "rgba(0,229,255,0.65)")
        .arcDashLength(0.35)
        .arcDashGap(0.2)
        .arcDashAnimateTime(1400)
        .arcStroke(0.45)
        // ⚠️ NO htmlElements — they appear above text and are impossible to vignette
        // Labels are handled as points instead
        .pointsData(MARKERS)
        .pointColor(() => "#00E5FF")
        .pointAltitude(0.025)
        .pointRadius(0.5)
        .pointsMerge(false);

      // Load countries geojson
      fetch("https://raw.githubusercontent.com/vasturiano/globe.gl/master/example/datasets/ne_110m_admin_0_countries.geojson")
        .then((r) => r.json())
        .then((data) => {
          if (destroyed) return;
          globe.polygonsData(data.features);
          setReady(true);
        });

      // Auto-rotate, no user zoom
      globe.controls().autoRotate = true;
      globe.controls().autoRotateSpeed = 0.65;
      globe.controls().enableZoom = false;
      globe.controls().enablePan = false;
      globe.controls().enableRotate = false;
      globe.pointOfView({ lat: 42, lng: 58, altitude: 2.5 }, 1200);

      const onResize = () => {
        if (!containerRef.current || destroyed) return;
        const s = Math.min(containerRef.current.clientWidth, containerRef.current.clientHeight);
        globe.width(s).height(s);
      };
      window.addEventListener("resize", onResize);

      return () => {
        destroyed = true;
        window.removeEventListener("resize", onResize);
      };
    };

    document.head.appendChild(script);
    return () => {
      destroyed = true;
      if (script.parentNode) script.parentNode.removeChild(script);
    };
  }, []);

  return (
    <div className="relative w-full h-full">
      {/* Spinner while loading */}
      {!ready && (
        <div className="absolute inset-0 flex items-center justify-center">
          <div className="w-10 h-10 rounded-full border-2 border-white/10 border-t-cyan-400 animate-spin" />
        </div>
      )}

      {/* Globe canvas */}
      <motion.div
        ref={containerRef}
        initial={{ opacity: 0 }}
        animate={{ opacity: ready ? 1 : 0 }}
        transition={{ duration: 1.5 }}
        className="w-full h-full"
        style={{ minHeight: "400px" }}
      />

      {/* Flag labels rendered in React (NOT globe.gl htmlElements)
          — positioned at fixed spots around the globe so they never overlap the title */}
      {ready && (
        <div className="absolute inset-0 pointer-events-none select-none">
          {/* English — top right */}
          <motion.div
            initial={{ opacity: 0, y: -8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4, duration: 0.8 }}
            className="absolute top-[18%] right-[12%] flex items-center gap-2 bg-black/70 backdrop-blur-sm border border-cyan-500/40 rounded-full px-3 py-1.5"
          >
            <img src="https://flagcdn.com/w40/gb.png" alt="GB" className="w-5 h-3.5 rounded-[2px] object-cover" />
            <span className="text-white text-xs font-bold tracking-wide">English</span>
          </motion.div>

          {/* Romanian — left middle */}
          <motion.div
            initial={{ opacity: 0, x: -8 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.6, duration: 0.8 }}
            className="absolute top-[55%] left-[8%] flex items-center gap-2 bg-black/70 backdrop-blur-sm border border-cyan-500/40 rounded-full px-3 py-1.5"
          >
            <img src="https://flagcdn.com/w40/ro.png" alt="RO" className="w-5 h-3.5 rounded-[2px] object-cover" />
            <span className="text-white text-xs font-bold tracking-wide">Romanian</span>
          </motion.div>

          {/* Japanese — bottom right */}
          <motion.div
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.8, duration: 0.8 }}
            className="absolute bottom-[22%] right-[10%] flex items-center gap-2 bg-black/70 backdrop-blur-sm border border-cyan-500/40 rounded-full px-3 py-1.5"
          >
            <img src="https://flagcdn.com/w40/jp.png" alt="JP" className="w-5 h-3.5 rounded-[2px] object-cover" />
            <span className="text-white text-xs font-bold tracking-wide">Japanese</span>
          </motion.div>
        </div>
      )}
    </div>
  );
}
