// Module-level tile image cache — shared across all map instances and renders.
// Uses CartoDB dark basemap tiles (CC BY 3.0, no API key required for low traffic).
const SUBDOMAINS = "abcd";
const MAX_CACHE_SIZE = 512;

type CacheEntry = HTMLImageElement | null; // null = loading
const imageCache = new Map<string, CacheEntry>();

function tileUrl(z: number, x: number, y: number): string {
  const s = SUBDOMAINS[(x + y) % SUBDOMAINS.length];
  return `https://${s}.basemaps.cartocdn.com/dark_nolabels/${z}/${x}/${y}.png`;
}

export function getTile(
  z: number,
  x: number,
  y: number,
  onLoad: () => void
): HTMLImageElement | undefined {
  const key = `${z}/${x}/${y}`;
  const cached = imageCache.get(key);

  if (cached instanceof HTMLImageElement) return cached;
  if (cached === null) return undefined; // already loading

  if (imageCache.size >= MAX_CACHE_SIZE) {
    const firstKey = imageCache.keys().next().value;
    if (firstKey !== undefined) imageCache.delete(firstKey);
  }

  imageCache.set(key, null);

  const img = new Image();
  img.crossOrigin = "anonymous";
  img.onload = () => {
    imageCache.set(key, img);
    onLoad();
  };
  img.onerror = () => {
    imageCache.delete(key); // allow retry on next render
  };
  img.src = tileUrl(z, x, y);

  return undefined;
}
