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

91.76% Statements 1147/1250
89.58% Branches 215/240
88.23% Functions 15/17
91.76% Lines 1147/1250

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 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 12511x 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 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 14x 14x 14x 14x 2x 2x 2x 2x 2x 2x 2x 2x 12x 14x 14x 1x 1x 1x 1x 1x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 15x 19x 1x 19x 19x 3x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 21x 18x 16x 16x 16x 16x 18x 21x 21x 21x 21x 21x 15x 21x 1x 1x 21x 21x 2x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 10x 10x 10x 1x 1x 1x 1x 1x 1x 282x 282x 282x 815x 815x 815x 282x 282x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 3x 3x 3x 3x 84x 84x 87x 84x 87x 217x 217x 217x 68x 68x 217x 16x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 118x 118x 118x 244x 244x 244x 244x 117x 117x 117x 117x 244x 40x 40x 40x 40x 40x 40x 77x 77x 77x 77x 77x 77x 244x 40x 40x 40x 244x 3x 3x 3x 3x 3x 3x 37x 37x 37x 37x 37x 37x 49x 49x 37x 37x 37x 37x 37x 37x 37x 37x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 24x 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 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 298x 298x 298x 298x 298x 298x 298x 93x               93x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 294x 294x 294x 294x 294x 294x 179x 294x 6x 294x 13x 13x 13x 13x 5x 5x 4x 2x 13x 12x 12x 1x 1x 1x     294x 96x 294x 298x 298x 298x 265x 171x 298x 298x 298x 265x 171x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 294x 294x 8x 8x 8x 294x 294x 294x 294x 282x 282x 282x 13x 13x 13x 13x 294x                 294x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 298x 298x 298x 298x 298x 294x 13x 298x 298x 298x 265x 46x 46x 298x 298x 298x 292x 292x 292x 292x 28x 28x 292x 28x 28x 298x 298x 298x 298x 298x 172x 159x 298x 298x 298x 298x 298x 298x 298x 172x 159x 138x 298x 298x 298x 298x 298x 172x 159x 298x 298x 298x 298x 298x 298x 298x 298x 298x 294x 21x 21x 273x 294x 1x 1x 272x 298x 298x 298x 298x 294x 6x 6x 288x 298x 298x 298x 298x 298x 298x 298x 298x 86x 86x 86x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 237x 237x 93x 93x 93x 93x 93x 144x 144x 144x 144x 144x 144x                                                                                       298x 298x 298x 298x 84x 84x 84x 84x 7x 4x 84x 1x 1x 83x 83x 83x 83x 84x 3x 3x 3x 3x 3x 83x 83x 83x 83x 83x 83x 83x 84x 10x 10x 10x 10x 10x 10x 10x 73x 84x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 49x 49x 25x 49x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 49x 42x 42x 42x 84x 12x 12x 12x 12x 12x 12x 3x 3x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x     12x 12x 84x 84x 84x 84x 13x 13x 13x 2x   13x     13x 13x 84x 84x 298x 298x 298x 298x 4x 4x 4x 1x   4x     4x 4x 4x 3x 3x 3x 4x 4x 4x     3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 298x 298x 298x 15x 15x 15x 14x 14x 14x 14x 4x 3x 14x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 14x 298x 298x 298x 4x 4x 4x 4x 4x           4x 298x 298x 298x                   298x 298x 298x                         298x 298x 298x 20x 20x 20x 20x 1x   20x     20x 20x 298x 298x 298x 11x 11x 11x 11x 11x 11x 298x 298x 298x 298x 7x 7x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 7x 7x 298x 298x 298x 298x 3x 3x 3x 3x 3x 3x 298x 298x 298x 1x 298x 298x 298x 2x 298x 298x 298x 14x 14x 14x 14x 14x 14x 14x 11x 11x 11x 14x 14x 14x 14x 14x 298x 298x 298x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 93x 93x 93x 10x 10x 10x 9x 7x 10x 93x 93x 10x 10x 7x 7x 7x 7x 7x 7x 7x 10x 93x 93x 19x 10x 19x 93x 93x     93x 93x 93x 93x 93x 93x 93x 93x 93x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x 298x  
'use client'
 
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { GeneratedProblem } from '@/db/schema/session-plans'
 
// =============================================================================
// Types
// =============================================================================
 
/**
 * Problem context passed as a prop - the single source of truth for what problem
 * is currently being worked on. This is computed by the parent component from
 * redoState + session plan, eliminating dual sources of truth.
 */
export interface ProblemContext {
  /** The problem being solved */
  problem: GeneratedProblem
  /** Index in the current part (original slot index for redos) */
  slotIndex: number
  /** Part index in the session */
  partIndex: number
}
 
/**
 * Input-level state for a problem attempt.
 * This is what the student is actively working on - their answer input.
 */
export interface AttemptInput {
  /** The problem being solved */
  problem: GeneratedProblem
  /** Index in the current part */
  slotIndex: number
  /** Part index in the session */
  partIndex: number
  /** When the attempt started */
  startTime: number
  /** Accumulated time spent paused (ms) - subtract from elapsed time for actual response time */
  accumulatedPauseMs: number
  /**
   * Subset of `accumulatedPauseMs` that came from the tab being hidden /
   * backgrounded (visibility layer, #156). Audit-only — recorded on the result
   * as `hiddenTimeExcludedMs`; it is already included in `accumulatedPauseMs`.
   */
  accumulatedHiddenMs: number
  /** User's current answer input */
  userAnswer: string
  /** Number of times user used backspace or had digits rejected */
  correctionCount: number
  /** Whether manual submit is required (exceeded auto-submit threshold) */
  manualSubmitRequired: boolean
  /** Rejected digit to show as red X (null = no rejection) */
  rejectedDigit: string | null
}
 
/**
 * Context for help mode - computed when entering help
 */
