// Which imagery each map draws on — one choice per map.
//
// The world map and the grid-square map used to share a single key, so picking
// satellite imagery to look at grids also repainted the main map, and there was
// no way to have terrain on one and plain streets on the other. They are
// different maps answering different questions, and the imagery that suits one
// is not the imagery that suits the next.
//
// Portable (see lib/uiPref) like the remembered views in lib/mapView: a copied
// data folder brings the choices with it.
import { writeUiPref } from '@/lib/uiPref';
import type { BasemapKey } from '@/components/MainMap';

// The keys in use. Named here rather than typed at each call site so a rename
// cannot silently orphan somebody's choice.
export const MAP_BASE_WORLD = 'opslog.mapBasemap';
export const MAP_BASE_GRIDS = 'opslog.gridMapBase';
export const MAP_BASE_FT = 'opslog.ftmapBase';
export const MAP_BASE_SAT = 'opslog.satMapBase';

const VALID = ['light', 'voyager', 'street', 'satellite'];

// loadMapBase reads one map's choice.
//
// inheritFrom exists for the split: the grid map's choice lived under the world
// map's key until they were separated, so an operator who had chosen imagery
// there keeps it instead of being silently reset to the default.
export function loadMapBase(key: string, fallback: BasemapKey, inheritFrom?: string): BasemapKey {
  const read = (k: string) => {
    const v = localStorage.getItem(k);
    return v && VALID.includes(v) ? (v as BasemapKey) : null;
  };
  return read(key) ?? (inheritFrom ? read(inheritFrom) : null) ?? fallback;
}

export function saveMapBase(key: string, v: BasemapKey): void {
  writeUiPref(key, v);
}
