/* global React, L, FIELDS, FARM_COORDS */
/**
 * Visor satelital + suelos INTA (WMS vivo, sin shapefile).
 * El mapa vive dentro del panel para convivir con el HUD.
 */
function FieldMap({ selectedId, onSelect, onProfile, showSoils, showNdvi }) {
  const { useRef, useEffect } = React;
  const elRef = useRef(null);
  const mapRef = useRef(null);
  const layersRef = useRef({});
  const onSelectRef = useRef(onSelect);
  const onProfileRef = useRef(onProfile);
  onSelectRef.current = onSelect;
  onProfileRef.current = onProfile;

  function fetchProfile(lat, lng, field) {
    if (onProfileRef.current) onProfileRef.current({ loading: true, field });
    const qs = new URLSearchParams({ lat, lng });
    if (field) {
      qs.set("fieldId", field.id);
      qs.set("fieldName", field.name);
    }
    fetch(`/api/visor?${qs}`)
      .then((r) => r.json())
      .then((data) => {
        window.__VISOR_SOIL = data;
        if (onProfileRef.current) onProfileRef.current(data);
      })
      .catch((err) => onProfileRef.current && onProfileRef.current({ ok: false, error: String(err) }));
  }

  useEffect(() => {
    if (!elRef.current || !window.L || mapRef.current) return undefined;
    const esri = L.tileLayer(
      "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
      { maxZoom: 18, attribution: "Esri World Imagery" }
    );
    const soils = L.tileLayer.wms("https://geo-backend.inta.gob.ar/geoserver/wms", {
      layers: "geonode:suelos_argentina_1_500",
      format: "image/png",
      transparent: true,
      version: "1.1.1",
      opacity: 0.52,
      attribution: "INTA 1:500.000",
    });
    const ndvi = L.tileLayer.wms("https://gibs.earthdata.nasa.gov/wms/epsg3857/best/wms.cgi", {
      layers: "MODIS_Terra_NDVI_8Day",
      format: "image/png",
      transparent: true,
      version: "1.1.1",
      opacity: 0.45,
    });
    const map = L.map(elRef.current, {
      zoomControl: false,
      attributionControl: true,
      center: [FARM_COORDS.lat, FARM_COORDS.lng],
      zoom: 14,
      layers: [esri, soils],
    });
    const lotGroup = L.featureGroup().addTo(map);
    const polygons = {};
    (FIELDS || []).forEach((f) => {
      if (!f.coordinates) return;
      const poly = L.polygon(f.coordinates, {
        color: "#f2f3ea",
        weight: 1.4,
        fillColor: "#c6e84b",
        fillOpacity: 0.1,
      });
      poly.on("click", (ev) => {
        L.DomEvent.stopPropagation(ev);
        if (onSelectRef.current) onSelectRef.current(f.id);
        const c = f.center || ev.latlng;
        const lat = Array.isArray(c) ? c[0] : c.lat;
        const lng = Array.isArray(c) ? c[1] : c.lng;
        fetchProfile(lat, lng, f);
      });
      poly.bindTooltip(f.name, { sticky: true, opacity: 0.9 });
      poly.addTo(lotGroup);
      polygons[f.id] = poly;
    });
    if (lotGroup.getLayers().length) map.fitBounds(lotGroup.getBounds().pad(0.18));
    map.on("click", (e) => fetchProfile(e.latlng.lat, e.latlng.lng, null));
    const importGroup = L.featureGroup().addTo(map);
    const stationGroup = L.featureGroup().addTo(map);
    layersRef.current = { map, esri, soils, ndvi, lotGroup, polygons, importGroup, stationGroup, stations: {} };
    mapRef.current = map;
    window.__PAMPA_MAP = map;
    window.__PAMPA_VISOR = {
      addGeoJSON(gj, opts) {
        opts = opts || {};
        importGroup.clearLayers();
        const layer = L.geoJSON(gj, {
          style: {
            color: opts.color || "#7ec8ff",
            weight: 2,
            fillColor: opts.fill || "#7ec8ff",
            fillOpacity: 0.22,
          },
          pointToLayer: (_f, latlng) => L.circleMarker(latlng, {
            radius: 6, color: "#7ec8ff", fillColor: "#c6e84b", fillOpacity: 0.9, weight: 1,
          }),
          onEachFeature: (feat, lyr) => {
            const p = feat.properties || {};
            const title = p.name || p.NAME || p.lote || "Capa importada";
            lyr.bindTooltip(String(title));
          },
        });
        layer.addTo(importGroup);
        if (importGroup.getLayers().length) map.fitBounds(importGroup.getBounds().pad(0.12));
        return importGroup;
      },
      addStation(st) {
        if (!st || st.lat == null || st.lng == null) return;
        const prev = layersRef.current.stations[st.id];
        if (prev) stationGroup.removeLayer(prev);
        const html =
          `<strong>${st.name || "Estación"}</strong><br/>` +
          (st.t != null ? `T ${Number(st.t).toFixed(1)} °C<br/>` : "") +
          (st.rh != null ? `HR ${Number(st.rh).toFixed(0)} %<br/>` : "") +
          (st.wind != null ? `Viento ${Number(st.wind).toFixed(1)} km/h<br/>` : "") +
          `<span style="opacity:.7">${st.source || ""}</span>`;
        const m = L.circleMarker([st.lat, st.lng], {
          radius: 8,
          color: "#f5d76e",
          fillColor: "#f5d76e",
          fillOpacity: 0.95,
          weight: 2,
        }).bindPopup(html);
        m.addTo(stationGroup);
        layersRef.current.stations[st.id] = m;
      },
      clearImported() { importGroup.clearLayers(); },
    };
    if (window.__IMPORT_LAYER && window.__IMPORT_LAYER.geojson) {
      window.__PAMPA_VISOR.addGeoJSON(window.__IMPORT_LAYER.geojson);
    }
    if (window.__STATIONS) {
      Object.keys(window.__STATIONS).forEach((id) => window.__PAMPA_VISOR.addStation(window.__STATIONS[id]));
    }
    setTimeout(() => map.invalidateSize(), 80);
    return () => {
      map.remove();
      mapRef.current = null;
      window.__PAMPA_MAP = null;
      window.__PAMPA_VISOR = null;
    };
  }, []);

  useEffect(() => {
    const Lr = layersRef.current;
    const map = mapRef.current;
    if (!map || !Lr.soils) return;
    if (showSoils) {
      if (!map.hasLayer(Lr.soils)) Lr.soils.addTo(map);
    } else if (map.hasLayer(Lr.soils)) map.removeLayer(Lr.soils);
    if (showNdvi) {
      if (!map.hasLayer(Lr.ndvi)) Lr.ndvi.addTo(map);
    } else if (map.hasLayer(Lr.ndvi)) map.removeLayer(Lr.ndvi);
  }, [showSoils, showNdvi]);

  useEffect(() => {
    const polys = layersRef.current.polygons || {};
    Object.entries(polys).forEach(([id, poly]) => {
      const on = id === selectedId;
      poly.setStyle({
        color: on ? "#c6e84b" : "#f2f3ea",
        weight: on ? 3 : 1.4,
        fillOpacity: on ? 0.26 : 0.1,
      });
    });
  }, [selectedId]);

  return (
    <div
      ref={elRef}
      style={{ position: "absolute", inset: 0, borderRadius: 28, zIndex: 0 }}
    />
  );
}
window.FieldMap = FieldMap;
