"use client";
import React, { useEffect } from "react";
import { LatLng, LeafletMouseEventHandlerFn } from "leaflet";
import { useMap } from "react-leaflet";

export type MapEventsProps = {
    onClick?: (coords: LatLng) => void;
};

export const MapEvents: React.FC<MapEventsProps> = (props) => {
    const {
        onClick
    } = props;

    const map = useMap();

    useEffect(() => {
        if(!onClick) {
            return;
        }

        const handler: LeafletMouseEventHandlerFn = (e) => {
            return onClick(e.latlng);
        };

        map.on("click", handler);

        return () => {
            map.off("click", handler);
        };
    }, [map, onClick]);

    return null;
};
