
function init(): void {
  let overlays: OverlayState = OverlayState.load() ?? new OverlayState(); 
  const map = L.map('map').setView([35.6653, -105.9507], 13);

  const streetLayer = TileLayerWrapper.constructLayer(
    "streetLayer",
    L.tileLayer(
      'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      {
        maxZoom: 19,
        attribution: '© OpenStreetMap'
      }));
      
  const satelliteLayer = TileLayerWrapper.constructLayer(
    "satelliteLayer",
    L.tileLayer(
      'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
      {
        maxZoom: 19,
        attribution: "&copy; Esri"
      }));
      
  TileLayerWrapper.enableOnly(streetLayer, map);
  
  overlays.markers.forEach(m=>m.add(map));
  overlays.circles.forEach(m=>m.add(map));
  overlays.polygons.forEach(m=>m.add(map));
  
  const modal = new Modal();
  
  const addMarkerHandler = (e: any) => {
    modal.setVisible(true);
    modal.setState(OverlayType.POINT, {
      latlng: e.latlng,
      map: map,
      overlays: overlays,
    });    
    map.off("click", addMarkerHandler);
  }
  
  const addMarkerBtn = document.getElementById("addPoint-btn");
  if (addMarkerBtn) {
    addMarkerBtn.onclick = (e: any)=>{
      try{
        map.off("click", addMarkerHandler);
      } finally {
        map.on("click", addMarkerHandler);
      }
    };
  }  
  
  const saveBtn = document.getElementById("save-btn");
  if (saveBtn) {
    saveBtn.onclick = (e: any) => {
      OverlayState.save(overlays);
    };
  }
  
  const clearBtn = document.getElementById("clear-btn");
  if (clearBtn) {
    clearBtn.onclick = (e: any) => {
      overlays = OverlayState.clear(overlays, map);
    }
  }
  
  const tilesBtn = document.getElementById("tiles-btn");
  if (tilesBtn) {
    tilesBtn.onclick = (e: any) => {
      if (TileLayerWrapper.getActiveLayer() == satelliteLayer) {
        TileLayerWrapper.enableOnly(streetLayer, map);
      } else {
        TileLayerWrapper.enableOnly(satelliteLayer, map);
      }
    };
  }
}

init();
