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

export const useModalStore = defineStore('modal', () => {
  const modals = ref([])

  const isModal = (name) => modals.value.some((x) => x.name === name)
  const getModal = (name) => modals.value.find((x) => x.name === name)
  const getActiveModal = computed(() => modals.value.at(-1))

  const openModal = (name, data) => {
    if (!modals.value.some((x) => x.name === name)) {
      modals.value.push({ name, data })
    }
  }

  const closeModal = (name) => {
    if (name) {
      modals.value = modals.value.filter((x) => x.name !== name)
    } else if (modals.value.length > 0) {
      modals.value.pop()
    }
  }

  return {
    modals,
    getActiveModal,
    isModal,
    getModal,
    openModal,
    closeModal,
  }
})
