// Remembered map views — where each map was left, per map.
//
// Panning and zooming a map is an operator saying "this is the part of the world
// I work". Throwing that away on every tab switch made the maps something to
// set up again each time rather than something to glance at, and the world map
// was the only one that remembered anything.
//
// One key per map, and portable (see lib/uiPref) like the world map's own: a
// copied data folder brings the views with it.
import { writeUiPref } from '@/lib/uiPref';

export type MapView = { lat: number; lon: number; zoom: number };

// The keys in use. Named here rather than typed at each call site so a rename
// cannot silently orphan somebody's saved view.
export const MAP_VIEW_WORLD = 'opslog.mapView';
export const MAP_VIEW_FT = 'opslog.ftMapView';
export const MAP_VIEW_GRIDS = 'opslog.gridMapView';

export function loadMapView(key: string): MapView | null {
  try {
    const v = JSON.parse(localStorage.getItem(key) || 'null');
    return v && typeof v.zoom === 'number' && typeof v.lat === 'number' && typeof v.lon === 'number' ? v : null;
  } catch {
    return null; // corrupt or unreadable → open where the map would by default
  }
}

export function saveMapView(key: string, lat: number, lon: number, zoom: number): void {
  writeUiPref(key, JSON.stringify({ lat, lon, zoom }));
}
