<script setup>
import { watch, onMounted, onUnmounted } from 'vue';
import { usePage } from '@inertiajs/vue3';
import { Toaster } from '@/Components/ui/sonner';
import { toast } from 'vue-sonner';

const page = usePage();

// Watch for flash messages from Inertia
watch(
  () => page.props.flash,
  (flash) => {
    if (!flash) return;

    const flashTypes = ['success', 'error', 'warning', 'info'];
    for (const type of flashTypes) {
      if (flash[type]) {
        switch (type) {
          case 'success':
            toast.success(flash[type]);
            break;
          case 'error':
            toast.error(flash[type]);
            break;
          case 'warning':
            toast.warning(flash[type]);
            break;
          case 'info':
            toast.info(flash[type]);
            break;
        }
      }
    }
  },
  { deep: true, immediate: true }
);

// Expose toast methods globally for backward compatibility
onMounted(() => {
  window.$toast = {
    success: (message, options = {}) => {
      toast.success(message, options);
    },
    error: (message, options = {}) => {
      toast.error(message, options);
    },
    warning: (message, options = {}) => {
      toast.warning(message, options);
    },
    info: (message, options = {}) => {
      toast.info(message, options);
    },
    remove: (id) => {
      if (id) {
        toast.dismiss(id);
      }
    },
  };
});

onUnmounted(() => {
  if (window.$toast) {
    delete window.$toast;
  }
});
</script>

<template>
  <Toaster class="pointer-events-auto" position="bottom-right" />
</template>
