// TARA — Indonesia food-balance choropleth (Leaflet + real province boundaries)
const { useEffect: useMapEffect, useRef: useMapRef } = React;

const TARA_SURPLUS = "#22C55E";
const TARA_DEFICIT = "#DC2626";
const TARA_NEUTRAL = "#CBD5E1";

// classification keyed on the dataset's uppercase `Propinsi`
const PROV_STATUS = {
  "JAWA TIMUR":        { s: "surplus", detail: "Surplus +1,2 juta ton", note: "Lumbung utama · stok aman >120 hari" },
  "SULAWESI SELATAN":  { s: "surplus", detail: "Surplus beras",          note: "Lumbung Indonesia Timur" },
  "NUSATENGGARA BARAT":{ s: "surplus", detail: "Surplus pangan",         note: "Termasuk wilayah lumbung" },
  "NUSA TENGGARA TIMUR":{ s: "deficit", detail: "Defisit · 23 kab. prioritas", note: "Tujuan penyaluran utama" },
  "MALUKU":            { s: "deficit", detail: "Defisit pangan",         note: "Kepulauan, distribusi sulit" },
  "MALUKU UTARA":      { s: "deficit", detail: "Defisit pangan",         note: "Logistik antarpulau mahal" },
  "IRIAN JAYA TIMUR":  { s: "deficit", detail: "Defisit pangan",         note: "Logistik antarpulau mahal" },
  "IRIAN JAYA TENGAH": { s: "deficit", detail: "Defisit pangan",         note: "Akses terbatas" },
  "IRIAN JAYA BARAT":  { s: "deficit", detail: "Defisit pangan",         note: "Akses terbatas" },
};
const STATUS_COLOR = { surplus: TARA_SURPLUS, deficit: TARA_DEFICIT, neutral: TARA_NEUTRAL };
const STATUS_PILL = {
  surplus: { bg: "#DCFCE7", fg: "#15803D" },
  deficit: { bg: "#FEE2E2", fg: "#B91C1C" },
  neutral: { bg: "#E2E8F0", fg: "#475569" },
};

function titleCase(s) {
  return s.toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase())
    .replace("Dki", "DKI").replace("Di. Aceh", "Aceh").replace("Daerah Istimewa", "D.I.");
}
function statusOf(name) { return (PROV_STATUS[name] || { s: "neutral", detail: "Neraca seimbang", note: "Produksi & konsumsi imbang" }); }

function IndonesiaMap() {
  const elRef = useMapRef(null);
  const mapRef = useMapRef(null);

  useMapEffect(() => {
    if (!window.L || !window.IDN_PROVINCES || mapRef.current) return;
    const L = window.L;

    const map = L.map(elRef.current, {
      zoomControl: false,
      attributionControl: false,
      scrollWheelZoom: false,
      doubleClickZoom: false,
      dragging: true,
      boxZoom: false,
      keyboard: false,
      zoomSnap: 0.25,
    });
    mapRef.current = map;
    L.control.zoom({ position: "bottomright" }).addTo(map);

    const tip = L.tooltip({ sticky: true, direction: "top", className: "tara-leaf-tip", opacity: 1 });

    const layer = L.geoJSON(window.IDN_PROVINCES, {
      style: (f) => {
        const st = statusOf(f.properties.Propinsi).s;
        return { fillColor: STATUS_COLOR[st], fillOpacity: 0.9, color: "#FFFFFF", weight: 1, lineJoin: "round" };
      },
      onEachFeature: (f, lyr) => {
        const name = f.properties.Propinsi;
        const info = statusOf(name);
        const pill = STATUS_PILL[info.s];
        lyr.bindTooltip(
          `<b>${titleCase(name)}</b><br><span class="t-note">${info.note}</span><br>` +
          `<span class="t-pill" style="background:${pill.bg};color:${pill.fg}">${info.detail}</span>`,
          { sticky: true, direction: "top", className: "tara-leaf-tip", opacity: 1 }
        );
        lyr.on({
          mouseover: (e) => e.target.setStyle({ weight: 2, color: "#1E293B", fillOpacity: 1 }),
          mouseout: (e) => layer.resetStyle(e.target),
        });
      },
    }).addTo(map);

    map.fitBounds(layer.getBounds(), { padding: [12, 12] });
    map.setMaxBounds(layer.getBounds().pad(0.35));

    // ---- distribution corridors ----
    const surabaya = [-7.255, 112.752];
    const kupang = [-10.178, 123.607];
    const makassar = [-5.147, 119.432];
    const jayapura = [-2.533, 140.717];
    // secondary national corridors (thinner) — consistent with Distributor page
    L.polyline([makassar, [-7.6, 121.4], kupang], {
      color: "#307FE2", weight: 1.5, opacity: 0.5, dashArray: "2 6", lineCap: "round",
    }).addTo(map);
    L.polyline([makassar, [-2.9, 130.0], jayapura], {
      color: "#307FE2", weight: 1.5, opacity: 0.5, dashArray: "2 6", lineCap: "round",
    }).addTo(map);
    // primary corridor: Surabaya (surplus) -> Kupang (deficit), via Flores sea
    const mid = [-9.6, 118.2];
    L.polyline([surabaya, mid, kupang], {
      color: "#0857C3", weight: 2.5, opacity: 0.9, dashArray: "6 5", lineCap: "round",
    }).addTo(map);

    const dot = (latlng, fill, label, anchor, sec) =>
      L.marker(latlng, {
        icon: L.divIcon({
          className: "tara-node" + (sec ? " sec" : ""),
          html: `<span class="tn-dot" style="background:${fill}"></span><span class="tn-lbl ${anchor}">${label}</span>`,
          iconSize: [10, 10], iconAnchor: [5, 5],
        }),
        interactive: false,
      }).addTo(map);
    dot(surabaya, "#0857C3", "Surabaya", "right", false);
    dot(kupang, "#DC2626", "Kupang", "left", false);
    dot(makassar, "#307FE2", "Makassar", "right", true);
    dot(jayapura, "#307FE2", "Jayapura", "left", true);

    const onResize = () => map.invalidateSize();
    window.addEventListener("resize", onResize);
    setTimeout(() => map.invalidateSize(), 200);
    return () => { window.removeEventListener("resize", onResize); map.remove(); mapRef.current = null; };
  }, []);

  return <div ref={elRef} className="idn-leaflet" />;
}

