// MapHero — real Leaflet map with CartoDB Voyager tiles and custom HTML pins.
// Props & behavior preserved from the SVG stand-in.

const MapHero = ({ stores, activeStoreSlug, onPinClick, pulsingSlug, clusters = [], onClusterClick }) => {
  const mapEl = React.useRef(null);
  const mapRef = React.useRef(null);
  const markerLayerRef = React.useRef(null);

  const categoryColor = {
    pokemon_center: "#EF4444",
    yodobashi: "#F59E0B",
    bic_camera: "#F59E0B",
    aeon: "#10B981",
    yamada: "#3B82F6",
    toys_r_us: "#EC4899",
    other: "#6B7280",
  };
  const secondaryColor = {
    lottery: "#3B82F6",
    preorder: "#10B981",
    walk_in: "#F59E0B",
  };

  // Build the HTML for one pin — preserves the original brand+badge+secondary+pulse look.
  const pinHtml = (s) => {
    const color = categoryColor[s.category] || "#6B7280";
    const active = s.slug === activeStoreSlug;
    const pulsing = s.slug === pulsingSlug;
    const secondary = s.secondaryType && secondaryColor[s.secondaryType];
    const shadow = active
      ? "drop-shadow(0 3px 6px rgba(0,0,0,0.25))"
      : "drop-shadow(0 1px 2px rgba(0,0,0,0.2))";
    const pulse = pulsing
      ? `<span class="ph-pulse" style="background:${color}33;"></span>`
      : "";
    const badge = s.ongoingCount > 0
      ? `<span class="ph-badge">${s.ongoingCount}</span>`
      : "";
    const sec = secondary
      ? `<span class="ph-sec" style="background:${secondary};"></span>`
      : "";
    return `
      <div class="ph-pin" title="${(s.name_zh || s.name_ja || '').replace(/"/g,'&quot;')}">
        ${pulse}
        <svg width="22" height="28" viewBox="-11 -22 22 28" style="filter:${shadow};">
          <path d="M 0 0 C 0 0 -10 -11 -10 -18 A 10 10 0 1 1 10 -18 C 10 -11 0 0 0 0 Z"
                fill="${color}" stroke="#fff" stroke-width="2"/>
          <circle cx="0" cy="-18" r="4.5" fill="#fff"/>
        </svg>
        ${sec}
        ${badge}
      </div>
    `;
  };

  const clusterHtml = (c) => `
    <div class="ph-cluster" title="點擊展開 ${c.count} 家店">
      <span>${c.count}</span>
    </div>
  `;

  // 1) Initialize map once
  React.useEffect(() => {
    if (!mapEl.current || mapRef.current) return;
    const map = L.map(mapEl.current, {
      center: [35.685, 139.76],  // 東京中心
      zoom: 12,
      zoomControl: true,
      scrollWheelZoom: true,
      attributionControl: true,
    });
    L.tileLayer("https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png", {
      attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> · © <a href="https://carto.com/">CartoDB</a>',
      subdomains: "abcd",
      maxZoom: 20,
    }).addTo(map);
    markerLayerRef.current = L.layerGroup().addTo(map);
    mapRef.current = map;
    // Watch container size — re-fit pins when timeline resize changes map height
    const ro = new ResizeObserver(() => {
      map.invalidateSize();
      const pts = Object.values(markerLayerRef.current?._layers || {})
        .map(m => m.getLatLng())
        .filter(Boolean);
      if (pts.length > 0) {
        map.fitBounds(L.latLngBounds(pts), { padding: [40, 40], maxZoom: 14, animate: false });
      }
    });
    ro.observe(mapEl.current);
    return () => {
      ro.disconnect();
      map.remove();
      mapRef.current = null;
      markerLayerRef.current = null;
    };
  }, []);

  // 2) Re-render markers when stores / active / pulsing / clusters change
  React.useEffect(() => {
    const layer = markerLayerRef.current;
    if (!layer) return;
    layer.clearLayers();

    // Clusters first (so pins render on top)
    clusters.forEach(c => {
      const icon = L.divIcon({
        className: "ph-cluster-wrap",
        html: clusterHtml(c),
        iconSize: [36, 36],
        iconAnchor: [18, 18],
      });
      L.marker([c.latitude, c.longitude], { icon })
        .on("click", () => onClusterClick?.(c))
        .addTo(layer);
    });

    // Pins
    const latLngs = [];
    stores.forEach(s => {
      const icon = L.divIcon({
        className: "ph-pin-wrap",
        html: pinHtml(s),
        iconSize: [22, 28],
        iconAnchor: [11, 28],
      });
      const m = L.marker([s.latitude, s.longitude], { icon })
        .on("click", () => onPinClick?.(s.slug))
        .addTo(layer);
      latLngs.push([s.latitude, s.longitude]);
      // Hover tooltip only — details live in the StoreDrawer on click
      m.bindTooltip(s.name_zh || s.name_ja || "", {
        direction: "top", offset: [0, -24], className: "ph-tooltip",
      });
    });

    // Auto-fit so no pin is clipped at the edges (only on initial render with pins)
    if (latLngs.length > 0 && !mapRef.current._autoFitted) {
      const bounds = L.latLngBounds(latLngs);
      mapRef.current.fitBounds(bounds, { padding: [40, 40], maxZoom: 14 });
      mapRef.current._autoFitted = true;
    }
  }, [stores, activeStoreSlug, pulsingSlug, clusters]);

  const isMobile = useIsMobile();
  return (
    <div style={{
      flex: isMobile ? "0 0 auto" : 1,
      height: isMobile ? 320 : "auto",
      minHeight: isMobile ? 320 : 200,
      position: "relative", background: "#EEF2F1",
      overflow: "hidden", borderBottom: "1px solid var(--border-1)",
    }}>
      <div ref={mapEl} style={{ width: "100%", height: "100%" }}/>

      {/* Secondary-dot key overlay */}
      <div style={{
        position: "absolute", left: 12, bottom: 10, zIndex: 400,
        background: "rgba(255,255,255,0.96)", border: "1px solid var(--border-1)",
        borderRadius: 6, padding: "6px 10px", boxShadow: "var(--shadow-1)",
        display: "flex", alignItems: "center", gap: 10, fontSize: 11, color: "var(--fg-2)",
      }}>
        <span style={{ fontSize: 10.5, color: "var(--fg-3)", fontWeight: 500 }}>附加小點 · 另一類活動</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: "#3B82F6", border: "1.5px solid #fff", boxShadow: "0 0 0 1px #3B82F6" }}/>抽選
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: "#10B981", border: "1.5px solid #fff", boxShadow: "0 0 0 1px #10B981" }}/>予約
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: "#F59E0B", border: "1.5px solid #fff", boxShadow: "0 0 0 1px #F59E0B" }}/>店頭
        </span>
      </div>

      <style>{`
        .ph-pin-wrap, .ph-cluster-wrap { background: none; border: none; }
        .ph-pin { position: relative; width: 22px; height: 28px; }
        .ph-pin svg { position: absolute; left: 0; top: 0; }
        .ph-pulse {
          position: absolute; left: 1px; top: -6px; width: 20px; height: 20px;
          border-radius: 999px; animation: ph-pulse 1.6s ease-in-out infinite;
        }
        @keyframes ph-pulse {
          0%,100% { transform: scale(1); opacity: 0.6; }
          50%     { transform: scale(1.8); opacity: 0; }
        }
        .ph-badge {
          position: absolute; right: -8px; top: -8px;
          min-width: 16px; height: 16px; padding: 0 4px;
          background: #1C1917; color: #fff; border-radius: 999px;
          font: 600 10px var(--font-latin);
          display: inline-flex; align-items: center; justify-content: center;
          line-height: 1;
        }
        .ph-sec {
          position: absolute; right: -2px; top: 4px;
          width: 8px; height: 8px; border-radius: 999px;
          border: 1.5px solid #fff; box-sizing: content-box;
        }
        .ph-cluster {
          width: 36px; height: 36px; border-radius: 999px;
          background: #1C1917; color: #fff;
          border: 2px solid #fff;
          box-shadow: 0 3px 6px rgba(0,0,0,0.25);
          display: flex; align-items: center; justify-content: center;
          font: 600 13px var(--font-latin);
        }
        .leaflet-popup-content { margin: 8px 10px; font: var(--ts-body); }
        .leaflet-popup-content-wrapper { border-radius: 8px; }
        .ph-tooltip {
          background: #1C1917; color: #fff; border: none; border-radius: 5px;
          padding: 4px 8px; font: 600 11px var(--font-jp);
          box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }
      `}</style>
    </div>
  );
};

window.MapHero = MapHero;
