import { useEffect } from 'react';
import { router } from '@inertiajs/react';
import { notify } from '@rutatiina/ui/lib/notify';
import type { FlashToast } from '@rutatiina/ui/types/ui';

/**
 * Shows toasts flashed from controllers with `Inertia::flash('toast', [...])`.
 */
export function useFlashToast(): void {
  useEffect(() => {
    return router.on('flash', (event) => {
      const flash = (event as CustomEvent).detail?.flash;
      const data = flash?.toast as FlashToast | undefined;

      if (!data) {
        return;
      }

      notify[data.type](data.message);
    });
  }, []);
}