/* ---------- Corridor mini-map (Distributor) ---------- */
function CorridorMiniMap() {
  const elRef = useMapRef(null);
  const mapRef = useMapRef(null);

  useMapEffect(() => {
    if (!window.L || !window.IDN_PROVINCES || mapRef.current) return;
    const L = window.L;

    const map = L.map(elRef.current, {
      zoomControl: false, attributionControl: false, scrollWheelZoom: false,
      doubleClickZoom: false, dragging: true, boxZoom: false, keyboard: false, zoomSnap: 0.25,
    });
    mapRef.current = map;
    map.setView([-6.5, 124.0], 4);

    L.geoJSON(window.IDN_PROVINCES, {
      style: () => ({ fillColor: "#E6EDF6", fillOpacity: 1, color: "#FFFFFF", weight: 1, lineJoin: "round" }),
      interactive: false,
    }).addTo(map);

    const surabaya = [-7.255, 112.752];
    const makassar  = [-5.147, 119.432];
    const kupang    = [-10.178, 123.607];
    const jayapura  = [-2.533, 140.717];

    // secondary corridors (thinner, under)
    const c1 = L.polyline([makassar, [-7.6, 121.4], kupang], { color: "#307FE2", weight: 1.6, opacity: .5, dashArray: "2 6", lineCap: "round" }).addTo(map);
    const c2 = L.polyline([makassar, [-2.9, 130.0], jayapura], { color: "#307FE2", weight: 1.6, opacity: .5, dashArray: "2 6", lineCap: "round" }).addTo(map);
    // primary corridor on top
    const c0 = L.polyline([surabaya, [-9.6, 118.2], kupang], { color: "#0857C3", weight: 2.6, opacity: .95, dashArray: "6 5", lineCap: "round" }).addTo(map);

    const dot = (latlng, fill, label, anchor, sec) =>
      L.marker(latlng, {
        icon: L.divIcon({
          className: "tara-node" + (sec ? " sec" : ""),
          html: `<span class="tn-dot" style="background:${fill}"></span><span class="tn-lbl ${anchor}">${label}</span>`,
          iconSize: [10, 10], iconAnchor: [5, 5],
        }),
        interactive: false,
      }).addTo(map);
    dot(surabaya, "#0857C3", "Surabaya", "right", false);
    dot(kupang,   "#DC2626", "Kupang", "left", false);
    dot(makassar, "#307FE2", "Makassar", "right", true);
    dot(jayapura, "#307FE2", "Jayapura", "left", true);

    const group = L.featureGroup([c0, c1, c2]);
    const fit = () => {
      map.invalidateSize();
      map.fitBounds(group.getBounds(), { padding: [30, 56] });
    };
    setTimeout(fit, 220);

    const onResize = () => map.invalidateSize();
    window.addEventListener("resize", onResize);
    return () => { window.removeEventListener("resize", onResize); map.remove(); mapRef.current = null; };
  }, []);

  return <div ref={elRef} className="corridor-leaflet" />;
}

Object.assign(window, { IndonesiaMap, CorridorMiniMap });
