/* mapa.jsx — mapa REAL OpenStreetMap (Leaflet) del GBA. Markers de camión (iconos por tipo) +
   burbuja por paquetes + haz desde el depósito. Reactivo a las rutas. window.CR.Mapa. */
(function () {
  window.CR = window.CR || {};
  var React = window.React;
  var h = React.createElement;
  var K = window.CR.const;

  // centroides aproximados de cada zona del GBA + depósito (centro de distribución)
  var DEPOT = [-34.6118, -58.4440];
  var ZC = { N: [-34.512, -58.495], O: [-34.642, -58.620], E: [-34.665, -58.365], S: [-34.770, -58.400] };
  var UNIT = { CAM: 'camioneta', CHL: 'chasis_liviano', CHE: 'chasis_estandar', CHP: 'chasis_pesado' };

  function tiles(theme) {
    var dark = theme === 'dark';
    return window.L.tileLayer(
      'https://{s}.basemaps.cartocdn.com/' + (dark ? 'dark_all' : 'light_all') + '/{z}/{x}/{y}{r}.png',
      { maxZoom: 19, subdomains: 'abcd', attribution: '© OpenStreetMap · © CARTO' });
  }

  function Mapa(props) {
    var mapEl = React.useRef(null);
    var mapRef = React.useRef(null);
    var layerRef = React.useRef(null);
    var tileRef = React.useRef(null);

    function curTheme() { return document.documentElement.getAttribute('data-theme') || 'dark'; }

    function draw() {
      var L = window.L, map = mapRef.current, layer = layerRef.current;
      if (!L || !map || !layer || !map._loaded || !mapEl.current) return;
      try { drawInner(L, map, layer); } catch (e) { /* re-dibujo durante transición/zoom: lo ignoramos */ }
    }
    function drawInner(L, map, layer) {
      layer.clearLayers();
      var rutas = props.rutas || [];
      var choferes = props.choferes || [];
      var cById = {}; choferes.forEach(function (c) { cById[c.id] = c; });
      var maxPk = Math.max.apply(null, rutas.map(function (r) { return r.paquetes; }).concat([1]));

      // depósito
      L.marker(DEPOT, { icon: L.divIcon({ className: '', iconSize: [38, 38], iconAnchor: [19, 19],
        html: '<div class="cr-depot"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M3 11l9-8 9 8M5 10v10h14V10"/></svg></div>' }) })
        .addTo(layer).bindTooltip('Centro de distribución', { direction: 'top' });

      // agrupar por zona para jitter
      var byZona = {}; rutas.forEach(function (r) { (byZona[r.zona] = byZona[r.zona] || []).push(r); });
      Object.keys(byZona).forEach(function (z) {
        var arr = byZona[z]; var c = ZC[z]; if (!c) return;
        arr.forEach(function (r, i) {
          var ang = (Math.PI * 2 * i) / Math.max(1, arr.length) - Math.PI / 2;
          var off = arr.length > 1 ? 0.022 : 0;
          var lat = c[0] + Math.sin(ang) * off, lng = c[1] + Math.cos(ang) * off;
          // haz desde depósito (animado vía CSS .cr-beam)
          L.polyline([DEPOT, [lat, lng]], { color: '#1a73e8', weight: 2, opacity: .5, dashArray: '6 8', className: 'cr-beam' }).addTo(layer);
          // marker
          var ph = !r.vehiculoId && !r.choferId; // carga sin camión (sin cubrir)
          var over = ph || (r.discrepancia && (r.discrepancia.tipo === 'sobrecarga'));
          var D = Math.round(34 + Math.sqrt(r.paquetes / maxPk) * 34); // 34..68
          var op = (0.55 + Math.min(1, r.paquetes / (r.capacidad || r.paquetes)) * 0.4).toFixed(2);
          var chofer = cById[r.choferId];
          var unit = UNIT[r.tipoUnidad] || 'chasis_estandar';
          var top = ph
            ? '<div class="truck" style="width:30px;height:33px;display:flex;align-items:center;justify-content:center;font-size:22px">⚠</div>'
            : '<img class="truck" src="assets/icons/units/' + unit + '_marker.svg" style="width:30px;height:33px;filter:drop-shadow(0 2px 3px rgba(0,0,0,.4))"/>';
          var html =
            '<div class="cr-marker">' +
              top +
              '<div class="bub' + (over ? ' over' : '') + '" style="width:' + D + 'px;height:' + D + 'px;font-size:' + (D > 50 ? 15 : 12) + 'px;background:rgba(26,115,232,' + op + ')">' + r.paquetes + '</div>' +
              '<div class="lbl">' + (ph ? 'sin cubrir' : (r.numero || '') + (chofer ? ' · ' + chofer.nombre : '')) + '</div>' +
            '</div>';
          L.marker([lat, lng], { icon: L.divIcon({ className: '', iconSize: [D, D + 50], iconAnchor: [D / 2, D / 2 + 16], html: html }) })
            .addTo(layer)
            .bindTooltip(K.labelZona(z) + ' · ' + (r.tipoUnidad ? K.labelTipo(r.tipoUnidad) : '') + ' · ' + r.paquetes + '/' + r.capacidad + ' paquetes', { direction: 'top' });
        });
      });
    }

    React.useEffect(function () {
      var L = window.L;
      if (!L) { return; }
      var map = L.map(mapEl.current, { zoomControl: true, attributionControl: true, scrollWheelZoom: true, wheelPxPerZoomLevel: 90 }).setView([-34.63, -58.45], 10);
      mapRef.current = map;
      tileRef.current = tiles(curTheme()); tileRef.current.addTo(map);
      layerRef.current = L.layerGroup().addTo(map);
      var t0 = setTimeout(function () { if (!mapRef.current) return; try { map.invalidateSize(); } catch (e) {} draw(); }, 150);
      // observar cambio de tema -> swap tiles
      var obs = new MutationObserver(function () {
        if (!mapRef.current) return;
        try { if (tileRef.current) map.removeLayer(tileRef.current); tileRef.current = tiles(curTheme()); tileRef.current.addTo(map); } catch (e) {}
      });
      obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
      return function () { clearTimeout(t0); obs.disconnect(); mapRef.current = null; try { map.remove(); } catch (e) {} };
    }, []);

    var sig = (props.rutas || []).map(function (r) { return r.id + ':' + r.paquetes + ':' + r.choferId + ':' + r.tipoUnidad; }).join('|');
    React.useEffect(function () { draw(); }, [sig]);

    if (!window.L) {
      return h('div', { className: 'mapa-wrap' }, h('div', { className: 'empty' }, h('h3', null, 'Mapa no disponible'), h('p', { className: 'muted' }, 'No se pudo cargar Leaflet (¿sin internet?).')));
    }
    return h('div', { className: 'mapa-wrap' },
      h('div', { ref: mapEl, className: 'mapa-leaf' }),
      h('div', { className: 'mapa-legend' },
        h('span', null, h('i', { className: 'lg-dot', style: { background: 'var(--primary)', opacity: .6 } }), 'Tamaño = paquetes · color más fuerte = más lleno'),
        h('span', null, h('i', { className: 'lg-dot', style: { background: 'var(--danger)' } }), 'Sobrecarga'),
        h('span', { className: 'muted' }, 'Mapa © OpenStreetMap · CARTO')));
  }

  window.CR.Mapa = Mapa;
})();
