All files / web/src/components/practice/hooks useProgressiveAssistance.ts

69.51% Statements 472/679
98.11% Branches 52/53
83.33% Functions 5/6
69.51% Lines 472/679

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 6801x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 5x 5x 77x 77x 1x 1x 83x 83x 83x 83x 83x 83x 83x 1x 1x 1x 1x 1x 1x 1x 1x 1x 82x 82x 83x 5x 5x 5x 5x 5x 5x 5x 5x 5x 77x 77x 83x 1x 1x 1x 1x 1x 1x 1x 1x 1x 76x 76x 83x 31x 31x 22x 22x 22x 22x 22x 22x 22x 31x 31x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 31x 31x 2x 2x 2x 2x 2x 2x 2x 31x 31x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 31x 31x 1x 31x 31x 83x 83x 26x 26x 2x 2x 2x 2x 2x 2x 2x 26x 26x 20x 20x 20x 20x 20x 20x 20x 20x 26x 26x 1x 1x 1x 1x 1x 1x 1x 26x 26x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 26x 26x 1x 26x 26x 83x 83x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 1x 1x 1x 1x 1x 1x 1x 6x 6x 1x 6x 6x 83x 83x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 1x 3x 3x 83x 83x 10x 10x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 10x 10x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 1x 10x 10x 83x 83x   83x 83x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 5x 4x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                              
'use client'
 
import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react'
import type { SlotResult } from '@/db/schema/session-plans'
import {
  type AutoPauseStats,
  calculateAutoPauseInfo,
  calculateComplexityScaledThresholds,
  calculateNormalizedResponseTimeStats,
  getComplexityCost,
  type PauseInfo,
  type ProgressiveThresholds,
} from '../autoPauseCalculator'
import {
  getProgressiveAssistanceTiming,
  type ProgressiveAssistanceTimingConfig,
  shouldUseDebugTiming,
} from '@/constants/helpTiming'
 
// =============================================================================
// Types
// =============================================================================
 
export type AssistanceStateName = 'idle' | 'encouraging' | 'offeringHelp' | 'autoPaused' | 'inHelp'
 
export interface AssistanceEventLogEntry {
  timestamp: number
  event: string
  fromState: AssistanceStateName
  toState: AssistanceStateName
  note: string
}
 
export interface AssistanceContext {
  wrongAttemptCount: number
  helpedTermIndices: Set<number>
  allTermsHelped: boolean
  moveOnGraceStartedAt: number | null
  moveOnAvailable: boolean
  idleStartedAt: number
  thresholds: ProgressiveThresholds
  autoPauseStats: AutoPauseStats | null
  wrongAnswerThreshold: number
  moveOnGraceMs: number
  eventLog: AssistanceEventLogEntry[]
}
 
export interface AssistanceMachineState {
  state: AssistanceStateName
  context: AssistanceContext
}
 
export type AssistanceEvent =
  | { type: 'TIMER_ENCOURAGEMENT' }
  | { type: 'TIMER_HELP_OFFER' }
  | { type: 'TIMER_AUTO_PAUSE'; autoPauseStats: AutoPauseStats }
  | { type: 'TIMER_MOVE_ON_GRACE' }
  | { type: 'DIGIT_TYPED' }
  | { type: 'WRONG_ANSWER' }
  | { type: 'HELP_ENTERED' }
  | { type: 'HELP_TERM_COMPLETED'; termIndex: number }
  | { type: 'HELP_EXITED'; problemTermsCount: number }
  | { type: 'RESUMED' }
  | { type: 'PROBLEM_CHANGED' }
  | { type: 'DISMISS_WRONG_ANSWER_SUGGESTION' }
  | { type: 'UPDATE_THRESHOLDS'; thresholds: ProgressiveThresholds }
 
// =============================================================================
// Constants
// =============================================================================
 
const MAX_EVENT_LOG_SIZE = 30
 
// =============================================================================
// Pure Reducer
// =============================================================================
 
export function createFreshContext(
  thresholds: ProgressiveThresholds,
  wrongAnswerThreshold: number,
  moveOnGraceMs: number
): AssistanceContext {
  return {
    wrongAttemptCount: 0,
    helpedTermIndices: new Set(),
    allTermsHelped: false,
    moveOnGraceStartedAt: null,
    moveOnAvailable: false,
    idleStartedAt: Date.now(),
    thresholds,
    autoPauseStats: null,
    wrongAnswerThreshold,
    moveOnGraceMs,
    eventLog: [],
  }
}
 
