/* ============================================================
   Omnitok Analytics — real choropleth world map (d3-geo)
   → window.GeoMap   (falls back to Cartogram if libs/data fail)
   ============================================================ */
const { useState:gpS, useEffect:gpE, useRef:gpR, useMemo:gpM } = React;

// ISO 3166-1 numeric (world-atlas feature id) -> our A2 codes (only what we need)
const NUM2A2 = {'840':'US','484':'MX','320':'GT','222':'SV','340':'HN','188':'CR','591':'PA',
  '862':'VE','170':'CO','218':'EC','604':'PE','076':'BR','600':'PY','152':'CL','032':'AR',
  '724':'ES','276':'DE','528':'NL','156':'CN','702':'SG'};
// some atlases store ids without leading zeros
function a2ForId(id){ id=''+id; if(NUM2A2[id]) return NUM2A2[id]; const z=id.padStart(3,'0'); return NUM2A2[z]||null; }

function GeoMap({rows, drill, country}){
  const ref=gpR(null); const [w,setW]=gpS(720);
  const [world,setWorld]=gpS(window.__OA_WORLD||null);
  const [err,setErr]=gpS(false);
  const [tip,setTip]=gpS(null);

  gpE(()=>{ const ro=new ResizeObserver(es=>{ for(const e of es) setW(Math.max(320,e.contentRect.width)); });
    if(ref.current) ro.observe(ref.current); return ()=>ro.disconnect(); },[]);

  gpE(()=>{ if(world) return;
    if(!window.d3||!window.topojson){ setErr(true); return; }
    fetch('https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json')
      .then(r=>{ if(!r.ok) throw new Error('net'); return r.json(); })
      .then(j=>{ window.__OA_WORLD=j; setWorld(j); })
      .catch(()=>setErr(true));
  },[world]);

  const counts=gpM(()=>OA.countBy(rows,'co'),[rows]);
  const max=Math.max(1,...Object.values(counts));
  const color=(v)=>{ if(!v) return '#ECEBF3'; const t=Math.pow(v/max,.5); const l=(a,b)=>Math.round(a+(b-a)*t);
    const c1=[219,217,242], c2=[61,58,124]; return `rgb(${l(c1[0],c2[0])},${l(c1[1],c2[1])},${l(c1[2],c2[2])})`; };

  if(err) return React.createElement(window.Cartogram,{rows,drill,country});

  const height=Math.round(Math.min(560,Math.max(360,w*0.56)));
  let features=null, path=null;
  if(world && window.d3 && window.topojson){
    try{
      const all=window.topojson.feature(world, world.objects.countries).features.filter(f=>(''+f.id)!=='010'); // drop Antarctica
      const proj=window.d3.geoNaturalEarth1().fitExtent([[6,6],[w-6,height-6]],{type:'FeatureCollection',features:all});
      const gp=window.d3.geoPath(proj);
      features=all.map(f=>{ const a2=a2ForId(f.id); return {a2,d:gp(f),v:a2?(counts[a2]||0):0}; });
      path=gp;
    }catch(e){ return React.createElement(window.Cartogram,{rows,drill,country}); }
  }

  return React.createElement('div',{ref,style:{width:'100%',position:'relative'}},
    !features
      ? React.createElement('div',{style:{height,display:'flex',alignItems:'center',justifyContent:'center',color:'#A3A3A3',gap:10}},
          React.createElement('div',{className:'spinner',style:{width:24,height:24,borderWidth:3}}),
          OA.lang==='es'?'Cargando mapa…':'Loading map…')
      : React.createElement('svg',{width:w,height,style:{display:'block'},onMouseLeave:()=>setTip(null)},
          features.map((f,i)=> React.createElement('path',{key:i,d:f.d,
            fill:f.v?color(f.v):(f.a2?'#E4E3EE':'#F2F1F7'),
            stroke: country&&f.a2===country?'#FF177B':'#fff', strokeWidth: country&&f.a2===country?2:.6,
            style:{cursor:f.a2?'pointer':'default',transition:'fill .15s'},
            onMouseMove: f.a2?(ev)=>setTip({x:ev.clientX,y:ev.clientY,a2:f.a2,v:f.v}):undefined,
            onMouseLeave:()=>setTip(null),
            onClick: f.a2?()=>drill({country: country===f.a2?null:f.a2}):undefined
          }))),
    tip && React.createElement('div',{className:'cht-tip',style:{left:tip.x+12,top:tip.y+12,opacity:1}},
      React.createElement('div',{className:'tt-t'}, OA.countryName(tip.a2,OA.lang)),
      React.createElement('div',{className:'tt-r'},
        React.createElement('span',{className:'d',style:{background:'#4D4A9D'}}),
        OA.fmt(tip.v)+' '+OA.t('contentEvents')))
  );
}
window.GeoMap=GeoMap;
