/* ============================================================
   Paella — real interactive map (Leaflet + CARTO/OSM tiles)
   Real Moscow tiles · restaurant markers · click → mini card.
   ============================================================ */

function MapView({ ctx }) {
  const P = window.PAELLA;
  const elRef = useRef(null);
  const mapRef = useRef(null);
  const [sel, setSel] = useState(null);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    if (!window.L || !elRef.current) { setReady(false); return; }
    const dark = document.documentElement.getAttribute("data-theme") === "dark";
    const map = L.map(elRef.current, {
      zoomControl: true, scrollWheelZoom: false, attributionControl: true,
    });
    mapRef.current = map;
    map.attributionControl.setPrefix("");

    const tiles = 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";
    L.tileLayer(tiles, { maxZoom: 19, subdomains: "abcd", attribution: "© OpenStreetMap, © CARTO" }).addTo(map);

    const pts = [];
    P.restaurants.forEach((r) => {
      const b = P.byId(r.bestDishId);
      const icon = L.divIcon({
        className: "lpin-wrap",
        html: `<div class="lpin"><span class="e">${b ? b.emoji : "🍽️"}</span><span class="s">★ ${r.rating.toFixed(1)}</span></div>`,
        iconSize: [60, 28], iconAnchor: [30, 32],
      });
      const m = L.marker([r.latitude, r.longitude], { icon, riseOnHover: true }).addTo(map);
      m.on("click", () => setSel(r.id));
      pts.push([r.latitude, r.longitude]);
    });
    if (pts.length) map.fitBounds(pts, { padding: [44, 44] });
    setTimeout(() => { map.invalidateSize(); }, 60);
    setReady(true);

    return () => { map.remove(); mapRef.current = null; };
  }, []);

  const selRest = sel ? P.restById(sel) : null;
  const selBest = selRest ? P.byId(selRest.bestDishId) : null;

  return (
    <div className="map-wrap">
      <div ref={elRef} className="map-leaflet"></div>

      <div className="map-legend">
        <div className="li"><span className="lpin mini"><span className="s">★</span></span>наведите и нажмите на метку</div>
      </div>

      {!window.L && (
        <div className="map-fallback">
          <Icon name="pin" size={28} />
          <div style={{ fontWeight: 800, marginTop: 8 }}>Карта недоступна офлайн</div>
          <div className="muted" style={{ fontSize: 13 }}>Подключите интернет, чтобы загрузить карту Москвы.</div>
        </div>
      )}

      {selRest && (
        <div className="map-card">
          <button className="map-card-close" onClick={() => setSel(null)}><Icon name="x" size={16} /></button>
          <div className="map-card-top">
            <div className="map-card-img"><SmartImage src={selRest.imageUrl} emoji="🍽️" grad={["oklch(0.6 0.1 130)","oklch(0.45 0.09 120)"]} /></div>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontSize: 16.5, fontWeight: 800, letterSpacing: "-0.02em" }}>{selRest.name}</div>
              <div className="dcard-meta" style={{ fontSize: 12.5, marginTop: 3 }}>
                <span>{selRest.cuisine}</span><span className="dot"></span><span>{selRest.district}</span>
              </div>
              <div className="row" style={{ gap: 8, marginTop: 7 }}>
                <span className="score" style={{ fontSize: 12.5, padding: "3px 8px" }}><Icon name="star" size={11} fill="var(--gold)" sw={0} />{selRest.rating.toFixed(1)}</span>
                {selRest.averageCheck ? <span className="muted" style={{ fontSize: 12.5, fontWeight: 600 }}>≈ {selRest.averageCheck} ₽</span> : <span className="muted" style={{ fontSize: 12.5, fontWeight: 600 }}>{selRest.reviewCount.toLocaleString("ru-RU")} отзывов</span>}
              </div>
            </div>
          </div>
          {selBest && (
            <div className="rcard-best" style={{ margin: "0 14px" }}>
              <div style={{ position: "relative", width: 40, height: 40, borderRadius: 9, overflow: "hidden", flex: "none", background: "var(--bg-2)" }}>
                <DishPhoto src={selBest.photo} alt={selBest.name} />
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 10.5, fontWeight: 700, color: "var(--coral-ink)" }}>ХИТ ЗАВЕДЕНИЯ</div>
                <div style={{ fontSize: 13, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{selBest.name}</div>
              </div>
              <span style={{ marginLeft: "auto", flex: "none" }}>
                <ScoreTag u={uOf(selBest)} />
              </span>
            </div>
          )}
          <div style={{ padding: 14 }}>
            <button className="btn btn-pri btn-block btn-sm" onClick={() => ctx.openRest(selRest)}>
              Смотреть блюда <Icon name="arrowRight" size={16} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MapView });
