import { ref } from 'vue'
import { useUserStore } from '@/stores/modules/user'

interface LoginResult {
  status: boolean
  error?: string
  isFirstLogin?: boolean
}
const isLoginModalOpen = ref(false)
let resolvePromise: ((value: LoginResult) => void) | null = null

export function useLoginModal() {
  const openLoginModal = (): Promise<LoginResult> => {
    const userStore = useUserStore()
    const { isLogin } = storeToRefs(userStore)
    if (isLogin.value)
      return Promise.resolve({ status: true, isFirstLogin: false })
    isLoginModalOpen.value = true
    return new Promise((resolve) => {
      resolvePromise = resolve
    })
  }

  const closeLoginModal = (result: LoginResult) => {
    isLoginModalOpen.value = false
    if (resolvePromise) {
      resolvePromise(result)
      resolvePromise = null
    }
  }

  return {
    isLoginModalOpen,
    openLoginModal,
    closeLoginModal,
  }
}
