import leaflet from 'leaflet';
import { type Ref, useEffect } from 'preact/hooks';
import type { Coordinates } from '../../shared/types';

export const useMapClick = (
    mapRef: Readonly<Ref<leaflet.Map | undefined>>,
    onMapClick: (leaflet: Coordinates) => void,
) =>
    useEffect(() => {
        const map = mapRef.current;
        if (!map) {
            return;
        }

        const handler: leaflet.LeafletMouseEventHandlerFn = ({ latlng }) => {
            onMapClick(latlng);
        };
        map.on('click', handler);

        return () => {
            map.removeEventListener('click', handler);
        };
    }, [mapRef, onMapClick]);
