{{ define "organized_carpool_map" }}
<div id="map" class="w-full h-full min-h-96"></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": [
      {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [{{ .booking.PassengerPickupLng }}, {{ .booking.PassengerPickupLat }}]
        },
        "properties": {
          "label": "{{ .booking.PassengerPickupAddress }}",
          "type": "pickup"
        }
      },
      {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [{{ .booking.PassengerDropLng }}, {{ .booking.PassengerDropLat }}]
        },
        "properties": {
          "label": "{{ .booking.PassengerDropAddress }}",
          "type": "drop"
        }
      }
    ]
  }

  map.on('load', async () => {
    // Add route polyline if available
    // Add driver route if available
    {{if .booking.DriverRoute}}
    console.log("DriverRoute found");
    try {
      const driverRoute = JSON.parse(`{{ .booking.DriverRoute.Serialized }}`);
      console.log("Parsed driverRoute:", driverRoute);
      console.log("DriverRoute type:", driverRoute.type);
      console.log("DriverRoute features:", driverRoute.features);
      console.log("DriverRoute features count:", driverRoute.features ? driverRoute.features.length : 0);
      console.log("DriverRoute keys:", Object.keys(driverRoute));
      if (driverRoute.features && driverRoute.features.length > 0) {
        console.log("First feature:", driverRoute.features[0]);
        console.log("LineString features:", driverRoute.features.filter(f => f.geometry && f.geometry.type === 'LineString'));
      } else {
        console.log("No features found, checking alternative structure");
        console.log("All driverRoute properties:", driverRoute);
      }

      map.addSource('driver_route', {
        type: "geojson",
        data: driverRoute
      });

      map.addLayer({
        'id': 'driver_route',
        'type': 'line',
        'source': 'driver_route',
        'filter': ['==', ['geometry-type'], 'LineString'], // Only show LineString geometries
        'layout': {
          'line-join': 'round',
          'line-cap': 'round',
        },
        'paint': {
          'line-color': '#243887', // Blue - main application color
          'line-width': 3
        },
      });
      console.log("Driver route layer added successfully");
    } catch (error) {
      console.error("Error adding driver route:", error);
    }
    {{else}}
    console.log("No DriverRoute available");
    {{end}}

    // Add passenger route if available
    {{if .booking.PassengerRoute}}
    console.log("PassengerRoute found");
    try {
      const passengerRoute = JSON.parse(`{{ .booking.PassengerRoute.Serialized }}`);
      console.log("Parsed passengerRoute:", passengerRoute);
      console.log("PassengerRoute type:", passengerRoute.type);
      console.log("PassengerRoute features count:", passengerRoute.features ? passengerRoute.features.length : 0);

      map.addSource('passenger_route', {
        type: "geojson",
        data: passengerRoute
      });

      map.addLayer({
        'id': 'passenger_route',
        'type': 'line',
        'source': 'passenger_route',
        'filter': ['==', ['geometry-type'], 'LineString'], // Only show LineString geometries
        'layout': {
          'line-join': 'round',
          'line-cap': 'round',
        },
        'paint': {
          'line-color': '#243887', // Blue - main application color
          'line-width': 3
        },
      });
      console.log("Passenger route layer added successfully");
    } catch (error) {
      console.error("Error adding passenger route:", error);
    }
    {{else}}
    console.log("No PassengerRoute available");
    {{end}}

    map.addSource('carpool_points', {
      type: "geojson",
      data: geojsonPoints
    })

    // Add pickup point
    map.addLayer({
      'id': 'pickup_point',
      'type': 'circle',
      'source': 'carpool_points',
      'filter': ['==', ['get', 'type'], 'pickup'],
      'paint': {
        'circle-color': '#243887', // Blue - main application color
        'circle-radius': 8,
        'circle-stroke-color': '#fff',
        'circle-stroke-width': 2
      },
    });

    // Add drop point
    map.addLayer({
      'id': 'drop_point',
      'type': 'circle',
      'source': 'carpool_points',
      'filter': ['==', ['get', 'type'], 'drop'],
      'paint': {
        'circle-color': '#243887', // Blue - main application color
        'circle-radius': 8,
        'circle-stroke-color': '#fff',
        'circle-stroke-width': 2
      },
    });

    // Add popup on click
    map.on('click', 'pickup_point', (e) => {
      new maplibregl.Popup()
        .setLngLat(e.lngLat)
        .setHTML(`<strong>Point de départ</strong><br>${e.features[0].properties.label}`)
        .addTo(map);
    });

    map.on('click', 'drop_point', (e) => {
      new maplibregl.Popup()
        .setLngLat(e.lngLat)
        .setHTML(`<strong>Destination</strong><br>${e.features[0].properties.label}`)
        .addTo(map);
    });

    // Change cursor on hover
    map.on('mouseenter', 'pickup_point', () => map.getCanvas().style.cursor = 'pointer');
    map.on('mouseleave', 'pickup_point', () => map.getCanvas().style.cursor = '');
    map.on('mouseenter', 'drop_point', () => map.getCanvas().style.cursor = 'pointer');
    map.on('mouseleave', 'drop_point', () => map.getCanvas().style.cursor = '');

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