<!--
  @component

  Creates a maplibre-gl map that will fill its parent.

  Children will mount once the map is fully loaded.

  ```svelte
    <MapLibre mapProvider="open-street">
      <MapLibreMarker lngLat={{ lng: 0, lat: 0 }} />
    </MapLibre>
  ```

  ```svelte
    <MapLibre mapProvider="google-maps" mapProviderKey="mycoolkey">
      <MapLibreMarker lngLat={{ lng: 0, lat: 0 }} />
    </MapLibre>
  ```
-->

<script>import "maplibre-gl/dist/maplibre-gl.css";
import { onMount, tick } from "svelte";
import { provideMapContext } from "./hooks";
import { Map } from "maplibre-gl";
import { getStyleSpecification } from "./style";
import { LngLat } from "..";
import { MapProviders } from "./types";
import { DEFAULT_MAX_ZOOM } from "./zoom";
export let minPitch = 0;
export let maxPitch = 60;
export let zoom = 9;
export let minZoom = 0;
export let maxZoom = DEFAULT_MAX_ZOOM;
export let center = new LngLat(-73.984421, 40.7718116);
export let map = void 0;
export let options = void 0;
export let mapProvider = MapProviders.openStreet;
export let mapProviderKey = void 0;
export let onCreate = void 0;
export let onMove = void 0;
export let onResize = void 0;
const context = provideMapContext(center, zoom);
let container;
let created = false;
const setMapSize = () => {
  const canvas = map?.getCanvas();
  context.size.set({
    width: canvas?.clientWidth ?? 0,
    height: canvas?.clientHeight ?? 0
  });
};
const handleCreate = () => {
  if (map === void 0) {
    return;
  }
  created = true;
  onCreate?.(map);
  void tick().then(() => map?.resize());
};
const handleMove = () => {
  if (map === void 0) {
    return;
  }
  context.center.set(map.getCenter());
  context.zoom.set(map.getZoom());
  onMove?.(map);
};
const handleResize = () => {
  if (map === void 0) {
    return;
  }
  setMapSize();
  context.center.set(map.getCenter());
  context.zoom.set(map.getZoom());
  onResize?.(map);
};
onMount(() => {
  map = new Map({
    antialias: true,
    container,
    style: getStyleSpecification(mapProvider, mapProviderKey, maxZoom),
    center,
    zoom,
    minPitch,
    maxPitch,
    minZoom,
    maxZoom,
    ...options
  });
  context.map.set(map);
  map.on("move", handleMove);
  map.on("resize", handleResize);
  map.on("style.load", handleCreate);
  return () => {
    map?.off("move", handleMove);
    map?.off("resize", handleResize);
    map?.off("style.load", handleCreate);
  };
});
$:
  map?.setMinPitch(minPitch);
$:
  map?.setMaxPitch(maxPitch);
$:
  map?.setZoom(zoom);
$:
  map?.setCenter(center);
$:
  map?.setStyle(getStyleSpecification(mapProvider, mapProviderKey));
</script>

{#if created}
  <slot />
{/if}

<div
  class="h-full {$$restProps.class ?? ''}"
  {...$$restProps}
>
  <div
    class="h-full"
    bind:this={container}
  />

  {#if created}
    <slot name="layer" />
  {/if}
</div>
