import { createContext, useCallback, useContext, useState, type ReactNode } from 'react'

export type ToastVariant = 'default' | 'success' | 'error'
export type ToastItem = { id: number; message: string; variant: ToastVariant }

let nextId = 1
let pushImpl: ((message: string, variant: ToastVariant) => void) | null = null

type ToastContextValue = {
  toasts: ToastItem[]
  dismiss: (id: number) => void
}

const ToastContext = createContext<ToastContextValue | null>(null)

export function ToastProvider({ children }: { children: ReactNode }) {
  const [toasts, setToasts] = useState<ToastItem[]>([])

  const push = useCallback((message: string, variant: ToastVariant) => {
    setToasts((prev) => [...prev, { id: nextId++, message, variant }])
  }, [])

  const dismiss = useCallback((id: number) => {
    setToasts((prev) => prev.filter((t) => t.id !== id))
  }, [])

  pushImpl = push

  return <ToastContext value={{ toasts, dismiss }}>{children}</ToastContext>
}

export function useToastContext() {
  const ctx = useContext(ToastContext)
  if (!ctx) throw new Error('useToastContext must be used within ToastProvider')
  return ctx
}

/** Императивный вызов из любого места (не только компонентов) — как sonner/react-hot-toast. */
export const toast = {
  success: (message: string) => pushImpl?.(message, 'success'),
  error: (message: string) => pushImpl?.(message, 'error'),
  message: (message: string) => pushImpl?.(message, 'default'),
}
