import { create } from 'zustand'

const getInitialTheme = () => {
    const saved = localStorage.getItem('theme')
    if (saved) return saved
    return 'light'
}

const useStore = create((set) => ({
    user: null,
    theme: getInitialTheme(),

    setUser: (user) => set({ user }),

    toggleTheme: () => set((state) => {
        const next = state.theme === 'light' ? 'dark' : 'light'
        localStorage.setItem('theme', next)
        if (next === 'dark') document.documentElement.classList.add('dark')
        else document.documentElement.classList.remove('dark')
        return { theme: next }
    }),

    initTheme: () => {
        const theme = getInitialTheme()
        if (theme === 'dark') document.documentElement.classList.add('dark')
        else document.documentElement.classList.remove('dark')
        set({ theme })
    },
}))

export default useStore