<script lang="ts">
  import type { ServiceState, ToastType } from "$lib/ToastService/types";
  import { setContext } from "svelte";
  import Toast from "./Toast.svelte";

  const { children } = $props();

  let serviceState: ServiceState = $state({ toasts: {}, nextId: 0 });

  function addToast(toast: ToastType) {
    serviceState.toasts[serviceState.nextId++] = toast;
  }

  setContext('toastservice', addToast);

  function destroyToast(id: string) {
    delete serviceState.toasts[id];
  }

</script>

{@render children()}
<div class="toast toast-top toast-center z-80">
  {#each Object.entries(serviceState.toasts) as [i, toast] (i)}
    <Toast {toast} destroyer={() => destroyToast(i)}/>
  {/each}
</div>