import { useReducer, useCallback } from 'react'; import type { Exercise } from '../types/lesson'; export interface LessonState { exercises: Exercise[]; currentIndex: number; hearts: number; correctCount: number; selectedAnswer: unknown; isCorrect: boolean | null; isChecked: boolean; isFinished: boolean; } type LessonAction = | { type: 'SET_EXERCISES'; exercises: Exercise[] } | { type: 'RESTORE_STATE'; exercises: Exercise[]; currentIndex: number; hearts: number; correctCount: number } | { type: 'SELECT_ANSWER'; answer: unknown } | { type: 'CHECK_ANSWER'; correct: boolean } | { type: 'NEXT_EXERCISE' } | { type: 'FINISH' }; const initialState: LessonState = { exercises: [], currentIndex: 0, hearts: 5, correctCount: 0, selectedAnswer: null, isCorrect: null, isChecked: false, isFinished: false, }; function lessonReducer(state: LessonState, action: LessonAction): LessonState { switch (action.type) { case 'SET_EXERCISES': return { ...initialState, exercises: action.exercises, }; case 'RESTORE_STATE': return { ...initialState, exercises: action.exercises, currentIndex: action.currentIndex, hearts: action.hearts, correctCount: action.correctCount, }; case 'SELECT_ANSWER': if (state.isChecked) return state; return { ...state, selectedAnswer: action.answer, }; case 'CHECK_ANSWER': { const newHearts = action.correct ? state.hearts : state.hearts - 1; const newCorrectCount = action.correct ? state.correctCount + 1 : state.correctCount; const isFinished = newHearts === 0; return { ...state, isCorrect: action.correct, isChecked: true, hearts: newHearts, correctCount: newCorrectCount, isFinished, }; } case 'NEXT_EXERCISE': { const nextIndex = state.currentIndex + 1; const isFinished = nextIndex >= state.exercises.length; return { ...state, currentIndex: nextIndex, selectedAnswer: null, isCorrect: null, isChecked: false, isFinished, }; } case 'FINISH': return { ...state, isFinished: true, }; default: return state; } } export function useLesson() { const [state, dispatch] = useReducer(lessonReducer, initialState); const setExercises = useCallback( (exercises: Exercise[]) => dispatch({ type: 'SET_EXERCISES', exercises }), [], ); const restoreState = useCallback( (exercises: Exercise[], currentIndex: number, hearts: number, correctCount: number) => dispatch({ type: 'RESTORE_STATE', exercises, currentIndex, hearts, correctCount }), [], ); const selectAnswer = useCallback( (answer: unknown) => dispatch({ type: 'SELECT_ANSWER', answer }), [], ); const checkAnswer = useCallback( (correct: boolean) => dispatch({ type: 'CHECK_ANSWER', correct }), [], ); const nextExercise = useCallback( () => dispatch({ type: 'NEXT_EXERCISE' }), [], ); const finish = useCallback(() => dispatch({ type: 'FINISH' }), []); return { state, setExercises, restoreState, selectAnswer, checkAnswer, nextExercise, finish, }; }