export const useUiStore = defineStore('ui', () => {
    const sidebarCollapsed = ref(false)
    const darkMode = ref(false)

    if (import.meta.client) {
        const saved = localStorage.getItem('ui-sidebar-collapsed')
        if (saved !== null) {
            sidebarCollapsed.value = saved === 'true'
        }

        const savedDark = localStorage.getItem('ui-dark-mode')
        if (savedDark !== null) {
            darkMode.value = savedDark === 'true'
        }
        applyDarkClass(darkMode.value)
    }

    watch(sidebarCollapsed, (val) => {
        if (import.meta.client) {
            localStorage.setItem('ui-sidebar-collapsed', String(val))
        }
    })

    watch(darkMode, (val) => {
        if (import.meta.client) {
            localStorage.setItem('ui-dark-mode', String(val))
            applyDarkClass(val)
        }
    })

    function applyDarkClass(dark: boolean) {
        if (dark) {
            document.documentElement.classList.add('dark')
        } else {
            document.documentElement.classList.remove('dark')
        }
    }

    function toggleDarkMode() {
        darkMode.value = !darkMode.value
    }

    function toggleSidebar() {
        sidebarCollapsed.value = !sidebarCollapsed.value
    }

    return { sidebarCollapsed, darkMode, toggleSidebar, toggleDarkMode }
})