export interface HelpContext {
  /** Index of the term being helped with */
  termIndex: number
  /** Current running total before this term */
  currentValue: number
  /** Target value after adding this term */
  targetValue: number
  /** The term being added */
  term: number
}
 
/**
 * Snapshot of an attempt that's animating out during transition
 */
export interface OutgoingAttempt {
  key: string
  problem: GeneratedProblem
  userAnswer: string
  result: 'correct' | 'incorrect'
  /** Part the outgoing problem belonged to (so the transition can render its
   *  own vertical/linear format, which may differ from the incoming part). */
  partIndex: number
}
 
/**
 * Context for the disambiguation phase - when user's input matches
 * an intermediate prefix sum but could also be the start of the final answer
 */
export interface DisambiguationContext {
  /** Index of the matched prefix sum */
  matchedPrefixIndex: number
  /** Term index to show help for if they want it */
  helpTermIndex: number
  /** When the disambiguation timer started */
  timerStartedAt: number
}
 
/**
 * Non-paused phases (used for resumePhase type)
 */
export type ActivePhase =
  | { phase: 'loading' }
  | { phase: 'inputting'; attempt: AttemptInput }
  | {
      phase: 'awaitingDisambiguation'
      attempt: AttemptInput
      disambiguationContext: DisambiguationContext
    }
  | { phase: 'helpMode'; attempt: AttemptInput; helpContext: HelpContext }
  | { phase: 'submitting'; attempt: AttemptInput }
  | {
      phase: 'showingFeedback'
      attempt: AttemptInput
      result: 'correct' | 'incorrect'
    }
  | {
      phase: 'transitioning'
      outgoing: OutgoingAttempt
      incoming: AttemptInput
    }
  | { phase: 'complete' }
 
/**
 * Discriminated union representing all possible interaction phases.
 * Each phase carries exactly the data needed for that phase.
 */
export type InteractionPhase =
  | ActivePhase
  // Session paused - remembers what phase to return to
  | {
      phase: 'paused'
      resumePhase: ActivePhase
      /** When the pause started (used to calculate pause duration on resume) */
      pauseStartedAt: number
    }
 
/** Threshold for correction count before requiring manual submit */
export const MANUAL_SUBMIT_THRESHOLD = 2
 
/** Time to wait before auto-triggering help in ambiguous cases (ms) */
export const AMBIGUOUS_HELP_DELAY_MS = 4000
 
// =============================================================================
// Helper Functions
// =============================================================================
 
/**
 * Gets the active (non-paused) phase, unwrapping if paused.
 */
export function getActivePhase(phase: InteractionPhase): ActivePhase {
  return phase.phase === 'paused' ? phase.resumePhase : phase
}
 
/**
 * Applies a transformation to the active phase, preserving paused wrapper if present.
 * If the transform returns null, the phase is unchanged.
 */
export function transformActivePhase(
  phase: InteractionPhase,
  transform: (active: ActivePhase) => ActivePhase | null
): InteractionPhase {
  if (phase.phase === 'paused') {
    const newResumePhase = transform(phase.resumePhase)
    if (newResumePhase === null) return phase
    return {
      phase: 'paused',
      resumePhase: newResumePhase,
      pauseStartedAt: phase.pauseStartedAt,
    }
  }
  const newPhase = transform(phase)
  return newPhase === null ? phase : newPhase
}
 
/**
 * Creates a fresh attempt input for a new problem
 */
export function createAttemptInput(
  problem: GeneratedProblem,
  slotIndex: number,
  partIndex: number
): AttemptInput {
  return {
    problem,
    slotIndex,
    partIndex,
    startTime: Date.now(),
    accumulatedPauseMs: 0,
    accumulatedHiddenMs: 0,
    userAnswer: '',
    correctionCount: 0,
    manualSubmitRequired: false,
    rejectedDigit: null,
  }
}
 
/**
 * Returns the attempt an active phase is currently carrying, or null for phases
 * that carry none (`loading` / `complete`).
 */
export function getActivePhaseAttempt(active: ActivePhase): AttemptInput | null {
  switch (active.phase) {
    case 'inputting':
    case 'awaitingDisambiguation':
    case 'helpMode':
    case 'submitting':
    case 'showingFeedback':
      return active.attempt
    case 'transitioning':
      return active.incoming
    case 'loading':
    case 'complete':
      return null
  }
}
 
/**
 * Adds `ms` to the active phase's current attempt `accumulatedPauseMs`, and —
 * when the span was hidden-tab time — its `accumulatedHiddenMs` audit counter.
 * No-ops for phases without an attempt or a non-positive span. Preserves the
 * paused wrapper is NOT this function's job: callers pass an already-unwrapped
 * {@link ActivePhase}.
 *
 * Extracted from `resume()` so the visibility layer folds hidden time through
 * the identical accounting the pause clock uses.
 */
export function addPauseToActivePhase(
  active: ActivePhase,
  ms: number,
  opts: { hidden: boolean } = { hidden: false }
): ActivePhase {
  if (ms <= 0) return active
  const bump = (attempt: AttemptInput): AttemptInput => ({
    ...attempt,
    accumulatedPauseMs: attempt.accumulatedPauseMs + ms,
    accumulatedHiddenMs: opts.hidden ? attempt.accumulatedHiddenMs + ms : attempt.accumulatedHiddenMs,
  })
  switch (active.phase) {
    case 'inputting':
    case 'awaitingDisambiguation':
    case 'helpMode':
    case 'submitting':
    case 'showingFeedback':
      return { ...active, attempt: bump(active.attempt) }
    case 'transitioning':
      // Fold into the incoming attempt (mirrors resume()'s existing behavior).
      return { ...active, incoming: bump(active.incoming) }
    case 'loading':
    case 'complete':
      return active
  }
}
 
