/* global React, L */
const { useEffect: useEffectMap, useRef: useRefMap } = React;

const CITY = {
  brampton: [43.7315, -79.7624],
  toronto: [43.6532, -79.3832],
  mississauga: [43.589, -79.6441],
  hamilton: [43.2557, -79.8711],
  fortErie: [42.9061, -78.9447],
  buffalo: [42.8864, -78.8784],
  windsor: [42.3149, -83.0364],
  detroit: [42.3314, -83.0458],
  london: [42.9849, -81.2453],
  scarborough: [43.7764, -79.2318],
};

/* Real, dark, premium map via Leaflet + CARTO dark-matter tiles. */
function LeafMap({ center, zoom = 7, points = [], route = [], fit = true, interactive = false, animate = true, style }) {
  const ref = useRefMap(null);
  useEffectMap(() => {
    if (!ref.current || typeof L === "undefined") return;
    const map = L.map(ref.current, {
      center: center || [43.3, -79.4],
      zoom,
      zoomControl: false,
      attributionControl: false,
      dragging: interactive,
      scrollWheelZoom: false,
      doubleClickZoom: interactive,
      boxZoom: false,
      keyboard: false,
      touchZoom: interactive,
      tap: false,
      fadeAnimation: true,
    });

    L.tileLayer("https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png", {
      subdomains: "abcd",
      maxZoom: 19,
      crossOrigin: true,
    }).addTo(map);

    if (route.length > 1) {
      L.polyline(route, { color: "#7dd3fc", weight: 1.5, opacity: 0.35 }).addTo(map);
      L.polyline(route, { color: "#38bdf8", weight: 3, opacity: 0.95, lineCap: "round" }).addTo(map);
    }

    points.forEach((p) => {
      const cls = p.hq ? "leaf-pin leaf-pin--hq" : "leaf-pin";
      const html = `<div class="${cls}" style="--pc:${p.color || "#38bdf8"}"><span class="leaf-pin__dot"></span><span class="leaf-pin__label">${p.label}</span></div>`;
      L.marker(p.at, {
        icon: L.divIcon({ className: "leaf-pin-wrap", html, iconSize: [0, 0] }),
        interactive: false,
        keyboard: false,
      }).addTo(map);
    });

    let timer;
    if (animate && route.length > 1) {
      const truck = L.marker(route[0], {
        icon: L.divIcon({ className: "leaf-truck", html: "<span></span>", iconSize: [0, 0] }),
        interactive: false,
        keyboard: false,
      }).addTo(map);
      const pts = [];
      for (let i = 0; i < route.length - 1; i++) {
        const a = route[i], b = route[i + 1];
        const steps = 40;
        for (let t = 0; t < steps; t++) pts.push([a[0] + (b[0] - a[0]) * (t / steps), a[1] + (b[1] - a[1]) * (t / steps)]);
      }
      let idx = 0;
      timer = setInterval(() => { idx = (idx + 1) % pts.length; truck.setLatLng(pts[idx]); }, 90);
    }

    if (fit && (route.length > 1 || points.length > 1)) {
      const all = [...route, ...points.map((p) => p.at)];
      map.fitBounds(L.latLngBounds(all).pad(0.28), { animate: false });
    }

    // Leaflet needs a size recalc once the panel has laid out
    const ro = new ResizeObserver(() => map.invalidateSize());
    ro.observe(ref.current);
    setTimeout(() => map.invalidateSize(), 250);

    return () => { if (timer) clearInterval(timer); ro.disconnect(); map.remove(); };
  }, []);
  return <div ref={ref} className="leaf-map" style={style} />;
}

Object.assign(window, { LeafMap, CITY });
