<!--
Usage:
   gpx-map lat="47.123" lon="8.456" gpx="/uploads/gpx/my-track.gpx" zoom="12" height="600px" 
  All parameters are optional except lat/lon and gpx.
-->
<div id="gpx-map-{{ .Get "lat" }}-{{ .Get "lon" }}-{{ .Get "zoom" | default "13" }}" style="height:{{ .Get "height" | default "500px" }};"></div>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-gpx/1.7.0/gpx.min.js"></script>
<script>
(function () {
    var mapId = "gpx-map-{{ .Get "lat" }}-{{ .Get "lon" }}-{{ .Get "zoom" | default "13" }}";
    if (!window._gpx_maps) window._gpx_maps = {};
    if (!window._gpx_maps[mapId]) {
        var map = L.map(mapId).setView(
            [{{ .Get "lat" }}, {{ .Get "lon" }}],
            {{ .Get "zoom" | default "13" }}
        );
        
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);
        
        // Add a marker at the specified location
        L.marker([{{ .Get "lat" }}, {{ .Get "lon" }}]).addTo(map);
        
        // Load and display the GPX track
        var gpxUrl = "{{ .Get "gpx" }}";
        new L.GPX(gpxUrl, {
            async: true,
            marker_options: {
                startIconUrl: '/images/pin-icon-start.png',
                endIconUrl: '/images/pin-icon-end.png',
                shadowUrl: '/images/pin-shadow.png'
            },
            polyline_options: {
                color: '#3388ff',
                weight: 5,
                opacity: 0.8
            }
        }).on('loaded', function(e) {
            // Auto-fit the map to the track bounds if no specific lat/lon provided
            if (!("{{ .Get "lat" }}" && "{{ .Get "lon" }}")) {
                map.fitBounds(e.target.getBounds());
            }
        }).addTo(map);
        
        window._gpx_maps[mapId] = map;
    }
})();
</script>