import maplibregl from "maplibre-gl";
// Vite resolves this to a hashed, same-origin asset URL at build time, so the
// RTL plugin ships with the app (web, desktop, and the Jupyter embed) instead of
// being fetched from a CDN — keeps every build's CSP simple and works offline.
// The file is a copy of @mapbox/mapbox-gl-rtl-text's self-contained `dist`
// bundle (its ICU/wasm payload is base64-embedded, so there is no sibling .wasm),
// generated by the copy-rtl-text Vite plugin because the package's `exports` map
// hides the dist file. See apps/geolibre-desktop/vite-plugins/copy-rtl-text.ts.
import rtlTextPluginUrl from "./vendor/mapbox-gl-rtl-text.generated.js?url";

// Without this plugin, MapLibre lays right-to-left scripts (Arabic, Hebrew,
// Persian, Urdu, …) out left-to-right, so basemap labels render with their
// characters reversed/"flipped". Registering the RTL text plugin once per page
// fixes the shaping for every map the app creates.
// See https://github.com/hyperknot/openfreemap/issues/118.

if (typeof maplibregl.setRTLTextPlugin === "function") {
  const status = maplibregl.getRTLTextPluginStatus?.();
  // setRTLTextPlugin rejects if a plugin was already registered for the page;
  // only register when none is set yet ("unavailable" is the initial state).
  if (!status || status === "unavailable") {
    // Lazy (second arg `true`): defer downloading the plugin worker until a map
    // actually encounters RTL text, so the bytes are not paid for on LTR-only
    // maps. Returns a promise that resolves once the plugin is requested.
    maplibregl.setRTLTextPlugin(rtlTextPluginUrl, true).catch((error: unknown) => {
      console.error("[GeoLibre] Failed to load RTL text plugin", error);
    });
  }
}
