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

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

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

  function addToast(toast: Omit<Toast, 'id'>) {
    const id = crypto.randomUUID()
    const duration = toast.duration ?? (toast.type === 'error' ? 8000 : 5000)

    const newToast: Toast = {
      ...toast,
      id,
      duration,
    }

    toasts.value.push(newToast)

    // Auto-remove after duration
    if (duration > 0) {
      setTimeout(() => {
        removeToast(id)
      }, duration)
    }
  }

  function removeToast(id: string) {
    const index = toasts.value.findIndex(t => t.id === id)
    if (index !== -1) {
      toasts.value.splice(index, 1)
    }
  }

  function success(message: string, duration?: number) {
    addToast({ type: 'success', message, duration })
  }

  function error(message: string, duration?: number) {
    addToast({ type: 'error', message, duration })
  }

  function warning(message: string, duration?: number) {
    addToast({ type: 'warning', message, duration })
  }

  function info(message: string, duration?: number) {
    addToast({ type: 'info', message, duration })
  }

  return {
    toasts,
    addToast,
    removeToast,
    success,
    error,
    warning,
    info,
  }
})
