/* ColombiaMap — Mapa estilizado de Colombia con actores y conexiones */
/* Silueta aproximada del país + capitales departamentales como nodos */

// Capitales departamentales (lat, lng) — referencia geográfica
const DEPTO_COORDS = {
  "Bogotá D.C.":      { lat: 4.71,  lng: -74.07 },
  "Antioquia":        { lat: 6.25,  lng: -75.56 },
  "Valle del Cauca":  { lat: 3.45,  lng: -76.53 },
  "Atlántico":        { lat: 10.96, lng: -74.79 },
  "Santander":        { lat: 7.12,  lng: -73.12 },
  "Cundinamarca":     { lat: 4.71,  lng: -74.20 },
  "Bolívar":          { lat: 10.39, lng: -75.51 },
  "Risaralda":        { lat: 4.81,  lng: -75.69 },
  "Caldas":           { lat: 5.07,  lng: -75.52 },
  "Tolima":           { lat: 4.44,  lng: -75.23 },
  "Quindío":          { lat: 4.53,  lng: -75.68 },
  "Huila":            { lat: 2.93,  lng: -75.28 },
  "N. de Santander":  { lat: 7.89,  lng: -72.50 },
  "Nariño":           { lat: 1.21,  lng: -77.28 },
  "Sucre":            { lat: 9.30,  lng: -75.40 },
  "Cesar":            { lat: 10.46, lng: -73.25 },
  "Córdoba":          { lat: 8.76,  lng: -75.88 },
  "Meta":             { lat: 4.14,  lng: -73.62 },
  "Magdalena":        { lat: 11.24, lng: -74.20 },
  "Cauca":            { lat: 2.45,  lng: -76.61 },
  "Chocó":            { lat: 5.69,  lng: -76.66 },
  "Casanare":         { lat: 5.34,  lng: -72.40 },
  "Caquetá":          { lat: 1.62,  lng: -75.61 },
  "La Guajira":       { lat: 11.54, lng: -72.91 },
};

// Silueta aproximada de Colombia (clockwise desde el noroeste)
const COLOMBIA_POLY = [
  [8.55, -77.30], [8.95, -76.85], [9.40, -76.20], [10.05, -75.65], [10.55, -75.55],
  [11.05, -74.85], [11.30, -74.20], [11.80, -73.45], [12.45, -72.30], [12.40, -71.65],
  [11.60, -71.10], [11.00, -71.95], [10.45, -72.50], [9.20, -72.70], [7.40, -72.45],
  [7.05, -71.65], [6.95, -70.85], [6.20, -69.85], [4.70, -67.85], [3.50, -67.55],
  [2.00, -67.30], [0.85, -68.60], [-0.30, -69.45], [-1.40, -70.10], [-2.20, -70.85],
  [-4.20, -69.95], [-4.25, -70.30], [-3.50, -72.50], [-2.65, -73.20], [-1.50, -73.65],
  [-0.65, -74.80], [0.10, -75.65], [0.65, -76.40], [1.20, -76.95], [1.45, -77.85],
  [1.80, -78.85], [3.20, -77.55], [4.00, -77.40], [5.00, -77.55], [6.10, -77.45],
  [7.20, -77.85], [8.05, -77.85], [8.55, -77.30],
];

// Proyección equirectangular simple
const PROJ_BOUNDS = { latMin: -4.5, latMax: 12.8, lngMin: -79.5, lngMax: -66.5 };
function project(lat, lng, W, H) {
  const x = ((lng - PROJ_BOUNDS.lngMin) / (PROJ_BOUNDS.lngMax - PROJ_BOUNDS.lngMin)) * W;
  const y = ((PROJ_BOUNDS.latMax - lat) / (PROJ_BOUNDS.latMax - PROJ_BOUNDS.latMin)) * H;
  return { x, y };
}

const REGION_COLORS = {
  "Andina":    "#1a3a6c",
  "Caribe":    "#c97a16",
  "Pacífica":  "#1b7a4d",
  "Orinoquía": "#5b3f9e",
  "Amazonía":  "#7c5a1f",
};