function resetContext(ctx: AssistanceContext): AssistanceContext {
  return {
    ...ctx,
    wrongAttemptCount: 0,
    helpedTermIndices: new Set(),
    allTermsHelped: false,
    moveOnGraceStartedAt: null,
    moveOnAvailable: false,
    idleStartedAt: Date.now(),
    autoPauseStats: null,
  }
}
 
function appendLog(
  ctx: AssistanceContext,
  event: string,
  fromState: AssistanceStateName,
  toState: AssistanceStateName,
  note: string
): AssistanceEventLogEntry[] {
  const entry: AssistanceEventLogEntry = {
    timestamp: Date.now(),
    event,
    fromState,
    toState,
    note,
  }
  const log = [entry, ...ctx.eventLog]
  if (log.length > MAX_EVENT_LOG_SIZE) {
    log.length = MAX_EVENT_LOG_SIZE
  }
  return log
}
 
export function assistanceReducer(
  machine: AssistanceMachineState,
  event: AssistanceEvent
): AssistanceMachineState {
  const { state, context } = machine
 
  // UPDATE_THRESHOLDS can happen in any state
  if (event.type === 'UPDATE_THRESHOLDS') {
    return {
      state,
      context: {
        ...context,
        thresholds: event.thresholds,
        eventLog: appendLog(context, event.type, state, state, 'thresholds updated'),
      },
    }
  }
 
  // PROBLEM_CHANGED always resets to idle from any state
  if (event.type === 'PROBLEM_CHANGED') {
    const newCtx = resetContext(context)
    return {
      state: 'idle',
      context: {
        ...newCtx,
        eventLog: appendLog(context, event.type, state, 'idle', 'full reset'),
      },
    }
  }
 
  // DISMISS_WRONG_ANSWER_SUGGESTION — reset wrong attempt count
  if (event.type === 'DISMISS_WRONG_ANSWER_SUGGESTION') {
    return {
      state,
      context: {
        ...context,
        wrongAttemptCount: 0,
        eventLog: appendLog(context, event.type, state, state, 'dismissed'),
      },
    }
  }
 
  switch (state) {
    case 'idle': {
      switch (event.type) {
        case 'TIMER_ENCOURAGEMENT':
          return {
            state: 'encouraging',
            context: {
              ...context,
              eventLog: appendLog(context, event.type, 'idle', 'encouraging', ''),
            },
          }
 
        case 'DIGIT_TYPED':
          return {
            state: 'idle',
            context: {
              ...context,
              idleStartedAt: Date.now(),
              eventLog: appendLog(context, event.type, 'idle', 'idle', 'reset timer'),
            },
          }
 
        case 'WRONG_ANSWER': {
          const newCount = context.wrongAttemptCount + 1
          const nextState: AssistanceStateName =
            newCount >= context.wrongAnswerThreshold ? 'offeringHelp' : 'idle'
          return {
            state: nextState,
            context: {
              ...context,
              wrongAttemptCount: newCount,
              eventLog: appendLog(
                context,
                event.type,
                'idle',
                nextState,
                `count=${newCount}/${context.wrongAnswerThreshold}`
              ),
            },
          }
        }
 
        case 'HELP_ENTERED':
          return {
            state: 'inHelp',
            context: {
              ...context,
              eventLog: appendLog(context, event.type, 'idle', 'inHelp', ''),
            },
          }
 
        case 'TIMER_MOVE_ON_GRACE':
          if (context.allTermsHelped) {
            return {
              state: 'idle',
              context: {
                ...context,
                moveOnAvailable: true,
                moveOnGraceStartedAt: null,
                eventLog: appendLog(context, event.type, 'idle', 'idle', 'moveOn available'),
              },
            }
          }
          return machine
 
        default:
          return machine
      }
    }
 
    case 'encouraging': {
      switch (event.type) {
        case 'TIMER_HELP_OFFER':
          return {
            state: 'offeringHelp',
            context: {
              ...context,
              eventLog: appendLog(context, event.type, 'encouraging', 'offeringHelp', ''),
            },
          }
 
        case 'DIGIT_TYPED':
          return {
            state: 'idle',
            context: {
              ...context,
              idleStartedAt: Date.now(),
              eventLog: appendLog(context, event.type, 'encouraging', 'idle', 'reset timer'),
            },
          }
 
        case 'HELP_ENTERED':
          return {
            state: 'inHelp',
            context: {
              ...context,
              eventLog: appendLog(context, event.type, 'encouraging', 'inHelp', ''),
            },
          }
 
        case 'WRONG_ANSWER': {
          const newCount = context.wrongAttemptCount + 1
          const nextState: AssistanceStateName =
            newCount >= context.wrongAnswerThreshold ? 'offeringHelp' : 'encouraging'
          return {
            state: nextState,
            context: {
              ...context,
              wrongAttemptCount: newCount,
              eventLog: appendLog(
                context,
                event.type,
                'encouraging',
                nextState,
                `count=${newCount}/${context.wrongAnswerThreshold}`
              ),
            },
          }
        }
 
        default:
          return machine
      }
    }
 
    case 'offeringHelp': {
      switch (event.type) {
        case 'TIMER_AUTO_PAUSE':
          return {
            state: 'autoPaused',
            context: {
              ...context,
              autoPauseStats: event.autoPauseStats,
              eventLog: appendLog(context, event.type, 'offeringHelp', 'autoPaused', ''),
            },
          }
 
        case 'DIGIT_TYPED':
          return {
            state: 'idle',
            context: {
              ...context,
              idleStartedAt: Date.now(),
              eventLog: appendLog(context, event.type, 'offeringHelp', 'idle', 'reset timer'),
            },
          }
 
        case 'HELP_ENTERED':
          return {
            state: 'inHelp',
            context: {
              ...context,
              eventLog: appendLog(context, event.type, 'offeringHelp', 'inHelp', ''),
            },
          }
 
        default:
          return machine
      }
    }
 
    case 'autoPaused': {
      switch (event.type) {
        case 'RESUMED':
          return {
            state: 'idle',
            context: {
              ...context,
              idleStartedAt: Date.now(),
              eventLog: appendLog(context, event.type, 'autoPaused', 'idle', 'reset timer'),
            },
          }
 
        default:
          return machine
      }
    }
 
    case 'inHelp': {
      switch (event.type) {
        case 'HELP_TERM_COMPLETED': {
          const newSet = new Set(context.helpedTermIndices)
          newSet.add(event.termIndex)
          return {
            state: 'inHelp',
            context: {
              ...context,
              helpedTermIndices: newSet,
              eventLog: appendLog(
                context,
                event.type,
                'inHelp',
                'inHelp',
                `term=${event.termIndex}, helped=${newSet.size}`
              ),
            },
          }
        }
 
        case 'HELP_EXITED': {
          // Determine if all terms have been helped
          // Help is for terms at indices 1..n-1 (first term is the starting number)
          const helpableTermCount = Math.max(0, event.problemTermsCount - 1)
          const allHelped =
            helpableTermCount > 0 && context.helpedTermIndices.size >= helpableTermCount
          const shouldStartGrace = allHelped && !context.moveOnAvailable
 
          return {
            state: 'idle',
            context: {
              ...context,
              idleStartedAt: Date.now(),
              allTermsHelped: allHelped || context.allTermsHelped,
              moveOnGraceStartedAt: shouldStartGrace ? Date.now() : context.moveOnGraceStartedAt,
              eventLog: appendLog(
                context,
                event.type,
                'inHelp',
                'idle',
                allHelped ? 'all terms helped, grace started' : ''
              ),
            },
          }
        }
 
        case 'DIGIT_TYPED':
          return {
            state: 'idle',
            context: {
              ...context,
              idleStartedAt: Date.now(),
              eventLog: appendLog(context, event.type, 'inHelp', 'idle', 'student typed'),
            },
          }
 
        default:
          return machine
      }
    }
 
    default:
      return machine
  }
}
 