/**
 * Folds a hidden span `[hiddenAt, now]` into the active phase's current attempt
 * as excluded (hidden) time. The span is clamped to the attempt's own lifetime
 * (`max(hiddenAt, attempt.startTime)`) so a hidden interval that straddled a
 * problem transition can never drive the new attempt's response time negative.
 */
export function foldHiddenSpanIntoActivePhase(
  active: ActivePhase,
  hiddenAt: number,
  now: number
): ActivePhase {
  const attempt = getActivePhaseAttempt(active)
  if (!attempt) return active
  const effectiveStart = Math.max(hiddenAt, attempt.startTime)
  return addPauseToActivePhase(active, now - effectiveStart, { hidden: true })
}
 
/**
 * Computes prefix sums for a problem's terms.
 * prefixSums[i] = sum of terms[0..i] (inclusive)
 */
export function computePrefixSums(terms: number[]): number[] {
  const sums: number[] = []
  let total = 0
  for (const term of terms) {
    total += term
    sums.push(total)
  }
  return sums
}
 
/**
 * Checks if a digit would be consistent with any prefix sum.
 *
 * Leading zeros are allowed as a disambiguation mechanism:
 * - Typing "0" when answer is empty is allowed (starts a multi-digit entry)
 * - Typing "03" signals intent to enter a 2+ digit number ending in 3
 * - The numeric value after stripping leading zeros must be consistent
 */
export function isDigitConsistent(
  currentAnswer: string,
  digit: string,
  prefixSums: number[]
): boolean {
  const newAnswer = currentAnswer + digit
 
  // Allow leading zeros as disambiguation (e.g., "0" or "03" for 3)
  // Strip leading zeros to get the numeric prefix we're building toward
  const strippedAnswer = newAnswer.replace(/^0+/, '') || '0'
 
  // If the result is just zeros, allow it (user is typing leading zeros)
  if (strippedAnswer === '0' && newAnswer.length > 0) {
    // Allow typing zeros as long as we haven't exceeded max answer length
    const maxLength = Math.max(...prefixSums.map((s) => s.toString().length))
    return newAnswer.length <= maxLength
  }
 
  const newAnswerNum = parseInt(strippedAnswer, 10)
  if (Number.isNaN(newAnswerNum)) return false
 
  for (const sum of prefixSums) {
    const sumStr = sum.toString()
    // Check if stripped answer is a prefix of any sum
    if (sumStr.startsWith(strippedAnswer)) {
      return true
    }
  }
  return false
}
 
/**
 * Result of checking for prefix sum matches
 */
export interface PrefixMatchResult {
  /** Index of matched prefix sum (-1 if none) */
  matchedIndex: number
  /** Whether this is an ambiguous match (could be digit-prefix of final answer) */
  isAmbiguous: boolean
  /** The term index to show help for (matchedIndex + 1, since we help with the NEXT term) */
  helpTermIndex: number
}
 
/**
 * Finds which prefix sum the user's answer matches, if any.
 * Also detects ambiguous cases where the input could be either:
 * 1. An intermediate prefix sum (user is stuck)
 * 2. The first digit(s) of a later prefix sum (user is still typing)
 *
 * Leading zeros disambiguate and REQUEST help:
 * - "3" alone is ambiguous (could be prefix sum 3 OR first digit of 33)
 * - "03" is unambiguous - user clearly wants help with prefix sum 3
 */
export function findMatchedPrefixIndex(
  userAnswer: string,
  prefixSums: number[]
): PrefixMatchResult {
  const noMatch: PrefixMatchResult = {
    matchedIndex: -1,
    isAmbiguous: false,
    helpTermIndex: -1,
  }
 
  if (!userAnswer) return noMatch
 
  // Leading zeros indicate user is explicitly requesting help for that prefix sum
  // "03" means "I want help with prefix sum 3" - this is NOT ambiguous
  const hasLeadingZero = userAnswer.startsWith('0') && userAnswer.length > 1
 
  const answerNum = parseInt(userAnswer, 10)
  if (Number.isNaN(answerNum)) return noMatch
 
  const finalAnswer = prefixSums[prefixSums.length - 1]
 
  // Check if this is the final answer
  if (answerNum === finalAnswer) {
    return {
      matchedIndex: prefixSums.length - 1,
      isAmbiguous: false,
      helpTermIndex: -1,
    }
  }
 
  // Check if user's input matches an intermediate prefix sum
  const matchedIndex = prefixSums.findIndex(
    (sum, i) => i < prefixSums.length - 1 && sum === answerNum
  )
 
  if (matchedIndex === -1) return noMatch
 
  // If they used leading zeros, they're explicitly requesting help - NOT ambiguous
  // "03" clearly means "help me with prefix sum 3"
  if (hasLeadingZero) {
    return {
      matchedIndex,
      isAmbiguous: false, // Leading zero removes ambiguity - they want help
      helpTermIndex: matchedIndex + 1,
    }
  }
 
  // Check if user's input could be a digit-prefix of ANY later prefix sum
  // For example, with prefix sums [2, 3, 33, 43, 44]:
  // - "3" matches prefix sum at index 1, but could also be first digit of 33 or 43
  // - So "3" is ambiguous
  const couldBeLaterPrefixPrefix = prefixSums.slice(matchedIndex + 1).some((laterSum) => {
    const laterSumStr = laterSum.toString()
    return laterSumStr.startsWith(userAnswer)
  })
 
  return {
    matchedIndex,
    isAmbiguous: couldBeLaterPrefixPrefix,
    helpTermIndex: matchedIndex + 1, // Help with the NEXT term after the matched sum
  }
}
 
/**
 * Computes help context for a given term index
 */
export function computeHelpContext(terms: number[], termIndex: number): HelpContext {
  const sums = computePrefixSums(terms)
  const currentValue = termIndex === 0 ? 0 : sums[termIndex - 1]
  const targetValue = sums[termIndex]
  const term = terms[termIndex]
  return { termIndex, currentValue, targetValue, term }
}
 
