/* Maps component — Leaflet map with thicker borders, higher contrast */
const { useEffect: useEffM, useRef: useRefM, useState: useStateM } = React;

const EU_LOCATIONS = [
  { id: "vie", lat: 48.2082, lng: 16.3738, label: "Vienna",         region: "Austria",  count: 10, kind: "point",
    detail: "Tire sales & service · Auto repair · Auto sales · Electrical · HVAC · Car painting · Renovation" },
  { id: "stm", lat: 47.0707, lng: 15.4395, label: "Styria · Graz",   region: "Austria",  count: 2,  kind: "point",
    detail: "Tire sales & service (1) · B2B tire sales (1)" },
  { id: "noe", lat: 48.6000, lng: 15.6500, label: "Lower Austria",   region: "Austria",  count: 1,  kind: "point",
    detail: "Tire sales & service (1)" },
  { id: "ooe", lat: 48.3069, lng: 14.2858, label: "Upper Austria",   region: "Austria",  count: 1,  kind: "point",
    detail: "Tire sales & service (1)" },
  { id: "fra", lat: 50.1109, lng: 8.6821,  label: "Frankfurt area",  region: "Germany",  count: 2,  kind: "point",
    detail: "Tire sales & service (2)" },
  { id: "muc", lat: 48.1351, lng: 11.5820, label: "Munich area",     region: "Germany",  count: 1,  kind: "point",
    detail: "Tire sales & service (1)" },
];

const US_LOCATIONS = [
  { id: "nyc", lat: 40.7128, lng: -74.0060, label: "New York",        region: "Headquarters", kind: "point", count: 1,
    detail: "Erdem Holdings · United States acquisition platform" },
  { id: "ne",  lat: 41.5,    lng: -73.5,    label: "Northeast",       region: "Active sourcing", kind: "star",
    detail: "Service businesses across the Northeast corridor" },
  { id: "se",  lat: 33.5,    lng: -82.0,    label: "Southeast",       region: "Active sourcing", kind: "star",
    detail: "Carolinas, Georgia, Florida service markets" },
  { id: "mw",  lat: 41.5,    lng: -86.0,    label: "Midwest",         region: "Active sourcing", kind: "star",
    detail: "Ohio, Indiana, Illinois, Michigan service markets" },
  { id: "tx",  lat: 31.5,    lng: -98.5,    label: "Texas",           region: "Active sourcing", kind: "star",
    detail: "Texas service businesses" },
  { id: "mt",  lat: 39.0,    lng: -106.0,   label: "Mountain West",   region: "Active sourcing", kind: "star",
    detail: "Colorado, Utah, Arizona service markets" },
];

function makeMarker(loc) {
  const isStar = loc.kind === "star";
  const html = isStar
    ? `<div class=\"lm lm-star\"><svg width=\"22\" height=\"22\" viewBox=\"-11 -11 22 22\"><path d=\"M 0 -9 L 2.4 -2.8 L 9 -2.8 L 3.5 1.1 L 5.6 7.5 L 0 4 L -5.6 7.5 L -3.5 1.1 L -9 -2.8 L -2.4 -2.8 Z\" fill=\"#16302a\" stroke=\"#f3efe1\" stroke-width=\"1.2\"/></svg></div>`
    : `<div class=\"lm lm-point\"><span class=\"lm-pulse\"></span><span class=\"lm-dot\">${loc.count && loc.count > 1 ? loc.count : ""}</span></div>`;
  const icon = L.divIcon({
    className: "lm-wrap",
    html,
    iconSize: [36, 36],
    iconAnchor: [18, 18],
  });
  const m = L.marker([loc.lat, loc.lng], { icon, riseOnHover: true });
  const popup = `
    <div class="lm-pop">
      <div class="lm-pop-eyebrow">${isStar ? "Active sourcing" : "Operating"} · ${loc.region}</div>
      <div class="lm-pop-title">${loc.label}${loc.count && loc.count > 1 ? ` <span style="color:var(--accent)">${loc.count}</span>` : ""}</div>
      <div class="lm-pop-body">${loc.detail}</div>
    </div>`;
  m.bindPopup(popup, { closeButton: false, offset: [0, -6], maxWidth: 320 });
  m.on("mouseover", function () { this.openPopup(); });
  m.on("mouseout",  function () { this.closePopup(); });
  return m;
}

