// DrillContinent — zoomed continent view: country ranking with map and evolution

function DrillContinent({ hs, hsCodes, metric, years, drill, setDrill }) {
  const CF = window.CF;
  const EvolucionPanel = window.EvolucionPanel;
  const lo = Math.min(...years), hi = Math.max(...years);

  const apiData = window.useApi(
    `${window.API_BASE}/api/countries?${window.hsQ(hsCodes)}&from=${lo}&to=${hi}`,
    [hsCodes ? hsCodes.join(",") : hs, lo, hi]
  );

  const allCountries = React.useMemo(() => {
    if (!apiData.data) return [];
    const rows = apiData.data.rows
      .map(r => window.normalizeCountryRow(r, metric))
      .sort((a, b) => b.value - a.value);
    window.populateCountryCache(apiData.data.rows);
    return rows;
  }, [apiData.data, metric]);

  const continentCountries = allCountries.filter(c => c.continent === drill.continent);
  const loading = apiData.status === "loading";

  if (!loading && !continentCountries.length && apiData.status === "ok") {
    return (
      <div className="cf-empty">
        Continente no encontrado ·{" "}
        <button className="cf-btn" onClick={() => setDrill({level:"world", continent:null, country:null})}>Volver al mundo</button>
      </div>
    );
  }

  const cmax = continentCountries[0]?.value || 1;
  function gotoCountry(iso) {
    setDrill({ level: "country", continent: drill.continent, country: iso });
  }

  const activeObj = { continent: drill.continent, countries: continentCountries, value: continentCountries.reduce((a,c) => a+c.value, 0) };

  return (
    <div className="cf-fade-in">
      {!loading && continentCountries.length > 0 && (
        <ContinentMapLibre active={activeObj} onCountry={gotoCountry} metric={metric} />
      )}

      <div className="cf-grid-2" style={{marginTop:18}}>
        <div className="cf-panel">
          <div className="cf-panel-head">
            <div>
              <h2>{drill.continent} · ranking</h2>
              <p>{continentCountries.length} mercados · pulsa para abrir ficha de país</p>
            </div>
          </div>
          {loading && <div style={{padding:"20px 0", color:"var(--xn-fg-3)", fontSize:13}}>Cargando…</div>}
          {!loading && (
            <RankingList
              rows={continentCountries}
              max={cmax}
              metric={metric}
              onClick={(c) => gotoCountry(c.iso)}
            />
          )}
        </div>

        <div className="cf-panel" style={{display:"flex", flexDirection:"column", gap:0}}>
          <EvolucionPanel hs={hs} hsCodes={hsCodes} metric={metric} years={years} continent={drill.continent} />

        </div>
      </div>
    </div>
  );
}

const CONTINENT_BOUNDS = {
  "Europa":            [[-25, 27],  [50,  72]],
  "Europe":            [[-25, 27],  [50,  72]],
  "Asia":              [[25,  -10], [150, 75]],
  "África":            [[-20, -35], [55,  38]],
  "Africa":            [[-20, -35], [55,  38]],
  "América del Norte": [[-170, 15], [-50, 72]],
  "North America":     [[-170, 15], [-50, 72]],
  "América del Sur":   [[-82, -56], [-34, 13]],
  "South America":     [[-82, -56], [-34, 13]],
  "América":           [[-170, -56],[-34, 72]],
  "Oceanía":           [[110, -50], [180, -10]],
  "Oceania":           [[110, -50], [180, -10]],
  "Oriente Medio":     [[25,  12],  [65,  42]],
  "Middle East":       [[25,  12],  [65,  42]],
};

