import { ref, readonly } from 'vue'
import type { Toast } from '../types/toast'

let nextId = 1
const toasts = ref<Toast[]>([])

export function useToast() {
  function add(message: string, type: Toast['type'] = 'info', durationMs = 3500) {
    const id = nextId++
    toasts.value.push({ id, message, type, durationMs })
    if (durationMs > 0) {
      setTimeout(() => remove(id), durationMs)
    }
  }

  function remove(id: number) {
    const idx = toasts.value.findIndex(t => t.id === id)
    if (idx !== -1) toasts.value.splice(idx, 1)
  }

  return {
    toasts: readonly(toasts),
    success: (msg: string, durationMs?: number) => add(msg, 'success', durationMs),
    error: (msg: string, durationMs?: number) => add(msg, 'error', durationMs),
    info: (msg: string, durationMs?: number) => add(msg, 'info', durationMs),
    remove,
  }
}