function LeafletMapPanel({ which, setWhich }) {
  const elRef = useRefM(null);
  const mapRef = useRefM(null);
  const layerRef = useRefM(null);
  const [ready, setReady] = useStateM(false);

  useEffM(() => {
    if (!elRef.current || mapRef.current) return;
    const map = L.map(elRef.current, {
      zoomControl: true,
      scrollWheelZoom: false,
      attributionControl: true,
      worldCopyJump: false,
    });
    L.tileLayer("https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png", {
      attribution: "&copy; OpenStreetMap &copy; CARTO",
      subdomains: "abcd",
      maxZoom: 18,
    }).addTo(map);
    L.tileLayer("https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}{r}.png", {
      subdomains: "abcd",
      maxZoom: 18,
      pane: "shadowPane",
      opacity: 0.55,
    }).addTo(map);

    mapRef.current = map;
    setReady(true);
  }, []);

  useEffM(() => {
    if (!ready || !mapRef.current) return;
    const map = mapRef.current;
    if (layerRef.current) {
      map.removeLayer(layerRef.current);
      layerRef.current = null;
    }
    const isEU = which === "eu";
    const locs = isEU ? EU_LOCATIONS : US_LOCATIONS;
    const group = L.featureGroup(locs.map(l => makeMarker(l)));
    group.addTo(map);
    layerRef.current = group;

    if (isEU) map.setView([49.5, 13.5], 6);   // was 5
    else      map.setView([39.5, -96.5], 5);   // was 4
    setTimeout(() => map.invalidateSize(), 60);
  }, [ready, which]);

  return (
    <div className="map-card">
      <div className="map-head">
        <div>
          <div className="kicker">{which === "eu" ? "Map 01 · Europe" : "Map 02 · United States"}</div>
          <h3 className="h-sub serif" style={{ marginTop: 10 }}>
            {which === "eu" ? "European operating footprint" : "Acquisition program"}
          </h3>
          <p className="small" style={{ marginTop: 6, color: "var(--mute)" }}>
            {which === "eu"
              ? "The Erdem family operating group — businesses by category and region."
              : "Geographies of active acquisition sourcing — profitable service businesses, $500K – $3M EBITDA."}
          </p>
        </div>
        <div className="map-toggle">
          <button className={"map-tog-btn" + (which === "eu" ? " active" : "")} onClick={() => setWhich("eu")}>
            <span className="dot" /> Europe
          </button>
          <button className={"map-tog-btn" + (which !== "eu" ? " active" : "")} onClick={() => setWhich("us")}>
            <span className="dot star" /> United States
          </button>
        </div>
      </div>

      <div className="leaflet-stage">
        <div ref={elRef} className="leaflet-el" />
        <div className="map-corner mono">
          {which === "eu" ? "48.2°N · 16.4°E" : "39.5°N · 96.5°W"}
        </div>
      </div>

      <div className="map-legend">
        <div className="legend-item">
          <span className="legend-glyph">
            <svg width="22" height="22" viewBox="-11 -11 22 22"><circle r="7" fill="var(--accent)" stroke="var(--bg)" strokeWidth="2" /></svg>
          </span>
          <span>Operating company</span>
        </div>
        <div className="legend-item">
          <span className="legend-glyph">
            <svg width="22" height="22" viewBox="-11 -11 22 22">
              <path d="M 0 -9 L 2.4 -2.8 L 9 -2.8 L 3.5 1.1 L 5.6 7.5 L 0 4 L -5.6 7.5 L -3.5 1.1 L -9 -2.8 L -2.4 -2.8 Z" fill="var(--accent-2)" stroke="var(--bg)" strokeWidth="1.2" />
            </svg>
          </span>
          <span>Active acquisition focus</span>
        </div>
        <div className="legend-item">
          <span className="small" style={{ color: "var(--mute)" }}>Hover any marker for detail.</span>
        </div>
      </div>
    </div>
  );
}

window.LeafletMapPanel = LeafletMapPanel;