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

export const useUserStore = defineStore('user', () => {
  // State
  const currentUser = ref<string>('')
  const isLoggedIn = computed(() => !!currentUser.value)

  // Getters
  const userInitial = computed(() => {
    return currentUser.value.charAt(0).toUpperCase()
  })

  // Actions
  function login(username: string, rememberMe: boolean = false) {
    currentUser.value = username
    // 保存登录状态
    if (rememberMe) {
      localStorage.setItem('currentUser', username)
    } else {
      sessionStorage.setItem('currentUser', username)
    }
  }

  function logout() {
    currentUser.value = ''
    localStorage.removeItem('currentUser')
    sessionStorage.removeItem('currentUser')
  }

  function checkLoginStatus(): boolean {
    const savedUser = localStorage.getItem('currentUser') || sessionStorage.getItem('currentUser')
    if (savedUser) {
      currentUser.value = savedUser
      return true
    }
    return false
  }

  return {
    currentUser,
    isLoggedIn,
    userInitial,
    login,
    logout,
    checkLoginStatus
  }
})
