11import { create } from 'zustand'
22import { devtools , persist } from 'zustand/middleware'
33import { createLogger } from '@/lib/logs/console/logger'
4+ import { syncThemeToNextThemes } from '@/lib/theme-sync'
45import type { General , GeneralStore , UserSettings } from '@/stores/settings/general/types'
56
67const logger = createLogger ( 'GeneralStore' )
78
8- const CACHE_TIMEOUT = 5000
9+ const CACHE_TIMEOUT = 3600000 // 1 hour - settings rarely change
910const MAX_ERROR_RETRIES = 2
1011
1112export const useGeneralStore = create < GeneralStore > ( ) (
@@ -14,21 +15,22 @@ export const useGeneralStore = create<GeneralStore>()(
1415 ( set , get ) => {
1516 let lastLoadTime = 0
1617 let errorRetryCount = 0
18+ let hasLoadedFromDb = false // Track if we've loaded from DB in this session
1719
1820 const store : General = {
1921 isAutoConnectEnabled : true ,
2022 isAutoPanEnabled : true ,
2123 isConsoleExpandedByDefault : true ,
2224 isDebugModeEnabled : false ,
23- theme : 'system' as const ,
25+ theme : 'system' as const , // Keep for compatibility but not used
2426 telemetryEnabled : true ,
2527 isLoading : false ,
2628 error : null ,
2729 // Individual loading states
2830 isAutoConnectLoading : false ,
2931 isAutoPanLoading : false ,
3032 isConsoleExpandedByDefaultLoading : false ,
31- isThemeLoading : false ,
33+ isThemeLoading : false , // Keep for compatibility but not used
3234 isTelemetryLoading : false ,
3335 }
3436
@@ -99,7 +101,26 @@ export const useGeneralStore = create<GeneralStore>()(
99101
100102 setTheme : async ( theme ) => {
101103 if ( get ( ) . isThemeLoading ) return
102- await updateSettingOptimistic ( 'theme' , theme , 'isThemeLoading' , 'theme' )
104+
105+ const originalTheme = get ( ) . theme
106+
107+ // Optimistic update
108+ set ( { theme, isThemeLoading : true } )
109+
110+ // Update next-themes immediately for instant feedback
111+ syncThemeToNextThemes ( theme )
112+
113+ try {
114+ // Sync to DB for authenticated users
115+ await get ( ) . updateSetting ( 'theme' , theme )
116+ set ( { isThemeLoading : false } )
117+ } catch ( error ) {
118+ // Rollback on error
119+ set ( { theme : originalTheme , isThemeLoading : false } )
120+ syncThemeToNextThemes ( originalTheme )
121+ logger . error ( 'Failed to sync theme to database:' , error )
122+ throw error
123+ }
103124 } ,
104125
105126 setTelemetryEnabled : async ( enabled ) => {
@@ -114,6 +135,27 @@ export const useGeneralStore = create<GeneralStore>()(
114135
115136 // API Actions
116137 loadSettings : async ( force = false ) => {
138+ // Skip if we've already loaded from DB and not forcing
139+ if ( hasLoadedFromDb && ! force ) {
140+ logger . debug ( 'Already loaded settings from DB, using cached data' )
141+ return
142+ }
143+
144+ // If we have persisted state and not forcing, check if we need to load
145+ const persistedState = localStorage . getItem ( 'general-settings' )
146+ if ( persistedState && ! force ) {
147+ try {
148+ const parsed = JSON . parse ( persistedState )
149+ // If we have valid theme data, skip DB load unless forced
150+ if ( parsed . state ?. theme ) {
151+ logger . debug ( 'Using cached settings from localStorage' )
152+ hasLoadedFromDb = true // Mark as loaded to prevent future API calls
153+ return
154+ }
155+ } catch ( e ) {
156+ // If parsing fails, continue to load from DB
157+ }
158+ }
117159 // Skip loading if on a subdomain or chat path
118160 if (
119161 typeof window !== 'undefined' &&
@@ -147,15 +189,24 @@ export const useGeneralStore = create<GeneralStore>()(
147189
148190 set ( {
149191 isAutoConnectEnabled : data . autoConnect ,
150- isAutoPanEnabled : data . autoPan ?? true , // Default to true if undefined
151- isConsoleExpandedByDefault : data . consoleExpandedByDefault ?? true , // Default to true if undefined
152- theme : data . theme ,
192+ isAutoPanEnabled : data . autoPan ?? true ,
193+ isConsoleExpandedByDefault : data . consoleExpandedByDefault ?? true ,
194+ theme : data . theme || 'system' ,
153195 telemetryEnabled : data . telemetryEnabled ,
154196 isLoading : false ,
155197 } )
156198
199+ // Sync theme to next-themes if it's different
200+ if ( data . theme && typeof window !== 'undefined' ) {
201+ const currentTheme = localStorage . getItem ( 'sim-theme' )
202+ if ( currentTheme !== data . theme ) {
203+ syncThemeToNextThemes ( data . theme )
204+ }
205+ }
206+
157207 lastLoadTime = now
158208 errorRetryCount = 0
209+ hasLoadedFromDb = true
159210 } catch ( error ) {
160211 logger . error ( 'Error loading settings:' , error )
161212 set ( {
0 commit comments