{{ define "journey_map" }}
<div id="map" class="w-full h-full"></div>
<script>
  let protocol = new pmtiles.Protocol();
  maplibregl.addProtocol("pmtiles",protocol.tile);
  var map = new maplibregl.Map({
    container: 'map', // container id
    style: "/public/maps/protomaps-light/style.json",
  });

  const geojsonPoints = {
    "type": "FeatureCollection",
    "features": [
      {{ json .driver_journey.DriverDeparture }},
      {{ json .driver_journey.PassengerPickup }},
      {{ json .driver_journey.PassengerDrop }},
      {{ json .driver_journey.DriverArrival }}
    ]
  }
  const driverGeojsonPoints = {
    "type": "FeatureCollection",
    "features": [
      {{ json .driver_journey.DriverDeparture }},
      {{ json .driver_journey.DriverArrival }}
    ]
  }
  const passengerGeojsonPoints = {
    "type": "FeatureCollection",
    "features": [
      {{ json .driver_journey.PassengerPickup }},
      {{ json .driver_journey.PassengerDrop }},
    ]
  }


  map.on('load', async () => {
    {{if .driver_journey.JourneyPolyline}}
    var linestring = polyline.toGeoJSON('{{.driver_journey.JourneyPolyline}}');
    map.addSource('trip', {
      type: "geojson",
      data: linestring
    })
    map.addLayer({
      'id': 'trip',
      'type': 'line',
      'source': 'trip',
      'layout': {
        'line-join': 'round',
        'line-cap': 'round',
      },
      'paint': {
        'line-color': '#243887',
        'line-width': 3
      },
    });
    {{end}}

    map.addSource('driver_points', {
      type: "geojson",
      data: driverGeojsonPoints
    })
    map.addLayer({
      'id': 'driver_points',
      'type': 'circle',
      'source': 'driver_points',
      'paint': {
        'circle-color': '#000'
      },
    });
    map.addSource('passenger_points', {
      type: "geojson",
      data: passengerGeojsonPoints
    })
    map.addLayer({
      'id': 'passenger_points',
      'type': 'circle',
      'source': 'passenger_points',
      'paint': {
        'circle-color': '#243887',
        'circle-radius': 8
      },
    });
    var bbox=turf.bbox(geojsonPoints)

    map.fitBounds(bbox, { padding: 50 })
  })
</script>
 
{{ end }}
