1- import React , { createContext , useContext , useReducer } from 'react' ;
1+ import React , { createContext , useContext , useReducer , useEffect } from 'react' ;
22
33const AppContext = createContext ( ) ;
44
@@ -12,6 +12,7 @@ const initialState = {
1212 schedules : [ ] ,
1313 isManualMode : false ,
1414 currentTime : new Date ( ) . toLocaleTimeString ( ) ,
15+ theme : 'light' ,
1516} ;
1617
1718function appReducer ( state , action ) {
@@ -44,13 +45,52 @@ function appReducer(state, action) {
4445 return { ...state , isManualMode : ! state . isManualMode } ;
4546 case 'UPDATE_TIME' :
4647 return { ...state , currentTime : action . payload } ;
48+ case 'SET_THEME' :
49+ return { ...state , theme : action . payload } ;
4750 default :
4851 return state ;
4952 }
5053}
5154
5255export function AppProvider ( { children } ) {
53- const [ state , dispatch ] = useReducer ( appReducer , initialState ) ;
56+ // Lazy initializer reads saved theme synchronously to avoid an initial flash
57+ const init = ( initState ) => {
58+ try {
59+ const saved = localStorage . getItem ( 'themeChoice' ) ;
60+ if ( saved ) {
61+ return { ...initState , theme : saved } ;
62+ }
63+ } catch ( e ) {
64+ // ignore and fall back to defaults
65+ }
66+ return initState ;
67+ } ;
68+
69+ const [ state , dispatch ] = useReducer ( appReducer , initialState , init ) ;
70+
71+ // Apply theme class to document root and persist choice
72+ useEffect ( ( ) => {
73+ const applyTheme = ( themeChoice ) => {
74+ let resolved = themeChoice ;
75+ if ( themeChoice === 'auto' ) {
76+ resolved = window . matchMedia && window . matchMedia ( '(prefers-color-scheme: dark)' ) . matches ? 'dark' : 'light' ;
77+ }
78+
79+ if ( resolved === 'dark' ) {
80+ document . documentElement . classList . add ( 'dark' ) ;
81+ } else {
82+ document . documentElement . classList . remove ( 'dark' ) ;
83+ }
84+
85+ try {
86+ localStorage . setItem ( 'themeChoice' , themeChoice ) ;
87+ } catch ( e ) {
88+ // ignore
89+ }
90+ } ;
91+
92+ applyTheme ( state . theme ) ;
93+ } , [ state . theme ] ) ;
5494
5595 return (
5696 < AppContext . Provider value = { { state, dispatch } } >
0 commit comments