"use client";

import "leaflet/dist/leaflet.css";
import { useEffect, useRef } from "react";

export type MapPin = { location: string; name: string; description?: string; lat: number; lng: number };

/**
 * The pins of the static page's map (were assets/js/global-presence-map.js). The map
 * shows them while the page shows its built-in content; once the offices are published
 * in the CMS, the pins are the offices that have a position.
 */
export const BUILT_IN_PINS: MapPin[] = [
  { location: "Vancouver, Canada", name: "North America Office", description: "West Coast Hub", lat: 49.2827, lng: -123.1207 },
  { location: "Minneapolis, USA", name: "North America HQ", description: "Great Lakes Operations", lat: 44.9778, lng: -93.265 },
  { location: "Dallas, USA", name: "North America HQ", description: "US South Operations", lat: 32.7767, lng: -96.797 },
  { location: "Kyiv, Ukraine", name: "Europe Office", description: "European Operations", lat: 50.4501, lng: 30.5234 },
  { location: "Nur-Sultan, Kazakhstan", name: "Central Asia Office", description: "Regional Trade Point", lat: 51.1801, lng: 71.446 },
  { location: "Shanghai, China", name: "China Trade Division", description: "Supply Chain Network", lat: 31.2304, lng: 121.4737 },
  { location: "Kano, Nigeria", name: "West Africa Logistics", description: "Supply Chain Hub", lat: 12.0022, lng: 8.592 },
  { location: "Hyderabad, India", name: "South-Asia Hub", description: "Agri & Export Base", lat: 17.385, lng: 78.4867 },
];

/** Popup of one pin: every office at that position (text only, never HTML). */
function popup(offices: MapPin[]): HTMLElement {
  const el = document.createElement("div");
  offices.forEach((o, i) => {
    if (i > 0) el.append(document.createElement("br"), document.createElement("br"));
    const city = document.createElement("strong");
    city.textContent = o.location;
    el.append(city, document.createElement("br"), o.name);
    if (o.description) {
      const d = document.createElement("span");
      d.style.cssText = "color:#2E2E2E;font-size:12px";
      d.textContent = o.description;
      el.append(document.createElement("br"), d);
    }
  });
  return el;
}

/**
 * Global Presence: the interactive office map (Leaflet, Esri tiles). Offices sharing a
 * position share a pin. Without pins the map shows the world.
 */
export function OfficeMap({ pins = BUILT_IN_PINS }: { pins?: MapPin[] }) {
  const ref = useRef<HTMLDivElement>(null);
  const key = JSON.stringify(pins);
  useEffect(() => {
    const mapEl = ref.current;
    if (!mapEl) return;
    const list: MapPin[] = JSON.parse(key);
    let disposed = false;
    let destroy = () => {};
    import("leaflet").then(({ default: L }) => {
      if (disposed) return;
      const map = L.map(mapEl, { scrollWheelZoom: false, zoomControl: true, attributionControl: true });
      L.tileLayer("https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", {
        attribution:
          "Tiles &copy; Esri &mdash; Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012",
      }).addTo(map);
      const pinIcon = L.divIcon({
        className: "leaflet-office-pin",
        html: '<span class="leaflet-office-pin-dot" aria-hidden="true"></span>',
        iconSize: [28, 28],
        iconAnchor: [14, 28],
        popupAnchor: [0, -28],
      });
      const byPosition = new Map<string, MapPin[]>();
      list.forEach((o) => {
        const at = `${o.lat},${o.lng}`;
        byPosition.set(at, [...(byPosition.get(at) ?? []), o]);
      });
      const bounds: [number, number][] = [];
      byPosition.forEach((offices) => {
        const { lat, lng } = offices[0];
        L.marker([lat, lng], { icon: pinIcon }).addTo(map).bindPopup(popup(offices), { className: "office-map-popup" });
        bounds.push([lat, lng]);
      });
      if (bounds.length) map.fitBounds(bounds, { padding: [30, 24], maxZoom: 3 });
      else map.setView([20, 0], 2);
      const enable = () => map.scrollWheelZoom.enable();
      const disable = () => map.scrollWheelZoom.disable();
      mapEl.addEventListener("click", enable);
      mapEl.addEventListener("mouseleave", disable);
      destroy = () => {
        mapEl.removeEventListener("click", enable);
        mapEl.removeEventListener("mouseleave", disable);
        map.remove();
      };
    });
    return () => {
      disposed = true;
      destroy();
    };
  }, [key]);

  return (
    <div
      ref={ref}
      id="global-offices-map"
      className="global-offices-map"
      role="region"
      aria-label="Interactive map of Unionists Group global office locations"
    ></div>
  );
}
