import leaflet from 'leaflet';
import { type Ref, useEffect } from 'preact/hooks';

export const useLayers = (
    mapRef: Readonly<Ref<leaflet.Map | undefined>>,
    layers: leaflet.Layer[],
) =>
    useEffect(() => {
        const map = mapRef.current;
        if (!map) {
            return;
        }

        for (const layer of layers) {
            layer.addTo(map);
        }

        return () => {
            for (const layer of layers) {
                layer.removeFrom(map);
                layer.remove();
            }
        };
    }, [mapRef, layers]);
