import { useState, createElement, Fragment } from "react";
import { Component, useField, SugaredField } from "@contember/binding";
import { FieldContainer } from "@contember/ui";
import * as Leaflet from "leaflet";
import { Map, TileLayer, Marker } from "react-leaflet";
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 = (e) => {
    const latLng = e.latlng;
    if (latLng === void 0) {
      return;
    }
    latitude.updateValue(latLng.lat);
    longitude.updateValue(latLng.lng);
  };
  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];
  });
  return /* @__PURE__ */ createElement(FieldContainer, {
    ...fieldContainerProps
  }, /* @__PURE__ */ createElement("div", {
    className: "locationField-map-container"
  }, /* @__PURE__ */ createElement(Map, {
    center: resolvedCenter,
    zoom,
    className: "locationField-map-canvas",
    ...mapProps ?? {},
    onclick: moveMarker
  }, /* @__PURE__ */ createElement(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__ */ createElement(Marker, {
    icon: markerIcon,
    ...markerProps ?? {},
    position: [latitude.value, longitude.value],
    onmove: moveMarker,
    draggable: true
  }))));
}, (props) => /* @__PURE__ */ createElement(Fragment, null, /* @__PURE__ */ createElement(SugaredField, {
  field: props.latitudeField
}), /* @__PURE__ */ createElement(SugaredField, {
  field: props.longitudeField
})), "LocationField");
export { LocationField };
//# sourceMappingURL=LocationField.js.map
