// ============================================================
// BVS — globe.gl "active markets" globe (accurate country fills)
// Library + GeoJSON are bundled locally (assets/globe-lib.js, assets/countries.geojson)
// ============================================================
const GLOBE_HIGHLIGHT = new Set(['United States of America', 'France', 'Italy', 'Republic of Serbia', 'Poland']);
const GLOBE_NAME = (f) => (f.properties && (f.properties.ADMIN || f.properties.NAME)) || '';
const GLOBE_LBLS = [
  { text: 'USA', lat: 39.5, lng: -98.5, monaco: false },
  { text: 'FRANCE', lat: 46.6, lng: 2.4, monaco: false },
  { text: 'MONACO', lat: 43.7333, lng: 7.4167, monaco: true },
  { text: 'ITALY', lat: 42.8, lng: 12.5, monaco: false },
  { text: 'SERBIA', lat: 44.0, lng: 20.9, monaco: false },
  { text: 'POLAND', lat: 52.0, lng: 19.4, monaco: false },
];

function CountryGlobe({ size = 440 }) {
  const wrapRef = useRef(null);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    const wrap = wrapRef.current;
    if (!el || !wrap || !window.Globe) return;
    let world = null, disposed = false;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    // responsive: never render larger than the available container width
    const measure = () => Math.max(220, Math.min(size, Math.floor(wrap.clientWidth || size)));
    let cur = measure();

    world = window.Globe({ rendererConfig: { preserveDrawingBuffer: true, antialias: true, alpha: true } })(el)
      .backgroundColor('rgba(0,0,0,0)')
      .showAtmosphere(true)
      .atmosphereColor('#2240ff')
      .atmosphereAltitude(0.16)
      .showGraticules(false)
      .width(cur).height(cur);

    world.globeMaterial().color.set('#0d0f14');
    world.globeMaterial().emissive.set('#05070d');
    world.globeMaterial().shininess = 5;

    const ctrl = world.controls();
    ctrl.autoRotate = !reduce;
    ctrl.autoRotateSpeed = -0.5;
    ctrl.enableZoom = false;
    ctrl.enablePan = false;
    world.pointOfView({ lat: 40, lng: -24, altitude: 2.1 }, 0);

    fetch((window.__resources && window.__resources['assets/countries.geojson']) || 'assets/countries.geojson').then((r) => r.json()).then(({ features }) => {
      if (disposed) return;
      world
        .hexPolygonsData(features)
        .hexPolygonResolution(3)
        .hexPolygonMargin(0.2)
        .hexPolygonUseDots(true)
        .hexPolygonAltitude(0.005)
        .hexPolygonColor((f) => GLOBE_HIGHLIGHT.has(GLOBE_NAME(f)) ? 'rgba(74,222,91,0.95)' : 'rgba(120,135,160,0.16)');
    }).catch(() => {});

    // resize the WebGL globe whenever the container width changes (e.g. phone)
    const onResize = () => {
      if (disposed) return;
      const w = measure();
      if (w !== cur) { cur = w; world.width(w).height(w); }
    };
    let ro = null;
    if (window.ResizeObserver) { ro = new ResizeObserver(onResize); ro.observe(wrap); }
    else window.addEventListener('resize', onResize);

    return () => { disposed = true; if (ro) ro.disconnect(); else window.removeEventListener('resize', onResize); try { if (world) { world._destructor && world._destructor(); } } catch (e) {} el.innerHTML = ''; };
  }, [size]);
  return (
    <div ref={wrapRef} style={{ width: '100%', maxWidth: size, display: 'flex', justifyContent: 'center' }} aria-hidden="true">
      <div ref={ref} />
    </div>
  );
}

Object.assign(window, { CountryGlobe });