// =============================================================================
// Derived Values
// =============================================================================
 
export function showWrongAnswerSuggestion(
  state: AssistanceStateName,
  ctx: AssistanceContext
): boolean {
  return (
    ctx.wrongAttemptCount >= ctx.wrongAnswerThreshold &&
    state !== 'inHelp' &&
    state !== 'autoPaused'
  )
}
 
// =============================================================================
// Hook
// =============================================================================
 
export interface UseProgressiveAssistanceInputs {
  /** Current attempt (null when loading) */
  attempt: {
    startTime: number
    accumulatedPauseMs: number
    problem: {
      terms: number[]
      generationTrace?: { totalComplexityCost?: number }
    }
  } | null
  /** Historical results for threshold calculation */
  results: SlotResult[]
  /** Number of terms in current problem */
  problemTermsCount: number
  /** Whether session is currently paused */
  isPaused: boolean
  /** Called when auto-pause fires — should pause the session and set pause info */
  onAutoPause: (info: PauseInfo) => void
}
 
export interface UseProgressiveAssistanceReturn {
  machineState: AssistanceMachineState
  showWrongAnswerSuggestion: boolean
  /** True when complexity cost data is missing from the current problem */
  complexityCostMissing: boolean
  onDigitTyped: () => void
  onWrongAnswer: () => void
  onHelpEntered: () => void
  onHelpTermCompleted: (termIndex: number) => void
  onHelpExited: () => void
  onResumed: () => void
  onProblemChanged: () => void
  dismissWrongAnswerSuggestion: () => void
}
 