// =============================================================================
// Hook
// =============================================================================
 
export interface InitialProblemData {
  problem: GeneratedProblem
  slotIndex: number
  partIndex: number
}
 
/**
 * Active problem context with a stable key for change detection.
 * The key allows the hook to detect when the problem truly changes,
 * not just when references change.
 */
export interface ActiveProblem {
  problem: GeneratedProblem
  slotIndex: number
  partIndex: number
  /** Stable identifier for this problem instance - changes when the problem changes */
  key: string
}
 
export interface UseInteractionPhaseOptions {
  /** Initial problem to hydrate with (for SSR) */
  initialProblem?: InitialProblemData
  /**
   * Active problem context - derived from redoState + session plan.
   * When the key changes, the hook automatically loads the new problem.
   * This is the single source of truth for which problem is being worked on.
   */
  activeProblem?: ActiveProblem | null
  /** Called when auto-submit threshold is exceeded */
  onManualSubmitRequired?: () => void
  /**
   * When true (LINEAR parts), the abacus is put away entirely: never reject a
   * digit, never enter awaitingDisambiguation, and never enter help mode. The
   * student just types the final answer to the number sentence.
   */
  disableAbacusScaffolding?: boolean
}
 
export interface UseInteractionPhaseReturn {
  // Current phase
  phase: InteractionPhase
 
  // Extracted state from phase (single source of truth)
  /** Current attempt being worked on (null in loading/complete phases) */
  attempt: AttemptInput | null
  /** Help context when in helpMode (null otherwise) */
  helpContext: HelpContext | null
  /** Outgoing attempt during transition animation (null otherwise) */
  outgoingAttempt: OutgoingAttempt | null
 
  // Derived predicates for UI
  /** Can we accept keyboard/keypad input? */
  canAcceptInput: boolean
  /** Should the problem display show as completed? */
  showAsCompleted: boolean
  /** Should the help overlay be shown? */
  showHelpOverlay: boolean
  /** Should the input area (keypad/submit) be shown? */
  showInputArea: boolean
  /** Should the feedback message be shown? */
  showFeedback: boolean
  /** Is the input box focused? */
  inputIsFocused: boolean
  /** Are we currently in the transitioning phase? */
  isTransitioning: boolean
  /** Are we currently paused? */
  isPaused: boolean
  /** Are we currently submitting? */
  isSubmitting: boolean
 
  // Computed values (only valid when attempt exists)
  /** Prefix sums for current problem */
  prefixSums: number[]
  /** Full prefix match result with ambiguity info */
  prefixMatch: PrefixMatchResult
  /** Matched prefix index (-1 if none) - shorthand for prefixMatch.matchedIndex */
  matchedPrefixIndex: number
  /** Can the submit button be pressed? */
  canSubmit: boolean
  /** Should auto-submit trigger? */
  shouldAutoSubmit: boolean
 
  // Ambiguous prefix state
  /** Term index to show "need help?" prompt for (-1 if not in awaitingDisambiguation phase) */
  ambiguousHelpTermIndex: number
 
  // Actions
  /** Load a new problem (loading → inputting) */
  loadProblem: (problem: GeneratedProblem, slotIndex: number, partIndex: number) => void
  /** Handle digit input */
  handleDigit: (digit: string) => void
  /** Handle backspace */
  handleBackspace: () => void
  /** Enter help mode (inputting → helpMode) */
  enterHelpMode: (termIndex: number) => void
  /** Exit help mode (helpMode → inputting) */
  exitHelpMode: () => void
  /** Clear the current answer (used after help overlay transition completes) */
  clearAnswer: () => void
  /** Set the answer to a specific value (used when showing target reached value) */
  setAnswer: (value: string) => void
  /** Submit answer (inputting/helpMode → submitting) */
  startSubmit: () => void
  /** Handle submit result (submitting → showingFeedback) */
  completeSubmit: (result: 'correct' | 'incorrect') => void
  /** Start transition to next problem (showingFeedback → transitioning) */
  startTransition: (
    nextProblem: GeneratedProblem,
    nextSlotIndex: number,
    nextPartIndex?: number
  ) => void
  /** Complete transition (transitioning → inputting) */
  completeTransition: () => void
  /** Clear to loading state */
  clearToLoading: () => void
  /** Mark session as complete */
  markComplete: () => void
  /** Pause session (* → paused) */
  pause: () => void
  /** Resume session (paused → resumePhase) */
  resume: () => void
  /** Is the session complete? */
  isComplete: boolean
}
 
