import { Component, useField, SugaredField } from "@contember/binding";
import { FieldContainer } from "@contember/ui";
import * as Leaflet from "leaflet";
import { useCallback, useState, useEffect } from "react";
import { MapContainer, TileLayer, Marker } from "react-leaflet";
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
const markerIcon = Leaflet.divIcon({
  className: "locationField-marker",
  iconSize: [24, 24],
  iconAnchor: [12, 23]
});
const defaultZoom = 5;
const LocationField = Component(({
  latitudeField,
  longitudeField,
  mapCenter,
  zoom = defaultZoom,
  tileLayerProps,
  mapProps,
  markerProps,
  ...fieldContainerProps
}) => {
  const latitude = useField(latitudeField);
  const longitude = useField(longitudeField);
  const moveMarker = useCallback((e) => {
    const latLng = e.latlng;
    if (latLng === void 0) {
      return;
    }
    latitude.updateValue(latLng.lat);
    longitude.updateValue(latLng.lng);
  }, [latitude, longitude]);
  const [resolvedCenter] = useState(() => {
    if (mapCenter !== void 0) {
      return mapCenter;
    }
    if (latitude.value !== null && longitude.value !== null) {
      return [latitude.value, longitude.value];
    }
    return [50.102223, 9.254419];
  });
  const [map, setMap] = useState(null);
  useEffect(() => {
    map?.on("click", moveMarker);
    return () => {
      map?.off("click", moveMarker);
    };
  }, [map, moveMarker]);
  return /* @__PURE__ */ jsx(FieldContainer, {
    ...fieldContainerProps,
    children: /* @__PURE__ */ jsx("div", {
      className: "locationField-map-container",
      children: /* @__PURE__ */ jsxs(MapContainer, {
        ref: setMap,
        center: resolvedCenter,
        zoom,
        className: "locationField-map-canvas",
        ...mapProps ?? {},
        children: [/* @__PURE__ */ jsx(TileLayer, {
          url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
          attribution: '\xA9 <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
          ...tileLayerProps ?? {}
        }), latitude.value !== null && longitude.value !== null && /* @__PURE__ */ jsx(Marker, {
          icon: markerIcon,
          ...markerProps ?? {},
          position: [latitude.value, longitude.value],
          draggable: true,
          eventHandlers: {
            move: moveMarker
          }
        })]
      })
    })
  });
}, (props) => /* @__PURE__ */ jsxs(Fragment, {
  children: [/* @__PURE__ */ jsx(SugaredField, {
    field: props.latitudeField
  }), /* @__PURE__ */ jsx(SugaredField, {
    field: props.longitudeField
  })]
}), "LocationField");
export {
  LocationField
};
//# sourceMappingURL=LocationField.js.map