export function useProgressiveAssistance(
  inputs: UseProgressiveAssistanceInputs
): UseProgressiveAssistanceReturn {
  const { attempt, results, problemTermsCount, isPaused, onAutoPause } = inputs

  // Determine timing config
  const timing = useMemo<ProgressiveAssistanceTimingConfig>(
    () => getProgressiveAssistanceTiming(shouldUseDebugTiming()),
    []
  )

  // Derive complexity cost of the current problem
  const currentProblemCost = useMemo(
    () => (attempt ? getComplexityCost(attempt.problem) : null),
    [attempt?.problem?.generationTrace?.totalComplexityCost] // eslint-disable-line react-hooks/exhaustive-deps
  )
  const complexityCostMissing = attempt !== null && currentProblemCost === null

  // Calculate initial thresholds
  const initialThresholds = useMemo(
    () => calculateComplexityScaledThresholds(results, timing, currentProblemCost),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [] // Only on mount — thresholds update via UPDATE_THRESHOLDS event
  )

  const [machine, dispatch] = useReducer(assistanceReducer, {
    state: 'idle' as AssistanceStateName,
    context: createFreshContext(
      initialThresholds,
      timing.wrongAnswerThreshold,
      timing.moveOnGraceMs
    ),
  })

  // Update thresholds when results change or current problem cost changes
  const prevResultsLengthRef = useRef(results.length)
  const prevCostRef = useRef(currentProblemCost)
  useEffect(() => {
    const resultsChanged = results.length !== prevResultsLengthRef.current
    const costChanged = currentProblemCost !== prevCostRef.current
    if (resultsChanged || costChanged) {
      prevResultsLengthRef.current = results.length
      prevCostRef.current = currentProblemCost
      const newThresholds = calculateComplexityScaledThresholds(results, timing, currentProblemCost)
      dispatch({ type: 'UPDATE_THRESHOLDS', thresholds: newThresholds })
    }
  }, [results, timing, currentProblemCost])

  // Refs for stable callbacks that need current values
  const onAutoPauseRef = useRef(onAutoPause)
  onAutoPauseRef.current = onAutoPause
  const problemTermsCountRef = useRef(problemTermsCount)
  problemTermsCountRef.current = problemTermsCount

  // Timer orchestration for idle → encouraging → offeringHelp → autoPaused
  useEffect(() => {
    const timedStates: AssistanceStateName[] = ['idle', 'encouraging', 'offeringHelp']
    if (!timedStates.includes(machine.state)) return
    if (isPaused || !attempt) return

    const { thresholds, idleStartedAt } = machine.context
    const elapsed = Date.now() - idleStartedAt

    let targetMs: number
    let timerEventFactory: () => AssistanceEvent

    switch (machine.state) {
      case 'idle':
        targetMs = thresholds.encouragementMs
        timerEventFactory = () => ({ type: 'TIMER_ENCOURAGEMENT' })
        break
      case 'encouraging':
        targetMs = thresholds.helpOfferMs
        timerEventFactory = () => ({ type: 'TIMER_HELP_OFFER' })
        break
      case 'offeringHelp': {
        targetMs = thresholds.autoPauseMs
        timerEventFactory = () => {
          const { stats } = calculateAutoPauseInfo(results)
          // Enrich stats with complexity info
          const normStats = calculateNormalizedResponseTimeStats(results)
          const enrichedStats: AutoPauseStats = {
            ...stats,
            meanPerUnitMs: normStats.count >= 1 ? normStats.meanPerUnit : undefined,
            currentProblemCost: currentProblemCost ?? undefined,
            complexityCostMissing,
          }
          return { type: 'TIMER_AUTO_PAUSE', autoPauseStats: enrichedStats }
        }
        break
      }
      default:
        return
    }

    const remainingMs = targetMs - elapsed

    const fireTimer = () => {
      const timerEvent = timerEventFactory()
      dispatch(timerEvent)

      if (timerEvent.type === 'TIMER_AUTO_PAUSE') {
        const autoPauseInfo: PauseInfo = {
          pausedAt: new Date(),
          reason: 'auto-timeout',
          autoPauseStats: timerEvent.autoPauseStats,
        }
        onAutoPauseRef.current(autoPauseInfo)
      }
    }

    if (remainingMs <= 0) {
      fireTimer()
      return
    }

    const timeoutId = setTimeout(fireTimer, remainingMs)
    return () => clearTimeout(timeoutId)
  }, [
    machine.state,
    machine.context.idleStartedAt,
    machine.context.thresholds,
    isPaused,
    attempt,
    results,
    currentProblemCost,
    complexityCostMissing,
  ])

  // Move-on grace timer
  useEffect(() => {
    if (machine.state !== 'idle') return
    if (!machine.context.allTermsHelped) return
    if (machine.context.moveOnAvailable) return
    if (!machine.context.moveOnGraceStartedAt) return

    const elapsed = Date.now() - machine.context.moveOnGraceStartedAt
    const remaining = machine.context.moveOnGraceMs - elapsed

    if (remaining <= 0) {
      dispatch({ type: 'TIMER_MOVE_ON_GRACE' })
      return
    }

    const timeoutId = setTimeout(() => {
      dispatch({ type: 'TIMER_MOVE_ON_GRACE' })
    }, remaining)

    return () => clearTimeout(timeoutId)
  }, [
    machine.state,
    machine.context.allTermsHelped,
    machine.context.moveOnAvailable,
    machine.context.moveOnGraceStartedAt,
    machine.context.moveOnGraceMs,
  ])

  // Stable event dispatchers
  const onDigitTyped = useCallback(() => {
    dispatch({ type: 'DIGIT_TYPED' })
  }, [])

  const onWrongAnswer = useCallback(() => {
    dispatch({ type: 'WRONG_ANSWER' })
  }, [])

  const onHelpEntered = useCallback(() => {
    dispatch({ type: 'HELP_ENTERED' })
  }, [])

  const onHelpTermCompleted = useCallback((termIndex: number) => {
    dispatch({ type: 'HELP_TERM_COMPLETED', termIndex })
  }, [])

  const onHelpExited = useCallback(() => {
    dispatch({ type: 'HELP_EXITED', problemTermsCount: problemTermsCountRef.current })
  }, [])

  const onResumed = useCallback(() => {
    dispatch({ type: 'RESUMED' })
  }, [])

  const onProblemChanged = useCallback(() => {
    dispatch({ type: 'PROBLEM_CHANGED' })
  }, [])

  const dismissWrongAnswerSuggestion = useCallback(() => {
    dispatch({ type: 'DISMISS_WRONG_ANSWER_SUGGESTION' })
  }, [])

  // Derived values
  const showWrongAnswerSuggestionValue = showWrongAnswerSuggestion(machine.state, machine.context)

  return {
    machineState: machine,
    showWrongAnswerSuggestion: showWrongAnswerSuggestionValue,
    complexityCostMissing,
    onDigitTyped,
    onWrongAnswer,
    onHelpEntered,
    onHelpTermCompleted,
    onHelpExited,
    onResumed,
    onProblemChanged,
    dismissWrongAnswerSuggestion,
  }
}