export function useInteractionPhase(
  options: UseInteractionPhaseOptions = {}
): UseInteractionPhaseReturn {
  const { initialProblem, activeProblem, onManualSubmitRequired, disableAbacusScaffolding } =
    options
 
  // Initialize state with problem if provided (for SSR hydration)
  const [phase, setPhase] = useState<InteractionPhase>(() => {
    if (initialProblem) {
      const attempt = createAttemptInput(
        initialProblem.problem,
        initialProblem.slotIndex,
        initialProblem.partIndex
      )
      return { phase: 'inputting', attempt }
    }
    return { phase: 'loading' }
  })
 
  // Live mirror of `phase` for event handlers that must read the current phase
  // without re-subscribing (the visibility layer). Set during render — safe.
  const phaseRef = useRef(phase)
  phaseRef.current = phase
 
  // Live mirror of the abacus-scaffolding-disabled flag (LINEAR parts) so the
  // memoized handleDigit/enterHelpMode callbacks read the current value without
  // being re-created when it toggles. Set during render — safe.
  const disableScaffoldingRef = useRef(disableAbacusScaffolding)
  disableScaffoldingRef.current = disableAbacusScaffolding
 
  // Visibility layer (#156): when the tab is hidden/backgrounded we record the
  // instant here and fold the elapsed span into the current attempt on return,
  // the identical subtraction resume() performs. `null` = not currently hidden.
  // The pause clock and this hidden clock form a disjoint union (see pause/
  // resume + the visibility effect below) so time is never double-counted.
  const hiddenAtRef = useRef<number | null>(null)
 
  // ==========================================================================
  // Derived State
  // ==========================================================================
 
  // Extract attempt from phase if available
  const attempt = useMemo((): AttemptInput | null => {
    switch (phase.phase) {
      case 'inputting':
      case 'awaitingDisambiguation':
      case 'helpMode':
      case 'submitting':
      case 'showingFeedback':
        return phase.attempt
      case 'transitioning':
        return phase.incoming
      case 'paused': {
        // Recurse into resumePhase
        const inner = phase.resumePhase
        if (
          inner.phase === 'inputting' ||
          inner.phase === 'awaitingDisambiguation' ||
          inner.phase === 'helpMode' ||
          inner.phase === 'submitting' ||
          inner.phase === 'showingFeedback'
        ) {
          return inner.attempt
        }
        if (inner.phase === 'transitioning') {
          return inner.incoming
        }
        return null
      }
      default:
        return null
    }
  }, [phase])
 
  const prefixSums = useMemo(() => {
    if (!attempt) return []
    return computePrefixSums(attempt.problem.terms)
  }, [attempt])
 
  const prefixMatch = useMemo((): PrefixMatchResult => {
    if (!attempt) return { matchedIndex: -1, isAmbiguous: false, helpTermIndex: -1 }
    return findMatchedPrefixIndex(attempt.userAnswer, prefixSums)
  }, [attempt, prefixSums])
 
  // Convenience shorthand - most callers only need the index
  const matchedPrefixIndex = prefixMatch.matchedIndex
 
  // ==========================================================================
  // Disambiguation Timer (managed via phase state)
  // ==========================================================================
 
  // Timer ref for the disambiguation timeout
  const disambiguationTimerRef = useRef<NodeJS.Timeout | null>(null)
 
  // Manage disambiguation timer based on phase
  useEffect(() => {
    // Clear any existing timer
    if (disambiguationTimerRef.current) {
      clearTimeout(disambiguationTimerRef.current)
      disambiguationTimerRef.current = null
    }
 
    // LINEAR parts never enter awaitingDisambiguation (see handleDigit); with the
    // abacus scaffolding disabled there is no bead-help to schedule. Defensive.
    if (disableAbacusScaffolding) return
 
    // Only run timer when in awaitingDisambiguation phase
    if (phase.phase !== 'awaitingDisambiguation') return
 
    const ctx = phase.disambiguationContext
    const elapsed = Date.now() - ctx.timerStartedAt
 
    if (elapsed >= AMBIGUOUS_HELP_DELAY_MS) {
      // Timer already elapsed - transition to help mode immediately
      // Keep userAnswer during transition so it shows in answer boxes while fading out
      const helpContext = computeHelpContext(phase.attempt.problem.terms, ctx.helpTermIndex)
      setPhase({
        phase: 'helpMode',
        attempt: { ...phase.attempt, userAnswer: '' },
        helpContext,
      })
    } else {
      // Set timer for remaining time
      const remaining = AMBIGUOUS_HELP_DELAY_MS - elapsed
      disambiguationTimerRef.current = setTimeout(() => {
        setPhase((prev) => {
          if (prev.phase !== 'awaitingDisambiguation') return prev
          const helpContext = computeHelpContext(
            prev.attempt.problem.terms,
            prev.disambiguationContext.helpTermIndex
          )
          return {
            phase: 'helpMode',
            attempt: { ...prev.attempt, userAnswer: '' },
            helpContext,
          }
        })
      }, remaining)
    }
 
    return () => {
      if (disambiguationTimerRef.current) {
        clearTimeout(disambiguationTimerRef.current)
      }
    }
  }, [phase, disableAbacusScaffolding])
 
  // Derive which term to show "need help?" prompt for from the phase
  // Returns -1 when not in awaitingDisambiguation phase
  const ambiguousHelpTermIndex = useMemo(() => {
    if (phase.phase !== 'awaitingDisambiguation') return -1
    return phase.disambiguationContext.helpTermIndex
  }, [phase])
 
  const canSubmit = useMemo(() => {
    if (!attempt || !attempt.userAnswer) return false
    const answerNum = parseInt(attempt.userAnswer, 10)
    return !Number.isNaN(answerNum)
  }, [attempt])
 
  const shouldAutoSubmit = useMemo(() => {
    // Don't auto-submit in awaitingDisambiguation - the input might be a prefix sum
    if (phase.phase !== 'inputting' && phase.phase !== 'helpMode') return false
    if (!attempt || !attempt.userAnswer) return false
    if (attempt.correctionCount > MANUAL_SUBMIT_THRESHOLD) return false
 
    const answerNum = parseInt(attempt.userAnswer, 10)
    if (Number.isNaN(answerNum)) return false
 
    return answerNum === attempt.problem.answer
  }, [phase.phase, attempt])
 
  // UI predicates
  const canAcceptInput =
    phase.phase === 'inputting' ||
    phase.phase === 'awaitingDisambiguation' ||
    phase.phase === 'helpMode'
 
  const showAsCompleted = phase.phase === 'showingFeedback'
 
  const showHelpOverlay = phase.phase === 'helpMode'
 
  const showInputArea =
    phase.phase === 'inputting' ||
    phase.phase === 'awaitingDisambiguation' ||
    phase.phase === 'helpMode' ||
    phase.phase === 'submitting'
 
  const showFeedback = phase.phase === 'showingFeedback' && phase.result === 'incorrect'
 
  const inputIsFocused =
    phase.phase === 'inputting' ||
    phase.phase === 'awaitingDisambiguation' ||
    phase.phase === 'helpMode'
 
  const isTransitioning = phase.phase === 'transitioning'
 
  const isPaused = phase.phase === 'paused'
 
  const isSubmitting = phase.phase === 'submitting'
 
  // Extract helpContext from phase
  const helpContext = useMemo((): HelpContext | null => {
    if (phase.phase === 'helpMode') {
      return phase.helpContext
    }
    // Also check paused phase
    if (phase.phase === 'paused' && phase.resumePhase.phase === 'helpMode') {
      return phase.resumePhase.helpContext
    }
    return null
  }, [phase])
 
  // Extract outgoingAttempt from phase (only during transitions)
  const outgoingAttempt = useMemo((): OutgoingAttempt | null => {
    if (phase.phase === 'transitioning') {
      return phase.outgoing
    }
    return null
  }, [phase])
 
  // ==========================================================================
  // Actions
  // ==========================================================================
 
  const loadProblem = useCallback(
    (problem: GeneratedProblem, slotIndex: number, partIndex: number) => {
      const newAttempt = createAttemptInput(problem, slotIndex, partIndex)
      setPhase({ phase: 'inputting', attempt: newAttempt })
    },
    []
  )
 
  // ==========================================================================
  // React to activeProblem changes (single source of truth)
  // ==========================================================================
  // This effect handles two cases:
  // 1. activeProblem.key changes (redo mode, direct navigation, session plan advances)
  // 2. Phase becomes 'loading' (need to reload current problem after incorrect answer or part transition)
  const prevActiveProblemKeyRef = useRef<string | null>(null)
  const hasMountedRef = useRef(false)
 
  useEffect(() => {
    // Skip on initial mount - let initialProblem handle hydration
    if (!hasMountedRef.current) {
      hasMountedRef.current = true
      // Initialize the ref with current key
      prevActiveProblemKeyRef.current = activeProblem?.key ?? null
      return
    }
 
    // If no active problem, nothing to do
    if (!activeProblem) {
      prevActiveProblemKeyRef.current = null
      return
    }

    const prevKey = prevActiveProblemKeyRef.current
    const currentKey = activeProblem.key
    const keyChanged = prevKey !== currentKey

    // Case 1: Phase is 'loading' - need to load the problem
    // This happens after incorrect answers or when returning from part transitions
    if (phase.phase === 'loading') {
      const newAttempt = createAttemptInput(
        activeProblem.problem,
        activeProblem.slotIndex,
        activeProblem.partIndex
      )
      setPhase({ phase: 'inputting', attempt: newAttempt })
      prevActiveProblemKeyRef.current = currentKey
      return
    }

    // Case 2: Key changed - handle redo mode or session advancement
    if (keyChanged) {
      // CRITICAL: Don't interrupt normal progression flow
      // If we're in showingFeedback, submitting, or transitioning, the normal flow
      // (startTransition → completeTransition) handles advancing to the next problem.
      const isInProgressionFlow =
        phase.phase === 'showingFeedback' ||
        phase.phase === 'submitting' ||
        phase.phase === 'transitioning'

      if (isInProgressionFlow) {
        // Still update the ref so we track the change
        prevActiveProblemKeyRef.current = currentKey
        return
      }

      // Key changed and we're not in progression flow - load the new problem immediately
      const newAttempt = createAttemptInput(
        activeProblem.problem,
        activeProblem.slotIndex,
        activeProblem.partIndex
      )
      setPhase({ phase: 'inputting', attempt: newAttempt })
      prevActiveProblemKeyRef.current = currentKey
    }
  }, [activeProblem, phase.phase])
 
  const handleDigit = useCallback(
    (digit: string) => {
      setPhase((prev) => {
        // Accept input in inputting, awaitingDisambiguation, or helpMode
        if (
          prev.phase !== 'inputting' &&
          prev.phase !== 'awaitingDisambiguation' &&
          prev.phase !== 'helpMode'
        ) {
          return prev
        }
 
        // If in help mode, exit help mode and start fresh with the new digit
        // We reset to an empty answer and fall through to the normal digit processing
        // so that ambiguity checks (awaitingDisambiguation) still apply
        if (prev.phase === 'helpMode') {
          prev = {
            phase: 'inputting',
            attempt: { ...prev.attempt, userAnswer: '', rejectedDigit: null },
          }
        }
 
        const attempt = prev.attempt
        const sums = computePrefixSums(attempt.problem.terms)
 
        // Once manual submit is required — or during LINEAR parts, where the abacus
        // prefix-sum scaffolding is disabled — accept any digit without validation
        // (never reject, never enter awaitingDisambiguation/help mode).
        if (attempt.manualSubmitRequired || disableScaffoldingRef.current) {
          const updatedAttempt = {
            ...attempt,
            userAnswer: attempt.userAnswer + digit,
            rejectedDigit: null,
          }
          return { phase: 'inputting', attempt: updatedAttempt }
        }
 
        if (isDigitConsistent(attempt.userAnswer, digit, sums)) {
          const updatedAttempt = {
            ...attempt,
            userAnswer: attempt.userAnswer + digit,
            rejectedDigit: null,
          }
 
          // Check if the new answer creates an ambiguous prefix match
          const newPrefixMatch = findMatchedPrefixIndex(updatedAttempt.userAnswer, sums)
 
          if (newPrefixMatch.isAmbiguous && newPrefixMatch.helpTermIndex >= 0) {
            // Ambiguous match - transition to awaitingDisambiguation
            return {
              phase: 'awaitingDisambiguation',
              attempt: updatedAttempt,
              disambiguationContext: {
                matchedPrefixIndex: newPrefixMatch.matchedIndex,
                helpTermIndex: newPrefixMatch.helpTermIndex,
                timerStartedAt: Date.now(),
              },
            }
          } else if (
            !newPrefixMatch.isAmbiguous &&
            newPrefixMatch.matchedIndex >= 0 &&
            newPrefixMatch.helpTermIndex >= 0
          ) {
            // Unambiguous intermediate prefix match (e.g., "03" for prefix sum 3)
            // Immediately enter help mode
            // Keep userAnswer during transition so it shows in answer boxes while fading out
            const helpContext = computeHelpContext(
              attempt.problem.terms,
              newPrefixMatch.helpTermIndex
            )
            return {
              phase: 'helpMode',
              attempt: { ...updatedAttempt, userAnswer: '' },
              helpContext,
            }
          } else {
            // No special prefix match - stay in inputting (or return to it from awaitingDisambiguation)
            return { phase: 'inputting', attempt: updatedAttempt }
          }
        } else {
          // Reject the digit
          const newCorrectionCount = attempt.correctionCount + 1
          const nowRequiresManualSubmit =
            newCorrectionCount > MANUAL_SUBMIT_THRESHOLD && !attempt.manualSubmitRequired
 
          if (nowRequiresManualSubmit) {
            setTimeout(() => onManualSubmitRequired?.(), 0)
          }
 
          const updatedAttempt = {
            ...attempt,
            rejectedDigit: digit,
            correctionCount: newCorrectionCount,
            manualSubmitRequired: attempt.manualSubmitRequired || nowRequiresManualSubmit,
          }
 
          // Keep the same phase type but update attempt
          if (prev.phase === 'awaitingDisambiguation') {
            return { ...prev, attempt: updatedAttempt }
          }
          return { ...prev, attempt: updatedAttempt }
        }
      })
 
      // Clear rejected digit after animation
      setTimeout(() => {
        setPhase((prev) => {
          if (
            prev.phase !== 'inputting' &&
            prev.phase !== 'awaitingDisambiguation' &&
            prev.phase !== 'helpMode'
          ) {
            return prev
          }
          return { ...prev, attempt: { ...prev.attempt, rejectedDigit: null } }
        })
      }, 300)
    },
    [onManualSubmitRequired]
  )
 
  const handleBackspace = useCallback(() => {
    setPhase((prev) => {
      if (
        prev.phase !== 'inputting' &&
        prev.phase !== 'awaitingDisambiguation' &&
        prev.phase !== 'helpMode'
      ) {
        return prev
      }
 
      const attempt = prev.attempt
      if (attempt.userAnswer.length === 0) return prev
 
      const newCorrectionCount = attempt.correctionCount + 1
      const nowRequiresManualSubmit =
        newCorrectionCount > MANUAL_SUBMIT_THRESHOLD && !attempt.manualSubmitRequired
 
      if (nowRequiresManualSubmit) {
        setTimeout(() => onManualSubmitRequired?.(), 0)
      }
 
      const updatedAttempt = {
        ...attempt,
        userAnswer: attempt.userAnswer.slice(0, -1),
        correctionCount: newCorrectionCount,
        manualSubmitRequired: attempt.manualSubmitRequired || nowRequiresManualSubmit,
      }
 
      // After backspace, always return to inputting phase (no longer ambiguous)
      return { phase: 'inputting', attempt: updatedAttempt }
    })
  }, [onManualSubmitRequired])
 
  const enterHelpMode = useCallback((termIndex: number) => {
    // LINEAR parts have the abacus put away — bead-decomposition help must never
    // be entered. No-op keeps the current phase and typed answer intact.
    if (disableScaffoldingRef.current) return
    setPhase((prev) => {
      // Allow entering help mode from inputting, awaitingDisambiguation, or helpMode (to navigate to a different term)
      if (
        prev.phase !== 'inputting' &&
        prev.phase !== 'awaitingDisambiguation' &&
        prev.phase !== 'helpMode'
      ) {
        return prev
      }
 
      // Keep userAnswer during transition so it shows in answer boxes while fading out
      const helpContext = computeHelpContext(prev.attempt.problem.terms, termIndex)
      return {
        phase: 'helpMode',
        attempt: { ...prev.attempt, userAnswer: '' },
        helpContext,
      }
    })
  }, [])
 
  const exitHelpMode = useCallback(() => {
    setPhase((prev) => {
      if (prev.phase === 'helpMode') {
        const updatedAttempt = { ...prev.attempt, userAnswer: '' }
        return { phase: 'inputting', attempt: updatedAttempt }
      }
      if (prev.phase === 'inputting') {
        const updatedAttempt = { ...prev.attempt, userAnswer: '' }
        return { phase: 'inputting', attempt: updatedAttempt }
      }
      return prev
    })
  }, [])
 
  const clearAnswer = useCallback(() => {
    setPhase((prev) => {
      if (prev.phase !== 'helpMode') return prev
      const updatedAttempt = { ...prev.attempt, userAnswer: '' }
      return {
        phase: 'helpMode',
        attempt: updatedAttempt,
        helpContext: prev.helpContext,
      }
    })
  }, [])
 
  const setAnswer = useCallback((value: string) => {
    setPhase((prev) => {
      if (prev.phase !== 'helpMode' && prev.phase !== 'inputting') return prev
      const updatedAttempt = { ...prev.attempt, userAnswer: value }
      if (prev.phase === 'helpMode') {
        return {
          phase: 'helpMode',
          attempt: updatedAttempt,
          helpContext: prev.helpContext,
        }
      }
      return { phase: 'inputting', attempt: updatedAttempt }
    })
  }, [])
 
  const startSubmit = useCallback(() => {
    setPhase((prev) => {
      // Allow submitting from inputting, awaitingDisambiguation, or helpMode
      if (
        prev.phase !== 'inputting' &&
        prev.phase !== 'awaitingDisambiguation' &&
        prev.phase !== 'helpMode'
      ) {
        return prev
      }
      return { phase: 'submitting', attempt: prev.attempt }
    })
  }, [])
 
  const completeSubmit = useCallback((result: 'correct' | 'incorrect') => {
    setPhase((prev) =>
      transformActivePhase(prev, (active) => {
        if (active.phase !== 'submitting') return null
        return { phase: 'showingFeedback', attempt: active.attempt, result }
      })
    )
  }, [])
 
  const startTransition = useCallback(
    (nextProblem: GeneratedProblem, nextSlotIndex: number, nextPartIndex?: number) => {
      setPhase((prev) => {
        if (prev.phase !== 'showingFeedback') return prev
 
        const outgoing: OutgoingAttempt = {
          key: `${prev.attempt.partIndex}-${prev.attempt.slotIndex}`,
          problem: prev.attempt.problem,
          userAnswer: prev.attempt.userAnswer,
          result: prev.result,
          partIndex: prev.attempt.partIndex,
        }
 
        const incomingPartIndex = nextPartIndex ?? prev.attempt.partIndex
        const incoming = createAttemptInput(nextProblem, nextSlotIndex, incomingPartIndex)
 
        return { phase: 'transitioning', outgoing, incoming }
      })
    },
    []
  )
 
  const completeTransition = useCallback(() => {
    setPhase((prev) =>
      transformActivePhase(prev, (active) => {
        if (active.phase !== 'transitioning') return null
        return { phase: 'inputting', attempt: active.incoming }
      })
    )
  }, [])
 
  const clearToLoading = useCallback(() => {
    setPhase({ phase: 'loading' })
  }, [])
 
  const markComplete = useCallback(() => {
    setPhase({ phase: 'complete' })
  }, [])
 
  const pause = useCallback(() => {
    // Capture the hidden clock BEFORE the (pure) updater so StrictMode's
    // double-invocation can't fold the same span twice.
    const now = Date.now()
    const hiddenAt = hiddenAtRef.current
    setPhase((prev) => {
      if (prev.phase === 'paused' || prev.phase === 'loading' || prev.phase === 'complete')
        return prev
      // Disjoint-union rule (b): a hidden span in flight is folded into the
      // attempt FIRST (clamped to its lifetime); from here the pause clock owns
      // elapsed time, so the two never double-count.
      const base = hiddenAt != null ? foldHiddenSpanIntoActivePhase(prev, hiddenAt, now) : prev
      return { phase: 'paused', resumePhase: base, pauseStartedAt: now }
    })
    // The hidden span (if any) has been handed off to the pause clock.
    hiddenAtRef.current = null
  }, [])
 
  const resume = useCallback(() => {
    const now = Date.now()
    // Disjoint-union rule (c): if the tab is STILL hidden (teacher remote-resume
    // while backgrounded), re-arm the hidden clock so the still-hidden span
    // keeps being excluded when the child actually returns.
    const stillHidden = typeof document !== 'undefined' && document.visibilityState === 'hidden'
    setPhase((prev) => {
      if (prev.phase !== 'paused') return prev
      // Fold the pause span into the attempt via the shared accounting.
      return addPauseToActivePhase(prev.resumePhase, now - prev.pauseStartedAt, { hidden: false })
    })
    hiddenAtRef.current = stillHidden ? now : null
  }, [])
 
  // ==========================================================================
  // Visibility layer (#156): fold hidden-tab time out of the response time
  // ==========================================================================
  //
  // Mount-only. On hidden we arm `hiddenAtRef`; on return we fold the elapsed
  // span into the current attempt (silently — no phase change, so no pause
  // modal flashes). `visibilitychange` is primary; `pagehide` / persisted
  // `pageshow` are idempotent belt-and-suspenders for iOS Safari reliability.
  useEffect(() => {
    if (typeof document === 'undefined') return
 
    const arm = () => {
      // Rule (a): arm only when not already armed (idempotent under duplicate
      // pagehide + visibilitychange) and not paused (the pause clock owns it).
      if (hiddenAtRef.current != null) return
      if (phaseRef.current.phase === 'paused') return
      hiddenAtRef.current = Date.now()
    }
 
    const fold = () => {
      const hiddenAt = hiddenAtRef.current
      if (hiddenAt == null) return
      hiddenAtRef.current = null
      const now = Date.now()
      setPhase((prev) => {
        // Rule (d): visible while paused → no-op (pause clock owns the interval).
        if (prev.phase === 'paused') return prev
        return foldHiddenSpanIntoActivePhase(prev, hiddenAt, now)
      })
    }
 
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') arm()
      else fold()
    }
    const handlePageHide = () => arm()
    const handlePageShow = (event: PageTransitionEvent) => {
      if (event.persisted) fold()
    }
 
    document.addEventListener('visibilitychange', handleVisibilityChange)
    window.addEventListener('pagehide', handlePageHide)
    window.addEventListener('pageshow', handlePageShow)
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange)
      window.removeEventListener('pagehide', handlePageHide)
      window.removeEventListener('pageshow', handlePageShow)
    }
  }, [])
 
  // Is the session complete?
  const isComplete = phase.phase === 'complete'
 
  return {
    phase,
    attempt,
    helpContext,
    outgoingAttempt,
    canAcceptInput,
    showAsCompleted,
    showHelpOverlay,
    showInputArea,
    showFeedback,
    inputIsFocused,
    isTransitioning,
    isPaused,
    isSubmitting,
    prefixSums,
    prefixMatch,
    matchedPrefixIndex,
    canSubmit,
    shouldAutoSubmit,
    ambiguousHelpTermIndex,
    loadProblem,
    handleDigit,
    handleBackspace,
    enterHelpMode,
    exitHelpMode,
    clearAnswer,
    setAnswer,
    startSubmit,
    completeSubmit,
    startTransition,
    completeTransition,
    clearToLoading,
    markComplete,
    pause,
    resume,
    isComplete,
  }
}