<script lang="ts">
    import { onDestroy, onMount } from "svelte";
    import "leaflet/dist/leaflet.css";
    import { twMerge } from "tailwind-merge";
    import L from "leaflet";

    interface MarkerPoint {
        latitude: number;
        longitude: number;
        tooltip?: string;
    }

    export let coordinates: MarkerPoint[];

    let mapElement: HTMLDivElement;
    let map: L.Map | null = null;
    let markers: L.Marker<any>[] = [];
    var icon: L.Icon;

    onMount(async () => {
        icon = L.icon({
            iconUrl: "/map_marker.png",

            iconSize: [32, 32],
            iconAnchor: [16, 32],
            popupAnchor: [-3, -76],
        });

        map = L.map(mapElement);

        if (coordinates.length >= 1) {
            map.setView(
                [coordinates[0].latitude, coordinates[0].longitude],
                15,
            );
        }

        L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
            maxZoom: 18,
            attribution:
                '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            id: "base",
        }).addTo(map);

        updateMarkers();
    });

    onDestroy(async () => {
        map?.remove();
    });

    function addMarker(point: MarkerPoint) {
        let marker = L.marker([point.latitude, point.longitude], {
            icon: icon,
        });

        if (point.tooltip)
            marker.bindTooltip(point.tooltip, {
                direction: "bottom",
            });

        markers.push(marker);
        map?.addLayer(marker);
    }

    function updateMarkers() {
        if (L && map) {
            markers.forEach((point) => map?.removeLayer(point));
            markers = [];

            coordinates.forEach(addMarker);

            map?.flyToBounds(L.featureGroup(markers).getBounds(), {
                duration: 1,
            });
        }
    }

    $: coordinates && updateMarkers();
</script>

<div
    bind:this={mapElement}
    class={twMerge("z-0 h-full w-full", $$restProps["class"])}
></div>
