/* Quote Connect — Supplier Coverage Map (real Leaflet satellite map)
   - Esri World Imagery satellite tiles + place/boundary labels (towns & cities)
   - Supplier pins + true geographic coverage circles (admin-set radiusKm -> metres)
   - Sign-up mode: click the map to drop your business location
   - Admin mode: radius edits redraw the circle live */

const AU_BOUNDS = [[-44.2, 112.5], [-10.2, 154.2]];

const TILES = {
  sat: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
  labels: "https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}",
  streets: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
};

function circleStyle({ sel, edit, faded }) {
  if (faded) return { radius: 0, color: "#9fb3c8", weight: 1, opacity: 0.35, fillColor: "#9fb3c8", fillOpacity: 0.05, dashArray: "3 4" };
  if (edit) return { color: "#fe4805", weight: 2, opacity: 0.95, fillColor: "#fe4805", fillOpacity: 0.18, dashArray: "5 4" };
  if (sel) return { color: "#fe4805", weight: 1.8, opacity: 0.9, fillColor: "#fe4805", fillOpacity: 0.16, dashArray: "4 4" };
  return { color: "#fe4805", weight: 1.2, opacity: 0.55, fillColor: "#fe4805", fillOpacity: 0.1, dashArray: "4 4" };
}

function CoverageMap({ suppliers, selectedId, onSelect, mode, signupPin, onPick, editId }) {
  const elRef = React.useRef(null);
  const mapRef = React.useRef(null);
  const layersRef = React.useRef({});
  const onPickRef = React.useRef(onPick);
  const onSelectRef = React.useRef(onSelect);
  const modeRef = React.useRef(mode);
  const [base, setBase] = React.useState("sat");
  onPickRef.current = onPick; onSelectRef.current = onSelect; modeRef.current = mode;

  // init once
  React.useEffect(() => {
    if (!window.L || !elRef.current) return;
    const map = window.L.map(elRef.current, {
      zoomControl: true, attributionControl: true, minZoom: 3, maxZoom: 18,
      scrollWheelZoom: true, worldCopyJump: true,
    });
    map.fitBounds(AU_BOUNDS, { padding: [10, 10] });

    const sat = window.L.tileLayer(TILES.sat, { attribution: "Imagery © Esri, Maxar, Earthstar Geographics", maxZoom: 19 });
    const labels = window.L.tileLayer(TILES.labels, { maxZoom: 19, pane: "overlayPane" });
    const streets = window.L.tileLayer(TILES.streets, { attribution: "© OpenStreetMap contributors", maxZoom: 19 });
    sat.addTo(map); labels.addTo(map);

    const circles = window.L.layerGroup().addTo(map);
    const markers = window.L.layerGroup().addTo(map);
    const signup = window.L.layerGroup().addTo(map);

    map.on("click", (e) => {
      if (modeRef.current === "signup" && onPickRef.current) onPickRef.current(e.latlng.lng, e.latlng.lat);
    });

    layersRef.current = { sat, labels, streets, circles, markers, signup };
    mapRef.current = map;

    const ro = new ResizeObserver(() => map.invalidateSize());
    ro.observe(elRef.current);
    setTimeout(() => map.invalidateSize(), 220);

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

  // base layer toggle
  React.useEffect(() => {
    const map = mapRef.current, L = layersRef.current;
    if (!map || !L.sat) return;
    if (base === "sat") {
      if (!map.hasLayer(L.sat)) L.sat.addTo(map);
      if (!map.hasLayer(L.labels)) L.labels.addTo(map);
      if (map.hasLayer(L.streets)) map.removeLayer(L.streets);
    } else {
      if (!map.hasLayer(L.streets)) L.streets.addTo(map);
      if (map.hasLayer(L.sat)) map.removeLayer(L.sat);
      if (map.hasLayer(L.labels)) map.removeLayer(L.labels);
    }
  }, [base]);

  // markers + coverage circles
  React.useEffect(() => {
    const map = mapRef.current, L = layersRef.current;
    if (!map || !L.circles) return;
    L.circles.clearLayers(); L.markers.clearLayers();
    const faded = mode === "signup";
    suppliers.forEach((s) => {
      if (s.lat == null) return;
      const sel = s.id === selectedId, edit = s.id === editId;
      window.L.circle([s.lat, s.lng], { ...circleStyle({ sel, edit, faded }), radius: s.radiusKm * 1000 }).addTo(L.circles);
      const icon = window.L.divIcon({
        className: "cov-leaf-icon",
        html: `<span class="cov-leaf-pin ${sel ? "sel" : ""} ${faded ? "faded" : ""}"></span>`,
        iconSize: [20, 20], iconAnchor: [10, 10],
      });
      const m = window.L.marker([s.lat, s.lng], { icon, riseOnHover: true }).addTo(L.markers);
      m.bindTooltip(`${s.name} · ${s.radiusKm}km`, { direction: "top", offset: [0, -10], className: "cov-leaf-tip" });
      m.on("click", () => onSelectRef.current && onSelectRef.current(s.id));
    });
  }, [suppliers, selectedId, editId, mode]);

  // gentle pan to selected (map mode only)
  React.useEffect(() => {
    const map = mapRef.current;
    if (!map || mode !== "map") return;
    const s = suppliers.find((x) => x.id === selectedId);
    if (s && s.lat != null) map.panTo([s.lat, s.lng], { animate: true, duration: 0.5 });
  }, [selectedId]);

  // sign-up dropped pin
  React.useEffect(() => {
    const map = mapRef.current, L = layersRef.current;
    if (!map || !L.signup) return;
    L.signup.clearLayers();
    if (mode === "signup" && signupPin) {
      window.L.circle([signupPin.lat, signupPin.lng], {
        radius: (signupPin.radiusKm || 250) * 1000, color: "#0186da", weight: 1.6,
        opacity: 0.9, fillColor: "#0186da", fillOpacity: 0.14, dashArray: "5 4",
      }).addTo(L.signup);
      const icon = window.L.divIcon({ className: "cov-leaf-icon", html: `<span class="cov-leaf-drop"></span>`, iconSize: [30, 38], iconAnchor: [15, 34] });
      window.L.marker([signupPin.lat, signupPin.lng], { icon }).addTo(L.signup);
      map.panTo([signupPin.lat, signupPin.lng], { animate: true });
    }
  }, [signupPin, mode]);

  // keep size correct when layout/mode changes
  React.useEffect(() => {
    const map = mapRef.current;
    if (map) setTimeout(() => map.invalidateSize(), 60);
  }, [mode]);

  return (
    <div className={"cov-map" + (mode === "signup" ? " pickable" : "")}>
      <div ref={elRef} className="cov-leaf" />
      <div className="cov-baseswitch">
        <button className={base === "sat" ? "on" : ""} onClick={() => setBase("sat")}>Satellite</button>
        <button className={base === "streets" ? "on" : ""} onClick={() => setBase("streets")}>Map</button>
      </div>
      {mode === "signup" && !signupPin && (
        <div className="cov-hint"><span className="mono">Click anywhere on the map to set your business location</span></div>
      )}
    </div>
  );
}

window.CoverageMap = CoverageMap;
