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

export const useUiStore = defineStore('ui', () => {
  const currentSection = ref('search')
  const showLoginModal = ref(false)
  const toasts = ref([])
  const pendingAction = ref(null)

  let toastId = 0

  function showSection(name) {
    currentSection.value = name
  }

  function showToast(msg, duration = 1800) {
    const id = ++toastId
    toasts.value.push({ id, msg })
    setTimeout(() => {
      toasts.value = toasts.value.filter((t) => t.id !== id)
    }, duration)
  }

  function openLogin(afterLogin) {
    if (afterLogin) {
      pendingAction.value = afterLogin
    }
    showLoginModal.value = true
  }

  function closeLogin() {
    showLoginModal.value = false
  }

  function runPendingAction() {
    if (pendingAction.value) {
      const action = pendingAction.value
      pendingAction.value = null
      action()
    }
  }

  return {
    currentSection,
    showLoginModal,
    toasts,
    pendingAction,
    showSection,
    showToast,
    openLogin,
    closeLogin,
    runPendingAction,
  }
})
