<!DOCTYPE html>
    <html>
    <head>
        <meta charset='utf-8' />
        <title>Rio Viz</title>
        <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
        <script src='https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.js'></script>
        <link href='https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.css' rel='stylesheet' />

        <style>
            body { margin:0; padding:0; width:100%; height:100%;}
            #map { position:absolute; top:0; bottom:0; width:100%; }

            .zoom-info {
                z-index: 10;
                position: absolute;
                bottom: 17px;
                right: 0;
                padding: 5px;
                width: auto;
                height: auto;
                font-size: 12px;
                color: #000;
            }

            @media(max-width: 767px) {
              .maplibregl-ctrl-attrib {
                  font-size: 10px;
              }
            }
        </style>
    </head>
    <body>

    <div id='map'>
      <div class="zoom-info"><span id="zoom"></span></div>
    </div>

    <script>

var map = new maplibregl.Map({
  container: 'map',
  style: {
    version: 8,
    sources: {
      'basemap': {
        type: 'raster',
        tiles: [
          'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
        ],
        tileSize: 256,
        attribution: '<a href="http://www.openstreetmap.org/copyright">© OpenStreetMap</a>'
      }
    },
    layers: [
      {
        'id': 'basemap',
        'type': 'raster',
        'source': 'basemap',
        'minzoom': 0,
        'maxzoom': 20
      }
    ]
  },
  center: [0, 0],
  zoom: 1
})

map.on('zoom', function (e) {
  const z = (map.getZoom()).toString().slice(0, 6)
  document.getElementById('zoom').textContent = z
})


const bboxPolygon = (bounds) => {
    return {
        'type': 'Feature',
        'geometry': {
            'type': 'Polygon',
            'coordinates': [[
                [bounds[0], bounds[1]],
                [bounds[2], bounds[1]],
                [bounds[2], bounds[3]],
                [bounds[0], bounds[3]],
                [bounds[0], bounds[1]]
            ]]
        },
        'properties': {}
    }
}

const addAOI = (bounds) => {
  if (map.getLayer('aoi-polygon')) map.removeLayer('aoi-polygon')
  if (map.getSource('aoi')) map.removeSource('aoi')
  if (bounds[0] > bounds[2]) {
    map.addSource('aoi', {
      'type': 'geojson',
      'data': {
        "type": "FeatureCollection",
        "features": [
          bboxPolygon([-180, bounds[1], bounds[2], bounds[3]]),
          bboxPolygon([bounds[0], bounds[1], 180, bounds[3]]),
        ]
      }
    })
  } else {
    map.addSource('aoi', {
      'type': 'geojson',
      'data': {
        "type": "FeatureCollection",
        "features": [bboxPolygon(bounds)]
      }
    })
  }

  map.addLayer({
    id: 'aoi-polygon',
    type: 'line',
    source: 'aoi',
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': '#3bb2d0',
      'line-width': 1
    }
  })
  return
}

map.on('load', () => {
  var tilejson_endpoint = '{{ tilejson_endpoint|safe }}'
  fetch(tilejson_endpoint)
    .then(res => {
      if (res.ok) return res.json()
      throw new Error('Network response was not ok.')
    })
    .then(data => {
      console.log(data)

      addAOI(data.bounds)

      let crossing_dateline = false
      let bounds = [...data.bounds]
      // Bounds crossing dateline
      if (bounds[0] > bounds[2]) {
        crossing_dateline = true
        bounds[0] = bounds[0] - 360
      }
      map.fitBounds(
        [[bounds[0], bounds[1]], [bounds[2], bounds[3]]]
      )

      if (crossing_dateline) {
        // 2 sources and 2 layers
        // left
        map.addSource('raster-l', {
          type: 'raster',
          bounds: [-180, bounds[1], bounds[2], bounds[3]],
          minzoom: data.minzoom,
          maxzoom: data.maxzoom,
          tiles: data.tiles,
          tileSize: 256 // This might be false but it's not in TileJSON
        })
        map.addLayer({id: 'raster-l', type: 'raster', source: 'raster-l'})

        //right
        map.addSource('raster-r', {
          type: 'raster',
          bounds: [bounds[0], bounds[1], 180, bounds[3]],
          minzoom: data.minzoom,
          maxzoom: data.maxzoom,
          tiles: data.tiles,
          tileSize: 256 // This might be false but it's not in TileJSON
        })
        map.addLayer({id: 'raster-r', type: 'raster', source: 'raster-r'})

      } else {
        map.addSource('raster', {
          type: 'raster',
          bounds: bounds,
          minzoom: data.minzoom,
          maxzoom: data.maxzoom,
          tiles: data.tiles,
          tileSize: 256 // This might be false but it's not in TileJSON
        })
        map.addLayer({id: 'raster', type: 'raster', source: 'raster'})
      }
    })
    .catch(err => {
      console.warn(err)
    })
})
    </script>
    </body>
    </html>
