import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface Toast {
  id: number
  message: string
  type: 'success' | 'error' | 'warning' | 'info'
  timeout?: number
}

let nextId = 0

export const useToastStore = defineStore('toast', () => {
  const toasts = ref<Toast[]>([])

  function show(message: string, type: Toast['type'] = 'info', timeout = 5000): void {
    const id = nextId++
    toasts.value.push({ id, message, type, timeout })

    if (timeout > 0) {
      setTimeout(() => dismiss(id), timeout)
    }
  }

  function dismiss(id: number): void {
    const index = toasts.value.findIndex(t => t.id === id)
    if (index > -1) toasts.value.splice(index, 1)
  }

  function success(message: string): void { show(message, 'success') }
  function error(message: string): void { show(message, 'error') }
  function warning(message: string): void { show(message, 'warning') }
  function info(message: string): void { show(message, 'info') }

  return { toasts, show, dismiss, success, error, warning, info }
})
