import {defineStore} from "pinia";
import {ref} from "vue";


export const useUserStore = defineStore('userStore',() => {

    // 初始化时从localStorage读取用户信息
    const savedUserInfo = localStorage.getItem('userInfo')
    let userInfo = ref(savedUserInfo ? JSON.parse(savedUserInfo) : {})

    function setUserInfo(u){
        userInfo.value = u
        // 同步保存到localStorage
        if (u && Object.keys(u).length > 0) {
            localStorage.setItem('userInfo', JSON.stringify(u))
        }
    }

    // 清除用户信息
    function clearUserInfo() {
        userInfo.value = {}
        localStorage.removeItem('userInfo')
    }

    // 获取用户头像
    function getUserAvatar() {
        return userInfo.value?.cover || ''
    }

    return {userInfo, setUserInfo, clearUserInfo, getUserAvatar}
})