function ColombiaMap({ actores, conexiones, onSelectDepto, selectedDepto, tipoConexFilter }) {
  const W = 620, H = 720;

  // Agrupa actores por departamento
  const byDepto = useMemo(() => {
    const map = {};
    actores.forEach(a => {
      if (!map[a.depto]) map[a.depto] = [];
      map[a.depto].push(a);
    });
    return map;
  }, [actores]);

  // Conexiones inter-departamentales agregadas
  const interDeptoLinks = useMemo(() => {
    const counts = {};
    conexiones.forEach(c => {
      const fa = actores.find(a => a.id === c.from);
      const ta = actores.find(a => a.id === c.to);
      if (!fa || !ta || fa.depto === ta.depto) return;
      const k = [fa.depto, ta.depto].sort().join("→");
      if (!counts[k]) counts[k] = { from: fa.depto, to: ta.depto, count: 0, types: new Set() };
      counts[k].count += 1;
      counts[k].types.add(c.tipo);
    });
    return Object.values(counts);
  }, [actores, conexiones]);

  const maxActores = Math.max(...Object.values(byDepto).map(arr => arr.length), 1);

  // Polígono país
  const colombiaPath = COLOMBIA_POLY.map(([lat, lng], i) => {
    const p = project(lat, lng, W, H);
    return `${i === 0 ? "M" : "L"} ${p.x.toFixed(1)} ${p.y.toFixed(1)}`;
  }).join(" ") + " Z";

  const connTypeColors = { mentoria: "#7c5a1f", alianza: "#1b7a4d", lead: "#c97a16", inversion: "#a83a5b" };

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
      <defs>
        <pattern id="map-grid" width="40" height="40" patternUnits="userSpaceOnUse">
          <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#e2e5ea" strokeWidth="0.5"/>
        </pattern>
        <linearGradient id="map-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   stopColor="#eef3fa"/>
          <stop offset="100%" stopColor="#dde6f1"/>
        </linearGradient>
        <filter id="map-shadow">
          <feGaussianBlur in="SourceAlpha" stdDeviation="2"/>
          <feOffset dx="0" dy="1" result="o"/>
          <feComponentTransfer><feFuncA type="linear" slope="0.18"/></feComponentTransfer>
          <feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
      </defs>

      {/* Fondo */}
      <rect width={W} height={H} fill="#fafbfc"/>
      <rect width={W} height={H} fill="url(#map-grid)"/>

      {/* Silueta país */}
      <path d={colombiaPath} fill="url(#map-fill)" stroke="#b3c5e3" strokeWidth="1.2" filter="url(#map-shadow)"/>

      {/* Líneas de paralelos / ecuador */}
      {[0, 5, 10].map(lat => {
        const y = project(lat, PROJ_BOUNDS.lngMin, W, H).y;
        return (
          <g key={lat}>
            <line x1="0" x2={W} y1={y} y2={y} stroke="#cbd5e1" strokeWidth="0.5" strokeDasharray="2 4" opacity="0.55"/>
            <text x="4" y={y - 3} className="chart-label" style={{ fontSize: 9 }}>{lat}°N</text>
          </g>
        );
      })}

      {/* Etiquetas de regiones */}
      <g style={{ fontFamily: "var(--font-mono)", fontSize: 9, fill: "#98a0ac", textTransform: "uppercase", letterSpacing: "0.12em" }}>
        <text x={project(11.2, -73.5, W, H).x} y={project(11.2, -73.5, W, H).y} textAnchor="middle">Caribe</text>
        <text x={project(7.5, -76.2, W, H).x} y={project(7.5, -76.2, W, H).y} textAnchor="middle">Pacífica</text>
        <text x={project(5.7, -73.5, W, H).x} y={project(5.7, -73.5, W, H).y} textAnchor="middle">Andina</text>
        <text x={project(4.0, -70.5, W, H).x} y={project(4.0, -70.5, W, H).y} textAnchor="middle">Orinoquía</text>
        <text x={project(0.3, -71.5, W, H).x} y={project(0.3, -71.5, W, H).y} textAnchor="middle">Amazonía</text>
      </g>

      {/* Conexiones inter-departamentales (arcos) */}
      {interDeptoLinks.map((l, i) => {
        const fc = DEPTO_COORDS[l.from], tc = DEPTO_COORDS[l.to];
        if (!fc || !tc) return null;
        const p1 = project(fc.lat, fc.lng, W, H);
        const p2 = project(tc.lat, tc.lng, W, H);
        const dx = p2.x - p1.x, dy = p2.y - p1.y;
        const mx = (p1.x + p2.x) / 2, my = (p1.y + p2.y) / 2;
        const dist = Math.sqrt(dx * dx + dy * dy);
        // Control point offset perpendicular to line for arc curve
        const offset = dist * 0.18;
        const nx = -dy / dist, ny = dx / dist;
        const cx = mx + nx * offset, cy = my + ny * offset;
        return (
          <path key={i}
            d={`M ${p1.x} ${p1.y} Q ${cx} ${cy} ${p2.x} ${p2.y}`}
            fill="none"
            stroke="#1a3a6c"
            strokeWidth={Math.min(1 + l.count * 0.6, 3)}
            strokeOpacity={0.35}/>
        );
      })}

      {/* Nodos por departamento */}
      {Object.entries(byDepto).map(([depto, list]) => {
        const coords = DEPTO_COORDS[depto];
        if (!coords) return null;
        const dept = window.DEPARTAMENTOS.find(d => d.name === depto);
        const region = dept ? dept.region : "Andina";
        const color = REGION_COLORS[region] || "#1a3a6c";
        const p = project(coords.lat, coords.lng, W, H);
        const r = 6 + Math.sqrt(list.length / maxActores) * 18;
        const isSel = selectedDepto === depto;
        const total = dept ? dept.actores : list.length;
        return (
          <g key={depto} transform={`translate(${p.x}, ${p.y})`} style={{ cursor: "pointer" }}
             onClick={() => onSelectDepto && onSelectDepto(depto, list)}>
            {isSel && <circle r={r + 8} fill="none" stroke={color} strokeWidth="2" strokeDasharray="4 3"/>}
            <circle r={r} fill={color} fillOpacity="0.22" stroke={color} strokeWidth="1.5"/>
            <circle r={Math.max(3, r * 0.32)} fill={color}/>
            <text y={r + 13} textAnchor="middle" style={{ fontSize: 10.5, fontFamily: "var(--font-sans)", fontWeight: 600, fill: "var(--c-ink-2)", pointerEvents: "none" }}>{depto}</text>
            <text y={r + 24} textAnchor="middle" style={{ fontSize: 9.5, fontFamily: "var(--font-mono)", fill: "var(--c-ink-4)", pointerEvents: "none" }}>{total.toLocaleString()} actores</text>
          </g>
        );
      })}
    </svg>
  );
}

window.ColombiaMap = ColombiaMap;
window.REGION_COLORS = REGION_COLORS;
