'use client';

import { useEffect } from 'react';
import { useSnackbar } from 'notistack';

import type { ToastSeverity } from './dispatchToast';

interface ToastEventDetail {
  message: string;
  severity: ToastSeverity;
}

/**
 * Zero-UI component that bridges window 'app:toast' events to notistack.
 * Must be rendered inside <SnackbarProvider>.
 * This lets non-React code (e.g. clientFetch) fire toasts via dispatchToast().
 */
export function ToastBridge() {
  const { enqueueSnackbar } = useSnackbar();

  useEffect(() => {
    function handler(event: Event) {
      const { message, severity } = (event as CustomEvent<ToastEventDetail>).detail;
      enqueueSnackbar(message, { variant: severity });
    }
    window.addEventListener('app:toast', handler);
    return () => window.removeEventListener('app:toast', handler);
  }, [enqueueSnackbar]);

  return null;
}
