export interface TileLayerConfig {
  key: string;
  label: string;
  url: string;
  attribution: string;
  maxZoom?: number;
}

export const TILE_LAYERS: TileLayerConfig[] = [
  {
    key: 'normal',
    label: 'Normal',
    url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    maxZoom: 19,
  },
  {
    key: 'dark',
    label: 'Dark',
    url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/">CARTO</a>',
    maxZoom: 20,
  },
  {
    key: 'satellite',
    label: 'Satellite',
    url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
    attribution: '&copy; Esri, Maxar, Earthstar Geographics',
    maxZoom: 18,
  },
];

const STORAGE_KEY = 'cmlite:tilePref';

export function getPersistedTileLayer(): string {
  try {
    return localStorage.getItem(STORAGE_KEY) || 'dark';
  } catch {
    return 'dark';
  }
}

export function persistTileLayer(key: string): void {
  try {
    localStorage.setItem(STORAGE_KEY, key);
  } catch {
    // localStorage not available
  }
}

export function getTileConfig(key: string): TileLayerConfig {
  return TILE_LAYERS.find((t) => t.key === key) || TILE_LAYERS[1]!; // default dark
}
