import { toast as sonnerToast } from 'sonner'
import { Toaster } from '@/components/ui/sonner'

export interface ToastAction {
  label: string
  onClick: () => void
}

/** Shim that preserves the legacy `(title, message?, action?)` call
 *  shape used throughout the codebase while delegating to sonner for
 *  actual rendering. Call sites don't need to change. Actions auto-
 *  extend the toast duration to 8s so users have time to hit Undo. */
const build = (message?: string, action?: ToastAction, duration = 5000) => ({
  description: message,
  action: action && { label: action.label, onClick: action.onClick },
  duration: action ? Math.max(duration, 8000) : duration,
})

export const toast = {
  success: (title: string, message?: string, action?: ToastAction) =>
    sonnerToast.success(title, build(message, action)),
  error: (title: string, message?: string, action?: ToastAction) =>
    sonnerToast.error(title, build(message, action)),
  info: (title: string, message?: string, action?: ToastAction) =>
    sonnerToast.info(title, build(message, action)),
  warning: (title: string, message?: string, action?: ToastAction) =>
    sonnerToast.warning(title, build(message, action)),
}

/** Mounted once near the App root. Delegates to sonner's `<Toaster />`
 *  with palette-matched class overrides (see `@/components/ui/sonner`). */
export function ToastContainer() {
  return <Toaster />
}
