// Global toast notifications. Import useToast() anywhere and call
// toast.success('...') / toast.error('...') / toast.info('...'). A single
// <ToastHost /> mounted in AppLayout renders the stack.
import { reactive } from 'vue'

const state = reactive({
  items: [],
})

let nextId = 1

function dismiss(id) {
  const index = state.items.findIndex(t => t.id === id)
  if (index !== -1) state.items.splice(index, 1)
}

function push(message, type = 'info', duration = 5000) {
  if (!message) return
  const id = nextId++
  state.items.push({ id, message, type })
  if (duration > 0) {
    setTimeout(() => dismiss(id), duration)
  }
  return id
}

export function useToast() {
  return {
    items: state.items,
    dismiss,
    success: (message, duration) => push(message, 'success', duration),
    error: (message, duration) => push(message, 'error', duration ?? 8000),
    info: (message, duration) => push(message, 'info', duration),
  }
}
