<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="display: none">
    <div v-bind="$attrs" ref="message">
      <slot name="default" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { type Options as ToastOptions, toast } from "bulma-toast";
import { onMounted, useTemplateRef } from "vue";

export type HBulmaToast = {
  show(options: ToastOptions): void;
  hide(): void;
};

const emit = defineEmits<{
  (event: "handle", handle: HBulmaToast): void;
}>();

const message_div = useTemplateRef("message");

onMounted(() =>
  emit("handle", {
    show(options: ToastOptions = {}): void {
      if (message_div.value === null) return;

      toast({
        ...options,
        single: true,
        message: message_div.value,
      });
    },
    hide(): void {
      // using "toast" detaches "message" from the invisible "div"
      // => toast_div is not part of this component!
      const toast_div = message_div.value?.parentElement;
      const delete_button = toast_div?.querySelector("button.delete");
      if (!(delete_button instanceof HTMLButtonElement)) return;

      delete_button.click();
    },
  }),
);
</script>
