import { create } from 'zustand'

const savedUsername = localStorage.getItem('savedUsername')

const useAuthStore = create((set) => ({
  user: null,
  token: localStorage.getItem('token') || null,
  savedUsername: savedUsername || null,

  login(user, token) {
    localStorage.setItem('token', token)
    localStorage.setItem('savedUsername', user.username)
    set({ user, token, savedUsername: user.username })
  },

  logout() {
    localStorage.removeItem('token')
    localStorage.removeItem('savedUsername')
    set({ user: null, token: null, savedUsername: null })
  },

  clearSavedUsername() {
    localStorage.removeItem('savedUsername')
    set({ savedUsername: null })
  },
}))

export default useAuthStore
