import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'; import { timerStore, TimerState } from './TimerStore'; // Context interface interface TimerContextType { timerState: TimerState; isLoading: boolean; updateReps: (reps: number) => Promise; updateWorkTime: (workTime: number) => Promise; updateRestTime: (restTime: number) => Promise; updateState: (state: Partial) => Promise; } // Default context values const defaultContextValue: TimerContextType = { timerState: { reps: 1, workTime: 0, restTime: 0 }, isLoading: true, updateReps: async () => {}, updateWorkTime: async () => {}, updateRestTime: async () => {}, updateState: async () => {} }; // Context creation const TimerContext = createContext(defaultContextValue); // Custom hook to use the context export const useTimerContext = () => useContext(TimerContext); // Provider props interface TimerProviderProps { children: ReactNode; } // Provider component export const TimerProvider: React.FC = ({ children }) => { const [timerState, setTimerState] = useState({ reps: 1, workTime: 0, restTime: 0 }); const [isLoading, setIsLoading] = useState(true); // Load data on startup useEffect(() => { const loadData = async () => { try { const state = await timerStore.getState(); setTimerState(state); } catch (error) { console.error('Error loading data:', error); } finally { setIsLoading(false); } }; loadData(); }, []); // Update repetitions const updateReps = async (reps: number) => { try { await timerStore.saveReps(reps); setTimerState(prev => ({ ...prev, reps })); } catch (error) { console.error('Error updating repetitions:', error); } }; // Update work time const updateWorkTime = async (workTime: number) => { try { await timerStore.saveWorkTime(workTime); setTimerState(prev => ({ ...prev, workTime })); } catch (error) { console.error('Error updating work time:', error); } }; // Update rest time const updateRestTime = async (restTime: number) => { try { await timerStore.saveRestTime(restTime); setTimerState(prev => ({ ...prev, restTime })); } catch (error) { console.error('Error updating rest time:', error); } }; // Update multiple values at once const updateState = async (state: Partial) => { try { const newState = { ...timerState, ...state }; await timerStore.saveState(newState); setTimerState(newState); } catch (error) { console.error('Error updating state:', error); } }; const contextValue: TimerContextType = { timerState, isLoading, updateReps, updateWorkTime, updateRestTime, updateState }; return ( {children} ); };