import { create } from 'zustand'
import { User } from '../../types'

type UserStore = {
  user: User | null
  setUser: (user: User) => void
}

const UserStore = create<UserStore>((set) => {
  const savedUser = typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('user') || 'null') : null
  return {
    user: savedUser,
    setUser: (user: User) => {
      if (typeof window !== 'undefined') {
        localStorage.setItem('user', JSON.stringify(user))
      }
      set({ user })
    }
  }
})

export default UserStore
