// Real city food maps via Leaflet + OpenStreetMap tiles (CartoDB styles).
// Pins use real lat/lng from data-extras.js. HK / LA toggle handled by parent.

window.CityFoodMap = (function() {
  const CITY_CENTER = {
    HK: { center: [22.3, 114.17], zoom: 12 },
    LA: { center: [34.05, -118.28], zoom: 11 },
  };

  function View({ city = "HK", width = 1000, theme = "light", onSelectSpot }) {
    const data = window.JAMES_EXTRAS.foodSpotsByCity[city];
    const mountRef = React.useRef(null);
    const mapRef = React.useRef(null);
    const tileRef = React.useRef(null);
    const layerRef = React.useRef(null);
    const height = Math.round(width * 0.56);

    // Initialize map once
    React.useEffect(() => {
      if (!mountRef.current || mapRef.current) return;
      if (typeof L === "undefined") {
        mountRef.current.innerHTML = '<div style="padding:20px;color:var(--mute);font-family:monospace;font-size:12px">Leaflet failed to load.</div>';
        return;
      }
      const { center, zoom } = CITY_CENTER[city];
      const map = L.map(mountRef.current, {
        center, zoom,
        zoomControl: true,
        scrollWheelZoom: false,
        attributionControl: true,
      });
      mapRef.current = map;
      layerRef.current = L.layerGroup().addTo(map);
      return () => {
        map.remove();
        mapRef.current = null;
      };
    }, []);

    // Tile layer that adapts to theme
    React.useEffect(() => {
      const map = mapRef.current; if (!map) return;
      if (tileRef.current) { map.removeLayer(tileRef.current); tileRef.current = null; }
      const tileUrl = theme === "dark"
        ? "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
        : "https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png";
      tileRef.current = L.tileLayer(tileUrl, {
        attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> · © <a href="https://carto.com/attributions">CARTO</a>',
        subdomains: "abcd",
        maxZoom: 19,
      }).addTo(map);
    }, [theme]);

    // Re-target map + redraw pins when city or data changes
    React.useEffect(() => {
      const map = mapRef.current; const layer = layerRef.current;
      if (!map || !layer) return;
      const { center, zoom } = CITY_CENTER[city];
      map.setView(center, zoom, { animate: true });
      layer.clearLayers();

      const accent = getComputedStyle(document.documentElement).getPropertyValue("--accent").trim() || "#d73a49";
      const paper = getComputedStyle(document.documentElement).getPropertyValue("--paper").trim() || "#fffaf0";
      const ink = getComputedStyle(document.documentElement).getPropertyValue("--ink").trim() || "#1a1612";

      data.spots.forEach(s => {
        const isBar = s.kind === "bar";
        const pinColor = isBar ? "#1a1612" : accent;
        const icon = L.divIcon({
          className: "jg-food-pin",
          html: `<div style="width:14px;height:14px;border-radius:${isBar ? "3px" : "99px"};background:${pinColor};border:2px solid ${paper};box-shadow:0 1px 4px rgba(0,0,0,0.35);position:relative;transform:${isBar ? "rotate(45deg)" : "none"}"><div style="position:absolute;inset:-6px;border-radius:99px;background:${pinColor};opacity:0.2"></div></div>`,
          iconSize: [14, 14],
          iconAnchor: [7, 7],
        });
        const m = L.marker([s.lat, s.lng], { icon })
          .addTo(layer)
          .bindTooltip(
            `<div style="font-family:'Geist',system-ui,sans-serif;min-width:160px">
               <div style="font-family:'Instrument Serif',serif;font-size:18px;line-height:1.15;color:${ink}">${s.name}${isBar ? ' <span style="font-family:\'JetBrains Mono\',monospace;font-size:9px;letter-spacing:0.12em;color:#8a8478;vertical-align:middle;margin-left:4px">· BAR</span>' : ""}</div>
               <div style="font-family:'JetBrains Mono',monospace;font-size:10px;color:#8a8478;margin:3px 0 4px;letter-spacing:0.06em">${s.neighborhood.toUpperCase()}</div>
               <div style="font-size:12.5px;color:${ink}">${s.dish}</div>
               <div style="color:${accent};letter-spacing:2px;margin-top:4px;font-size:11px">${"★".repeat(s.rating)}<span style="opacity:0.2">${"★".repeat(5 - s.rating)}</span></div>
             </div>`,
            { direction: "top", offset: [0, -6], opacity: 1, className: "jg-food-tooltip" }
          );
        if (onSelectSpot) m.on("click", () => onSelectSpot(s));
      });

      // Fit bounds around the pins so LA's spread stays visible
      const bounds = L.latLngBounds(data.spots.map(s => [s.lat, s.lng]));
      if (bounds.isValid()) map.fitBounds(bounds, { padding: [40, 40], maxZoom: 13 });
    }, [city, data]);

    // Resize handling
    React.useEffect(() => {
      const map = mapRef.current; if (!map) return;
      setTimeout(() => map.invalidateSize(), 0);
    }, [width]);

    return (
      <div style={{ position: "relative", width: "100%", height, background: "var(--paper)", borderRadius: 8, overflow: "hidden", border: "1px solid var(--rule)" }}>
        <div ref={mountRef} style={{ width: "100%", height: "100%" }} />
        <style>{`
          .jg-food-tooltip { background: var(--paper) !important; border: 1px solid var(--rule) !important; border-radius: 6px !important; padding: 10px 12px !important; box-shadow: 0 6px 20px rgba(0,0,0,0.15) !important; }
          .jg-food-tooltip::before { border-top-color: var(--rule) !important; }
          .leaflet-container { background: var(--paper) !important; font-family: inherit; }
          .leaflet-control-attribution { font-size: 9.5px !important; background: rgba(255,250,240,0.8) !important; }
        `}</style>
      </div>
    );
  }

  return { View };
})();
