/**
 * Toast bridge — allows optimistic mutation callbacks to enqueue toasts
 * without being inside a React render context.
 *
 * The app shell's `<ToastProvider>` calls `mountToastBridge(toast)` once on
 * mount, wiring the Radix/useToast queue into this module-level store.
 * Mutation callbacks call `notify.error(msg)` / `notify.success(msg)` which
 * route through the wired function (or silently no-op before mount).
 *
 * This is the minimal imperative bridge required for TanStack Query mutation
 * callbacks, which run outside React component render.
 */

import { announce } from '@/lib/a11y/announce';
import type { ToastParams } from '@/components/ui/overlays/Toast/useToast';

type ToastFn = (params: ToastParams) => string;

let _toast: ToastFn | null = null;

/**
 * Wire the toast queue. Called once by the app shell on mount.
 * Must be called inside a component that owns the `useToast` return value.
 */
export function mountToastBridge(fn: ToastFn): void {
  _toast = fn;
}

function enqueue(params: ToastParams): void {
  announce({
    message: [params.title, params.description].filter(Boolean).join('. '),
    dedupeKey: params.id ?? params.title,
    source: 'toast',
  });

  if (_toast) {
    _toast(params);
  } else if (import.meta.env.DEV) {
    console.warn('[toast-bridge] toast not mounted yet — message dropped:', params.title);
  }
}

/** Imperative toast helpers for use outside React render (mutation callbacks, etc.) */
export const notify = {
  success(title: string, description?: string): void {
    enqueue({ title, description, tone: 'success' });
  },
  error(title: string, description?: string): void {
    enqueue({ title, description, tone: 'danger' });
  },
  info(title: string, description?: string): void {
    enqueue({ title, description, tone: 'info' });
  },
  warning(title: string, description?: string): void {
    enqueue({ title, description, tone: 'warning' });
  },
};
