// 真实地图组件 (Leaflet)，手绘风覆盖
// 依赖：全局 L (Leaflet)

function RealMap({ regions, selectedId, onSelect, showAvoid, showRoutes, sortMode, votes, sortHighlightIds }) {
  const mapEl = useRef(null);
  const mapRef = useRef(null);
  const markersRef = useRef({});
  const routesRef = useRef([]);

  // 初始化
  useEffect(() => {
    if (!mapEl.current || mapRef.current) return;
    const m = L.map(mapEl.current, {
      zoomControl: true,
      attributionControl: false,
      scrollWheelZoom: true,
    }).setView([30.5, 120.0], 7);

    // 使用带中文地名的底图 (CartoDB Voyager 支持中文)
    L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
      subdomains: 'abcd',
      maxZoom: 18,
    }).addTo(m);

    // 上海起点
    const shanghaiIcon = L.divIcon({
      className: 'shanghai-marker',
      html: `<div style="
        width: 48px; height: 48px; border-radius: 50%;
        background: #fffbe8; border: 2.5px solid #2a2a28;
        display: flex; align-items: center; justify-content: center;
        font-family: 'Caveat', cursive; font-weight: 700; font-size: 15px;
        box-shadow: 2px 3px 0 #2a2a28;
        transform: rotate(-3deg);
      ">上海↗</div>`,
      iconSize: [48, 48], iconAnchor: [24, 24],
    });
    L.marker([31.23, 121.47], { icon: shanghaiIcon, zIndexOffset: 1000 }).addTo(m);

    mapRef.current = m;
  }, []);

  // 更新 markers
  useEffect(() => {
    const m = mapRef.current;
    if (!m) return;

    // 清除
    Object.values(markersRef.current).forEach(mk => m.removeLayer(mk));
    markersRef.current = {};
    routesRef.current.forEach(r => m.removeLayer(r));
    routesRef.current = [];

    const visible = regions.filter(r => showAvoid || r.tier !== 'avoid');

    // routes: 上海 → 每个可玩地 (示意曲线)
    if (showRoutes) {
      visible.filter(r => r.tier !== 'avoid').forEach(r => {
        const from = [31.23, 121.47];
        const to = [r.coords.lat, r.coords.lng];
        // 添加中间控制点让线有弧度
        const midLat = (from[0] + to[0]) / 2 + (Math.random() - 0.5) * 0.3;
        const midLng = (from[1] + to[1]) / 2 - 0.3;
        const latlngs = [from, [midLat, midLng], to];
        const poly = L.polyline(latlngs, {
          color: r.color || '#4a4a45',
          weight: 1.8,
          opacity: 0.55,
          dashArray: '4 5',
          smoothFactor: 2,
        }).addTo(m);
        routesRef.current.push(poly);
      });
    }

    // markers
    visible.forEach(r => {
      const isSelected = r.id === selectedId;
      const isHighlight = sortHighlightIds && sortHighlightIds.has(r.id);
      const rVotes = (votes || {})[r.id] || {};
      const avg = Object.values(rVotes).filter(n => n > 0);
      const avgVal = avg.length ? (avg.reduce((a,b)=>a+b,0) / avg.length) : 0;
      const stars = avgVal > 0 ? '★'.repeat(Math.round(avgVal)) : '';

      let bg = '#fffbe8';
      let border = '#2a2a28';
      let label = r.short;
      let labelColor = '#2a2a28';

      if (r.tier === 'avoid') {
        bg = '#f5c9c2';
        border = '#a83a3a';
        labelColor = '#6a1f1f';
      } else if (r.tier === 'top') {
        bg = '#d8ecd4';
        border = '#2e7d5b';
      } else if (r.tier === 'good') {
        bg = '#f5e5c8';
        border = '#c08835';
      }

      const scale = isSelected ? 1.15 : isHighlight ? 1.05 : 1.0;
      const opacity = r.tier === 'avoid' ? 0.7 : 1;

      const icon = L.divIcon({
        className: 'region-marker',
        html: `<div style="
          position: relative;
          opacity: ${opacity};
          transform: scale(${scale});
          transform-origin: center bottom;
          transition: transform 0.2s;
        ">
          <div style="
            padding: 4px 10px;
            background: ${bg};
            border: 1.5px solid ${border};
            border-radius: 3px;
            font-family: 'Caveat','Ma Shan Zheng',cursive;
            font-weight: 700;
            font-size: 14px;
            color: ${labelColor};
            white-space: nowrap;
            box-shadow: 1.5px 2px 0 ${border};
            transform: rotate(${(r.id.charCodeAt(0) % 5 - 2) * 0.8}deg);
            ${isSelected ? 'outline: 2px dashed #2a2a28; outline-offset: 3px;' : ''}
          ">
            ${r.tier === 'avoid' ? '⚠ ' : ''}${label}
            ${stars ? `<span style="color:#c08835; margin-left:3px; font-size:11px;">${stars}</span>` : ''}
          </div>
          <div style="
            position: absolute; left: 50%; top: 100%;
            width: 8px; height: 8px; margin-left: -4px;
            background: ${border};
            border-radius: 50%;
            box-shadow: 0 1px 2px rgba(0,0,0,0.3);
          "></div>
        </div>`,
        iconSize: [80, 30], iconAnchor: [40, 30],
      });

      const mk = L.marker([r.coords.lat, r.coords.lng], { icon, zIndexOffset: isSelected ? 500 : isHighlight ? 200 : 0 })
        .addTo(m)
        .on('click', () => onSelect(r.id));

      markersRef.current[r.id] = mk;
    });
  }, [regions, selectedId, showAvoid, showRoutes, sortMode, votes, sortHighlightIds]);

  // 选中时平移
  useEffect(() => {
    const m = mapRef.current;
    if (!m || !selectedId) return;
    const r = regions.find(x => x.id === selectedId);
    if (r) m.panTo([r.coords.lat, r.coords.lng], { animate: true });
  }, [selectedId, regions]);

  return (
    <div
      ref={mapEl}
      style={{
        width: '100%', height: '100%',
        border: '1.5px solid var(--ink)',
        borderRadius: 4,
        boxShadow: '2px 3px 0 var(--ink)',
        background: 'var(--paper)',
      }}
    />
  );
}

window.RealMap = RealMap;