function ContinentMapLibre({ active, onCountry, metric }) {
  const containerRef = React.useRef(null);
  const mapRef = React.useRef(null);
  const dataRef = React.useRef({ byIso: {}, max: 1, value: 1 });
  const onCountryRef = React.useRef(onCountry);
  onCountryRef.current = onCountry;

  const byIso = Object.fromEntries(active.countries.map(c => [c.iso, c]));
  const max = Math.max(...active.countries.map(c => c.value), 1);
  dataRef.current = { byIso, max, value: active.value };

  const [hover, setHover] = React.useState(null);
  const [tipPos, setTipPos] = React.useState({ x: 0, y: 0 });

  React.useEffect(() => {
    if (!window.maplibregl || mapRef.current) return;

    const map = new window.maplibregl.Map({
      container: containerRef.current,
      style: {
        version: 8,
        sources: {},
        layers: [
          { id: "background", type: "background", paint: { "background-color": "#ffffff" } },
        ],
      },
      center: [15, 25],
      zoom: 1.3,
      minZoom: 0.8,
      maxZoom: 8,
      attributionControl: false,
    });
    mapRef.current = map;

    map.addControl(new window.maplibregl.NavigationControl({ showCompass: false }), "top-right");

    map.on("load", () => {
      fetch("https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_110m_admin_0_countries.geojson")
        .then(r => r.json())
        .then(geo => {
          geo.features.forEach(f => { f.properties.iso3 = f.properties.iso_a3; });
          map.addSource("countries", { type: "geojson", data: geo });

          const { byIso: d, max: m } = dataRef.current;
          map.addLayer({
            id: "countries-fill",
            type: "fill",
            source: "countries",
            paint: { "fill-color": window.buildFillExpr(d, m), "fill-opacity": 0.88 },
          });
          map.addLayer({
            id: "countries-outline",
            type: "line",
            source: "countries",
            paint: { "line-color": "#FFFFFF", "line-width": 0.6, "line-opacity": 1 },
          });

          const bounds = CONTINENT_BOUNDS[active.continent];
          if (bounds) map.fitBounds(bounds, { padding: 50, duration: 800 });
        });

      map.on("mousemove", "countries-fill", (e) => {
        const feat = e.features?.[0];
        if (!feat) { setHover(null); return; }
        const iso = feat.properties?.iso3;
        if (iso === "ESP") { map.getCanvas().style.cursor = "default"; setHover({ iso, name: "España", isOrigin: true }); setTipPos({ x: e.originalEvent.clientX, y: e.originalEvent.clientY }); return; }
        const row = iso ? dataRef.current.byIso[iso] : null;
        map.getCanvas().style.cursor = row ? "pointer" : "default";
        setHover(row ? row : { iso, name: feat.properties?.name || iso, noData: true });
        setTipPos({ x: e.originalEvent.clientX, y: e.originalEvent.clientY });
      });

      map.on("mouseleave", "countries-fill", () => { setHover(null); map.getCanvas().style.cursor = ""; });

      map.on("click", "countries-fill", (e) => {
        const iso = e.features?.[0]?.properties?.iso3;
        if (!iso) return;
        const row = dataRef.current.byIso[iso];
        if (row) onCountryRef.current(row.iso);
      });
    });

    return () => { map.remove(); mapRef.current = null; };
  }, []);

  React.useEffect(() => {
    const map = mapRef.current;
    if (!map) return;
    const tryUpdate = () => {
      if (!map.getSource("countries")) return;
      map.setPaintProperty("countries-fill", "fill-color", window.buildFillExpr(byIso, max));
      const bounds = CONTINENT_BOUNDS[active.continent];
      if (bounds) map.fitBounds(bounds, { padding: 50, duration: 500 });
    };
    if (map.loaded() && map.isStyleLoaded()) tryUpdate();
    else map.once("idle", tryUpdate);
  }, [active.continent]);

  return (
    <div className="cf-worldmap-wrap">
      <div className="cf-panel-head" style={{margin:0, marginBottom:14}}>
        <div>
          <h2>{active.continent} · mapa regional</h2>
          <p>Choroplético acotado a la región · pulsa un país para abrir su ficha</p>
        </div>
        <div className="cf-legend">
          <span>Intensidad</span>
          <div className="cf-legend-scale">
            {["#B6D0FF","#82AEFF","#4F8BFF","#2A6BF7","#173FB0","#0B1F5C"].map(c => (
              <span key={c} style={{background: c}} />
            ))}
          </div>
          <span className="cf-legend-labels"><span>0</span><span>·</span><span>{window.CF.fmtVal(max, metric)}</span></span>
        </div>
      </div>
      <div className="cf-maplibre-container" ref={containerRef} />
      {hover && !hover.isOrigin && (
        <div className="cf-map-tooltip" style={{
          left: Math.min(tipPos.x + 14, window.innerWidth - 220),
          top: tipPos.y - 80,
        }}>
          <div className="name">{hover.name}</div>
          {hover.noData
            ? <div className="row" style={{opacity:.6, fontSize:11, marginTop:2}}>Sin datos de exportación</div>
            : <>
                <div className="row"><span className="k">{window.CF.metricLabel(metric)}</span> <span className="v">{window.CF.fmtVal(hover.value, metric)}</span></div>
                <div className="row"><span className="k">Cuota región</span> <span className="v">{window.CF.fmtPct(hover.value / dataRef.current.value)}</span></div>
              </>
          }
        </div>
      )}
    </div>
  );
}

window.DrillContinent = DrillContinent;
