{{ define "rmo/component/map.html" }}
	<script src="https://api.mapbox.com/mapbox-gl-js/v3.17.0-beta.1/mapbox-gl.js"></script>
	<link
		href="https://api.mapbox.com/mapbox-gl-js/v3.17.0-beta.1/mapbox-gl.css"
		rel="stylesheet"
	/>
<script>
const geojson = JSON.parse({{.GeoJSON}})
function addMarkers(map, markers) {
	for (let i = 0; i < markers.length; i++) {
		let marker = markers[i];
		marker.addTo(map);
	}
}
function mapMarkers() {
	const markers = [
	{{ range .Markers }}
		new mapboxgl.Marker().setLngLat([{{.LatLng.Lng}}, {{.LatLng.Lat}}])
	{{end}}
	];
	return markers;
}

function onLoad() {
	console.log("Setting up the map...", geojson);
	mapboxgl.accessToken = {{ .MapboxToken }};
	const map = new mapboxgl.Map({
		container: "map",
		center: [{{.Center.Lng}}, {{.Center.Lat}}],
		style: 'mapbox://styles/mapbox/streets-v12', // style URL
		zoom: {{.Zoom}},
	});
	map.on("load", function() {
		console.log("Map post-load...");
		addMarkers(map, mapMarkers());
		const sourceId = 'h3-hexes';
		const layerId = 'h3-hexes-layer';
		let source = map.getSource(sourceId);

		if (!source) {
			map.addSource(sourceId, {
				type: 'geojson',
				data: geojson
			});
			map.addLayer({
				id: layerId,
				source: sourceId,
				type: 'fill',
				interactive: false,
				paint: {
					'fill-color': '#F00000',
					'fill-opacity': 0.3
				}
			});
			source = map.getSource(sourceId);
		}
		source.setData(geojson);

		console.log("Map post-load done.");
	});
	console.log("Map init done.");
}
window.addEventListener("load", onLoad);
</script>
	<style>
		.map-container {
			background-color: #e9ecef;
			border-radius: 10px;
			box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
			height: 500px;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 20px;
		}
		#map {
			height: 500px;
			width: 100%;
			margin-bottom: 10px;
		}
		#map img {
			max-width: none;
			min-width: 0px;
			height: auto;
		}
	</style>
{{ end }}
