/* kmz-data.jsx — loads the official VELOSOFIZE route network (converted from the KMZ
   by scripts/kmz-to-geojson.py) and exposes it to the map + safety engine.

   Two same-origin GeoJSON files are fetched at startup (service-worker cached, so this
   works offline after first load):
     data/velosofize-routes.geojson  → curated cycling route LineStrings (cat 1–5 + untested)
     data/velosofize-poi.geojson     → transit / crossing / bike-parking / misc Points

   window.loadVelosofize() → Promise<{ routes:[{id,cat,name,coords}], points:[{id,cat,name,at}] }>
   Coords are normalised to Leaflet [lat, lng] order so the renderer is uniform with
   the existing community layer. The result is also cached on window.VR_KMZ. */

(function () {
  let cache = null;
  let inflight = null;

  // GeoJSON [lng,lat] → Leaflet [lat,lng]
  const ll = (c) => [c[1], c[0]];

  async function fetchFC(url) {
    const res = await fetch(url);
    if (!res.ok) throw new Error(url + ' ' + res.status);
    return res.json();
  }

  window.loadVelosofize = function () {
    if (cache) return Promise.resolve(cache);
    if (inflight) return inflight;
    inflight = Promise.all([
      fetchFC('data/velosofize-routes.geojson'),
      fetchFC('data/velosofize-poi.geojson'),
    ]).then(([rfc, pfc]) => {
      // Fold imported categories onto the existing community categories so nothing
      // overlaps and the right icon/colour is reused (parking = blue P, fountains = green):
      //   bikepark      → parking   (drops the duplicate orange "Велопаркинги (OSM)" cat)
      //   poi "Чешма"   → water     (real drinking fountains join the Чешми category)
      // "Лостове" (outdoor-gym bars) stay as the generic poi bucket.
      const remapCat = (cat, name) => {
        if (cat === 'bikepark') return 'parking';
        if (cat === 'poi' && /чешма/i.test(name || '')) return 'water';
        return cat;
      };
      const props = (p) => ({
        id: p.id, cat: remapCat(p.cat, p.name), name: p.name || '', imported: true,
        desc: p.desc || '', url: p.url || '', meta: p.meta || null,
      });
      const routes = rfc.features.map((f) => ({
        ...props(f.properties),
        coords: f.geometry.coordinates.map(ll),
      })).filter((r) => r.coords.length > 1);

      const points = pfc.features.map((f) => ({
        ...props(f.properties),
        at: ll(f.geometry.coordinates),
      }));

      cache = { routes, points };
      window.VR_KMZ = cache;
      return cache;
    }).catch((e) => {
      console.warn('[veloroute] VELOSOFIZE layer failed to load:', e);
      inflight = null;
      return { routes: [], points: [] };
    });
    return inflight;
  };
})();
