All files / web/src/components/practice StartPracticeModalContext.tsx

93.85% Statements 886/944
86.15% Branches 168/195
100% Functions 2/2
93.85% Lines 886/944

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 9451x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 437x 437x 4x 4x 431x 431x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 179x 179x 179x 179x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 130x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 7x 7x 7x 4x 4x 6x 6x 1x 1x 7x 332x 332x 332x 332x 4x 4x 4x 4x 4x 3x 4x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 6x 6x 6x 5x 6x 6x 1x 6x 332x 332x 332x 332x 11x 11x 11x 11x 11x 10x 11x 332x 332x 332x 332x 184x 184x 184x 184x 184x 184x 184x 184x 184x 184x 184x 184x 332x 332x 332x 332x 169x 169x 169x 169x 332x 332x 332x 330x 330x 330x 330x 330x 330x 990x 670x 990x 990x 990x 990x 330x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 253x 121x 332x 332x 332x 332x 332x 332x 332x 223x 64x 223x 332x 332x 332x 332x 222x 40x 40x 92x 17x 17x 17x 17x 17x 23x 23x 92x 222x 222x 222x 222x 222x 332x 332x 332x 332x 332x 332x 332x 332x 332x 38x 38x 38x 38x 38x 332x 332x 332x 332x 169x 17x 17x 17x 17x 332x 332x 332x 332x 272x 272x 84x 81x 30x 272x     332x 332x 332x 332x 223x 48x 48x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 320x 169x 169x 169x 169x 151x 151x 150x 150x 315x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 179x 179x 179x 179x 179x 179x 179x 332x 332x 332x 189x 189x     189x 189x 189x 189x 189x 189x 189x 189x 189x 189x   189x 189x 186x 186x 186x 186x 186x 186x 3x 189x 189x 14x 14x 14x 14x 14x 14x 175x 189x 332x 332x 332x 189x 332x 332x 332x 179x 179x 179x 14x 14x 14x 179x 165x 179x 179x 179x 332x 332x 332x 179x 332x 332x 332x 332x 332x 332x 169x 3x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 326x 326x 326x 326x 332x 332x 169x     169x 169x     169x 169x 169x 332x 332x 332x 332x 330x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 5x 5x 5x 5x 5x 332x 332x 332x 332x 332x 325x 4x                                     332x 332x 332x 332x 173x     332x 332x 332x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x           4x 4x 4x 4x 4x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 5x 2x 2x 4x 4x 4x 4x 4x 5x                                           5x       332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x 332x  
'use client'
 
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
  type ReactNode,
} from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation'
import type {
  SessionPlan,
  GameBreakSelectionMode,
  PracticeBreakGameConfig,
} from '@/db/schema/session-plans'
import { DEFAULT_PLAN_CONFIG, DEFAULT_GAME_BREAK_SETTINGS } from '@/db/schema/session-plan-helpers'
import type { PlayerSessionPreferencesConfig } from '@/db/schema/player-session-preferences'
import { getPracticeApprovedGames } from '@/lib/arcade/practice-approved-games'
import type { PracticeBreakConfig } from '@/lib/arcade/manifest-schema'
import {
  ActiveSessionExistsClientError,
  NoSkillsEnabledClientError,
  SessionLimitReachedError,
  sessionPlanKeys,
  useAbandonSession,
  useApproveSessionPlan,
  useGenerateSessionPlan,
  useStartSessionPlan,
} from '@/hooks/useSessionPlan'
import type { SessionMode } from '@/lib/curriculum/session-mode'
import { computeTermCountRange } from '@/lib/curriculum/config/term-count-scaling'
import {
  convertSecondsPerProblemToSpt,
  estimateSessionProblemCount,
  TIME_ESTIMATION_DEFAULTS,
} from '@/lib/curriculum/time-estimation'
import {
  getSkillTutorialConfig,
  type SkillTutorialConfig,
} from '@/lib/curriculum/skill-tutorial-config'
 
// Problem length preference type and comfort adjustments
export type ProblemLengthPreference = 'shorter' | 'recommended' | 'longer'
 
export const COMFORT_ADJUSTMENTS: Record<ProblemLengthPreference, number> = {
  shorter: -0.3,
  recommended: 0,
  longer: 0.2,
}
 
// Part types configuration
export const PART_TYPES = [
  { type: 'abacus' as const, emoji: '🧮', label: 'Abacus', defaultWeight: 2 },
  {
    type: 'visualization' as const,
    emoji: '🧠',
    label: 'Visualize',
    defaultWeight: 1,
  },
  { type: 'linear' as const, emoji: '💭', label: 'Linear', defaultWeight: 0 },
] as const
 
// Purpose types configuration
export const PURPOSE_TYPES = [
  { type: 'focus' as const, emoji: '🎯', label: 'Focus', defaultWeight: 3 },
  { type: 'reinforce' as const, emoji: '💪', label: 'Reinforce', defaultWeight: 1 },
  { type: 'review' as const, emoji: '🔄', label: 'Review', defaultWeight: 1 },
  { type: 'challenge' as const, emoji: '⭐', label: 'Challenge', defaultWeight: 1 },
] as const
 
export type PurposeWeightType = 'focus' | 'reinforce' | 'review' | 'challenge'
export type PurposeWeights = Record<PurposeWeightType, number>
 
export type EnabledParts = {
  abacus: boolean
  visualization: boolean
  linear: boolean
}
 
export type PartType = 'abacus' | 'visualization' | 'linear'
 
export type PartWeights = {
  abacus: number
  visualization: number
  linear: number
}
 
// Game info interface for the context (used for both real games and mock overrides)
export interface GameInfo {
  manifest: {
    name: string
    displayName: string
    shortName?: string
    icon: string
    /** Practice break configuration (presets, locked fields, etc.) */
    practiceBreakConfig?: PracticeBreakConfig
  }
}
 
/** Difficulty preset type for game break configuration */
export type GameBreakDifficultyPreset = 'easy' | 'medium' | 'hard' | null
 
interface StartPracticeModalContextValue {
  // Read-only props from parent
  studentId: string
  studentName: string
  focusDescription: string
  sessionMode: SessionMode
  existingPlan: SessionPlan | null
 
  // Session config (state + setters)
  durationMinutes: number
  setDurationMinutes: (min: number) => void
  enabledParts: EnabledParts
  partWeights: PartWeights
  /** Tap on segment: 0→1, 1→2, 2→1 (never disables) */
  cyclePartWeight: (partType: keyof PartWeights) => void
  /** Explicit disable via × button (blocked if last active) */
  disablePart: (partType: keyof PartWeights) => void
  problemLengthPreference: ProblemLengthPreference
  setProblemLengthPreference: (pref: ProblemLengthPreference) => void
  /** Comfort level from the session mode API (0-1) */
  comfortLevel: number
  /** Per-mode comfort levels (e.g. { abacus: 0.72, visualization: 0.45, linear: 0.68 }) */
  comfortByMode: Record<string, number>
 
  // Purpose weight config
  purposeWeights: PurposeWeights
  /** Tap on segment: 0→1, 1↔2 (no-op if sole active) */
  cyclePurposeWeight: (purposeType: PurposeWeightType) => void
  /** Explicit disable via × button (blocked if last active) */
  disablePurpose: (purposeType: PurposeWeightType) => void
  /** Normalized 0-1 weights for API call */
  purposeTimeWeights: Record<PurposeWeightType, number>
  /** Whether to shuffle purposes within each part (true = interleaved, false = grouped in order) */
  shufflePurposes: boolean
  setShufflePurposes: (shuffle: boolean) => void
 
  // Game break config (state + setters)
  gameBreakEnabled: boolean
  setGameBreakEnabled: (enabled: boolean) => void
  gameBreakMinutes: number
  setGameBreakMinutes: (mins: number) => void
  gameBreakSelectionMode: GameBreakSelectionMode
  setGameBreakSelectionMode: (mode: GameBreakSelectionMode) => void
  gameBreakSelectedGame: string | 'random' | null
  setGameBreakSelectedGame: (game: string | 'random' | null) => void
  // Per-game config (state + setters)
  gameBreakDifficultyPreset: GameBreakDifficultyPreset
  setGameBreakDifficultyPreset: (preset: GameBreakDifficultyPreset) => void
  gameBreakCustomConfig: Record<string, unknown>
  setGameBreakCustomConfig: (config: Record<string, unknown>) => void
  gameBreakShowCustomize: boolean
  setGameBreakShowCustomize: (show: boolean) => void
  /** The selected game's practice break config (null if random or no game selected) */
  selectedGamePracticeConfig: PracticeBreakConfig | null
  /** Resolved game config based on preset or custom settings */
  resolvedGameConfig: Record<string, unknown>
 
  // Derived values
  secondsPerTerm: number
  avgTermsPerProblem: number
  problemsPerType: { abacus: number; visualization: number; linear: number }
  estimatedProblems: number
  enabledPartCount: number
  showGameBreakSettings: boolean
  practiceApprovedGames: GameInfo[]
  /** Games enabled for this player (filtered from practiceApprovedGames by per-player allowlist) */
  playerEnabledGames: GameInfo[]
  /** True when only one game is available for practice breaks */
  hasSingleGame: boolean
  /** The single game info when hasSingleGame is true, null otherwise */
  singleGame: GameInfo | null
  modesSummary: { text: string; emojis: string }
 
  // Tutorial/remediation derived values
  tutorialConfig: SkillTutorialConfig | null
  showTutorialGate: boolean
  showRemediationCta: boolean
  nextSkill: { skillId: string; displayName: string } | null
  /**
   * Whether the student can skip the tutorial.
   * False when user has no other skills to practice (first skill).
   * When false, tutorial is mandatory.
   */
  canSkipTutorial: boolean
  /**
   * Whether to include tutorial in the session.
   * Default: true when tutorialRequired.
   * User can uncheck if canSkipTutorial is true.
   */
  includeTutorial: boolean
  setIncludeTutorial: (include: boolean) => void
 
  // UI state
  isExpanded: boolean
  setIsExpanded: (expanded: boolean) => void
 
  // Mutation state
  isStarting: boolean
  displayError: Error | null
  isNoSkillsError: boolean
  isSessionLimitError: boolean
  /** Progress percentage (0-100) during plan generation */
  generationProgress: number
  /** Human-readable progress message during plan generation */
  generationProgressMessage: string | null
 
  // Skill selector (for "no skills" error remediation)
  showSkillSelector: boolean
  setShowSkillSelector: (show: boolean) => void
 
  // Actions
  handleStart: () => Promise<void>
  resetMutations: () => void
}
 
const StartPracticeModalContext = createContext<StartPracticeModalContextValue | null>(null)
 
export function useStartPracticeModal() {
  const context = useContext(StartPracticeModalContext)
  if (!context) {
    throw new Error('useStartPracticeModal must be used within StartPracticeModalProvider')
  }
  return context
}
 
interface StartPracticeModalProviderProps {
  children: ReactNode
  studentId: string
  studentName: string
  focusDescription: string
  sessionMode: SessionMode
  /** Comfort level from the session mode API (0-1), defaults to 0.3 */
  comfortLevel?: number
  /** Per-mode comfort levels from the session mode API */
  comfortByMode?: Record<string, number>
  secondsPerTerm?: number
  avgSecondsPerProblem?: number
  existingPlan?: SessionPlan | null
  /** When true, abandon existing session before generating a new one */
  startFresh?: boolean
  onStarted?: () => void
  /** Initial expanded state for settings panel (for Storybook) */
  initialExpanded?: boolean
  /** Override practice-approved games list (for Storybook/testing) */
  practiceApprovedGamesOverride?: GameInfo[]
  /** Previously saved session preferences for this student */
  savedPreferences?: PlayerSessionPreferencesConfig | null
  /** Callback fired when settings change (caller should debounce) */
  onSavePreferences?: (prefs: PlayerSessionPreferencesConfig) => void
}
 
export function StartPracticeModalProvider({
  children,
  studentId,
  studentName,
  focusDescription,
  sessionMode,
  comfortLevel: comfortLevelProp = 0.3,
  comfortByMode: comfortByModeProp = {},
  secondsPerTerm: secondsPerTermProp,
  avgSecondsPerProblem,
  existingPlan = null,
  startFresh = false,
  onStarted,
  initialExpanded = false,
  practiceApprovedGamesOverride,
  savedPreferences,
  onSavePreferences,
}: StartPracticeModalProviderProps) {
  const router = useRouter()
  const queryClient = useQueryClient()
 
  // Session config state (savedPreferences takes priority, then existingPlan, then hardcoded defaults)
  const [durationMinutes, setDurationMinutes] = useState(
    savedPreferences?.durationMinutes ?? existingPlan?.targetDurationMinutes ?? 10
  )
  const [isExpanded, setIsExpanded] = useState(initialExpanded)
  const [showSkillSelector, setShowSkillSelector] = useState(false)
  // Whether to include tutorial in session (default: true if tutorial is required)
  const [includeTutorial, setIncludeTutorial] = useState(
    sessionMode.type === 'progression' && sessionMode.tutorialRequired
  )
  const [partWeights, setPartWeights] = useState<PartWeights>(
    savedPreferences?.partWeights ?? { abacus: 2, visualization: 1, linear: 0 }
  )
  const enabledParts = useMemo<EnabledParts>(
    () => ({
      abacus: partWeights.abacus > 0,
      visualization: partWeights.visualization > 0,
      linear: partWeights.linear > 0,
    }),
    [partWeights]
  )
  const [problemLengthPreference, setProblemLengthPreference] = useState<ProblemLengthPreference>(
    savedPreferences?.problemLengthPreference ?? 'recommended'
  )
 
  // Game break config state
  const [gameBreakEnabled, setGameBreakEnabled] = useState(
    savedPreferences?.gameBreakEnabled ?? DEFAULT_GAME_BREAK_SETTINGS.enabled
  )
  const [gameBreakMinutes, setGameBreakMinutes] = useState(
    savedPreferences?.gameBreakMinutes ?? DEFAULT_GAME_BREAK_SETTINGS.maxDurationMinutes
  )
  const [gameBreakSelectionMode, setGameBreakSelectionMode] = useState<GameBreakSelectionMode>(
    (savedPreferences?.gameBreakSelectionMode as GameBreakSelectionMode) ??
      DEFAULT_GAME_BREAK_SETTINGS.selectionMode
  )
  const [gameBreakSelectedGame, setGameBreakSelectedGameRaw] = useState<string | 'random' | null>(
    savedPreferences?.gameBreakSelectedGame ?? DEFAULT_GAME_BREAK_SETTINGS.selectedGame
  )
  // Per-game config state
  const [gameBreakDifficultyPreset, setGameBreakDifficultyPreset] =
    useState<GameBreakDifficultyPreset>(
      (savedPreferences?.gameBreakDifficultyPreset as GameBreakDifficultyPreset) ?? 'medium'
    )
  const [gameBreakCustomConfig, setGameBreakCustomConfig] = useState<Record<string, unknown>>(
    savedPreferences?.gameBreakCustomConfig ?? {}
  )
  const [gameBreakShowCustomize, setGameBreakShowCustomize] = useState(
    savedPreferences?.gameBreakShowCustomize ?? false
  )
 
  // Tap on segment: 0→1, 1→2, 2→1 (never disables; no-op if sole active mode)
  const cyclePartWeight = useCallback((partType: keyof PartWeights) => {
    setPartWeights((prev) => {
      const current = prev[partType]
      if (current === 0) return { ...prev, [partType]: 1 }
      // If this is the only active mode, weight is meaningless — don't toggle
      const activeCount = Object.values(prev).filter((w) => w > 0).length
      if (activeCount === 1) return prev
      if (current === 1) return { ...prev, [partType]: 2 }
      // current === 2 → back to 1
      return { ...prev, [partType]: 1 }
    })
  }, [])
 
  // Explicit disable via × button (blocked if last active)
  const disablePart = useCallback((partType: keyof PartWeights) => {
    setPartWeights((prev) => {
      const othersTotal = Object.entries(prev)
        .filter(([k]) => k !== partType)
        .reduce((sum, [, v]) => sum + v, 0)
      if (othersTotal === 0) return prev // can't disable the last active part
      return { ...prev, [partType]: 0 }
    })
  }, [])
 
  // Purpose weight state
  const [purposeWeights, setPurposeWeights] = useState<PurposeWeights>(
    savedPreferences?.purposeWeights ?? { focus: 3, reinforce: 1, review: 1, challenge: 1 }
  )
  const [shufflePurposes, setShufflePurposes] = useState(savedPreferences?.shufflePurposes ?? true)
 
  // Tap on segment: 0→1, 1↔2 (no-op if sole active)
  const cyclePurposeWeight = useCallback((purposeType: PurposeWeightType) => {
    setPurposeWeights((prev) => {
      const current = prev[purposeType]
      if (current === 0) return { ...prev, [purposeType]: 1 }
      const activeCount = Object.values(prev).filter((w) => w > 0).length
      if (activeCount === 1) return prev
      if (current === 1) return { ...prev, [purposeType]: 2 }
      return { ...prev, [purposeType]: 1 }
    })
  }, [])
 
  // Explicit disable via × button (blocked if last active)
  const disablePurpose = useCallback((purposeType: PurposeWeightType) => {
    setPurposeWeights((prev) => {
      const othersTotal = Object.entries(prev)
        .filter(([k]) => k !== purposeType)
        .reduce((sum, [, v]) => sum + v, 0)
      if (othersTotal === 0) return prev
      return { ...prev, [purposeType]: 0 }
    })
  }, [])
 
  // Normalized 0-1 weights for API call
  const purposeTimeWeights = useMemo(() => {
    const total =
      purposeWeights.focus +
      purposeWeights.reinforce +
      purposeWeights.review +
      purposeWeights.challenge
    if (total === 0) return { focus: 1, reinforce: 0, review: 0, challenge: 0 }
    return {
      focus: purposeWeights.focus / total,
      reinforce: purposeWeights.reinforce / total,
      review: purposeWeights.review / total,
      challenge: purposeWeights.challenge / total,
    }
  }, [purposeWeights])
 
  // Derived values
  const secondsPerTerm = useMemo(() => {
    if (secondsPerTermProp !== undefined) return secondsPerTermProp
    if (avgSecondsPerProblem !== undefined)
      return convertSecondsPerProblemToSpt(avgSecondsPerProblem)
    return TIME_ESTIMATION_DEFAULTS.secondsPerTerm
  }, [secondsPerTermProp, avgSecondsPerProblem])
 
  const avgTermsPerProblem = useMemo(() => {
    const adjustment = COMFORT_ADJUSTMENTS[problemLengthPreference]
    const totalWeight = partWeights.abacus + partWeights.visualization + partWeights.linear
    if (totalWeight === 0) return 3 // fallback
 
    let weightedSum = 0
    for (const { type } of PART_TYPES) {
      if (partWeights[type] <= 0) continue
      const modeComfort = comfortByModeProp[type] ?? comfortLevelProp
      const adjustedComfort = Math.max(0, Math.min(1, modeComfort + adjustment))
      const range = computeTermCountRange(type, adjustedComfort)
      weightedSum += ((range.min + range.max) / 2) * partWeights[type]
    }
    return weightedSum / totalWeight
  }, [problemLengthPreference, comfortLevelProp, comfortByModeProp, partWeights])
 
  const practiceApprovedGames = useMemo(
    () => practiceApprovedGamesOverride ?? getPracticeApprovedGames(),
    [practiceApprovedGamesOverride]
  )
 
  // Per-player enabled games: filter approved games by the player's allowlist
  const gameBreakEnabledGames = savedPreferences?.gameBreakEnabledGames ?? []
  const playerEnabledGames = useMemo(() => {
    if (gameBreakEnabledGames.length === 0) return []
    return practiceApprovedGames.filter((g) => gameBreakEnabledGames.includes(g.manifest.name))
  }, [practiceApprovedGames, gameBreakEnabledGames])
 
  const hasSingleGame = playerEnabledGames.length === 1
  const singleGame = hasSingleGame ? playerEnabledGames[0] : null
 
  // Get the selected game's practice break config
  const selectedGamePracticeConfig = useMemo<PracticeBreakConfig | null>(() => {
    if (!gameBreakSelectedGame || gameBreakSelectedGame === 'random') return null
    const game = practiceApprovedGames.find((g) => g.manifest.name === gameBreakSelectedGame)
    return game?.manifest.practiceBreakConfig ?? null
  }, [gameBreakSelectedGame, practiceApprovedGames])
 
  // Resolve game config based on preset or custom settings
  const resolvedGameConfig = useMemo<Record<string, unknown>>(() => {
    if (!selectedGamePracticeConfig) return {}
 
    // If showing customize view, use custom config
    if (gameBreakShowCustomize) {
      return {
        ...selectedGamePracticeConfig.suggestedConfig,
        ...gameBreakCustomConfig,
      }
    }
 
    // Otherwise, use preset (defaults to medium if no preset selected)
    const preset = gameBreakDifficultyPreset ?? 'medium'
    const presetConfig = selectedGamePracticeConfig.difficultyPresets?.[preset]
    return {
      ...selectedGamePracticeConfig.suggestedConfig,
      ...presetConfig,
    }
  }, [
    selectedGamePracticeConfig,
    gameBreakShowCustomize,
    gameBreakCustomConfig,
    gameBreakDifficultyPreset,
  ])
 
  // Wrapper for setGameBreakSelectedGame that resets config when game changes
  const setGameBreakSelectedGame = useCallback((game: string | 'random' | null) => {
    setGameBreakSelectedGameRaw(game)
    // Reset config state when switching games
    setGameBreakDifficultyPreset('medium')
    setGameBreakCustomConfig({})
    setGameBreakShowCustomize(false)
  }, [])
 
  // Auto-select single game when only one is available
  useEffect(() => {
    if (hasSingleGame && singleGame) {
      setGameBreakSelectedGameRaw(singleGame.manifest.name)
      // Force auto-start mode when there's only one game
      setGameBreakSelectionMode('auto-start')
    }
  }, [hasSingleGame, singleGame])
 
  // If selected game is not in enabled list, reset to null
  useEffect(() => {
    if (
      gameBreakSelectedGame &&
      gameBreakSelectedGame !== 'random' &&
      playerEnabledGames.length > 0 &&
      !playerEnabledGames.some((g) => g.manifest.name === gameBreakSelectedGame)
    ) {
      setGameBreakSelectedGameRaw(null)
    }
  }, [gameBreakSelectedGame, playerEnabledGames])
 
  // If no games enabled, force game breaks off
  useEffect(() => {
    if (playerEnabledGames.length === 0 && gameBreakEnabled) {
      setGameBreakEnabled(false)
    }
  }, [playerEnabledGames.length, gameBreakEnabled])
 
  // Fire onSavePreferences callback whenever any persisted setting changes.
  // Use a ref for the callback so the effect only re-runs when settings change,
  // not when the callback identity changes (which would cause an infinite loop).
  const onSavePreferencesRef = useRef(onSavePreferences)
  onSavePreferencesRef.current = onSavePreferences
 
  // Track the last-saved config as JSON so we only fire saves when values actually change.
  // This handles StrictMode double-mount (ref persists, so second mount sees same JSON → skips)
  // and object reference changes (partWeights/purposeWeights are new objects each render).
  const lastSavedConfigRef = useRef<string | null>(null)
  useEffect(() => {
    const config = {
      durationMinutes,
      problemLengthPreference,
      partWeights,
      purposeWeights,
      shufflePurposes,
      gameBreakEnabled,
      gameBreakMinutes,
      gameBreakSelectionMode,
      gameBreakSelectedGame: gameBreakSelectedGame === 'random' ? null : gameBreakSelectedGame,
      gameBreakDifficultyPreset,
      gameBreakShowCustomize,
      gameBreakCustomConfig,
      gameBreakEnabledGames,
      kidLanguageStyle: savedPreferences?.kidLanguageStyle,
    }
    const configJson = JSON.stringify(config)
 
    if (lastSavedConfigRef.current === null) {
      // First run — capture initial state, don't save
      lastSavedConfigRef.current = configJson
      return
    }
 
    if (configJson === lastSavedConfigRef.current) return
 
    lastSavedConfigRef.current = configJson
    onSavePreferencesRef.current?.(config)
  }, [
    durationMinutes,
    problemLengthPreference,
    partWeights,
    purposeWeights,
    shufflePurposes,
    gameBreakEnabled,
    gameBreakMinutes,
    gameBreakSelectionMode,
    gameBreakSelectedGame,
    gameBreakDifficultyPreset,
    gameBreakShowCustomize,
    gameBreakCustomConfig,
    gameBreakEnabledGames,
    savedPreferences?.kidLanguageStyle,
  ])
 
  // Derive partTimeWeights from partWeights for the API call
  const partTimeWeights = useMemo(() => {
    const total = partWeights.abacus + partWeights.visualization + partWeights.linear
    if (total === 0) return { abacus: 1, visualization: 0, linear: 0 }
    return {
      abacus: partWeights.abacus / total,
      visualization: partWeights.visualization / total,
      linear: partWeights.linear / total,
    }
  }, [partWeights])
 
  const problemsPerType = useMemo(() => {
    const totalWeight = partWeights.abacus + partWeights.visualization + partWeights.linear
    if (totalWeight === 0) {
      return { abacus: 0, visualization: 0, linear: 0 }
    }
 
    return {
      abacus:
        partWeights.abacus > 0
          ? estimateSessionProblemCount(
              durationMinutes * (partWeights.abacus / totalWeight),
              avgTermsPerProblem,
              secondsPerTerm,
              'abacus'
            )
          : 0,
      visualization:
        partWeights.visualization > 0
          ? estimateSessionProblemCount(
              durationMinutes * (partWeights.visualization / totalWeight),
              avgTermsPerProblem,
              secondsPerTerm,
              'visualization'
            )
          : 0,
      linear:
        partWeights.linear > 0
          ? estimateSessionProblemCount(
              durationMinutes * (partWeights.linear / totalWeight),
              avgTermsPerProblem,
              secondsPerTerm,
              'linear'
            )
          : 0,
    }
  }, [durationMinutes, partWeights, avgTermsPerProblem, secondsPerTerm])
 
  const estimatedProblems = useMemo(() => {
    return problemsPerType.abacus + problemsPerType.visualization + problemsPerType.linear
  }, [problemsPerType])
 
  const modesSummary = useMemo(() => {
    const enabled = PART_TYPES.filter((p) => partWeights[p.type] > 0)
    if (enabled.length === PART_TYPES.length)
      return {
        text: 'all modes',
        emojis: enabled.map((p) => p.emoji).join(''),
      }
    if (enabled.length === 0) return { text: 'none', emojis: '—' }
    return {
      text: `${enabled.length} mode${enabled.length > 1 ? 's' : ''}`,
      emojis: enabled.map((p) => p.emoji).join(''),
    }
  }, [partWeights])
 
  const enabledPartCount = useMemo(() => {
    return PART_TYPES.filter((p) => partWeights[p.type] > 0).length
  }, [partWeights])
 
  const showGameBreakSettings = enabledPartCount >= 2
 
  // Tutorial/remediation derived values
  const tutorialConfig = useMemo(() => {
    if (sessionMode.type !== 'progression' || !sessionMode.tutorialRequired) return null
    return getSkillTutorialConfig(sessionMode.nextSkill.skillId)
  }, [sessionMode])
 
  const nextSkill = sessionMode.type === 'progression' ? sessionMode.nextSkill : null
 
  const showTutorialGate = !!tutorialConfig
  const showRemediationCta = sessionMode.type === 'remediation' && sessionMode.weakSkills.length > 0
 
  // Check if student can skip the tutorial (has other skills to practice)
  const canSkipTutorial = sessionMode.type === 'progression' ? sessionMode.canSkipTutorial : true
 
  // Mutations
  const generatePlan = useGenerateSessionPlan()
  const approvePlan = useApproveSessionPlan()
  const startPlan = useStartSessionPlan()
  const abandonSession = useAbandonSession()
 
  // Track whether we're in the start flow (waiting for generation → approve → start)
  const [isStartFlow, setIsStartFlow] = useState(false)
 
  const isStarting =
    isStartFlow ||
    generatePlan.isPending ||
    generatePlan.isGenerating ||
    approvePlan.isPending ||
    startPlan.isPending
 
  const displayError = useMemo(() => {
    if (generatePlan.error && !(generatePlan.error instanceof ActiveSessionExistsClientError)) {
      return generatePlan.error
    }
    // Show task-level errors (e.g., NoSkillsEnabled thrown inside the task)
    if (generatePlan.taskError) {
      return new Error(generatePlan.taskError)
    }
    if (approvePlan.error) return approvePlan.error
    if (startPlan.error) return startPlan.error
    return null
  }, [generatePlan.error, generatePlan.taskError, approvePlan.error, startPlan.error])
 
  const isNoSkillsError =
    displayError instanceof NoSkillsEnabledClientError ||
    (displayError?.message?.includes('no skills are enabled') ?? false)
 
  const isSessionLimitError = displayError instanceof SessionLimitReachedError
 
  // Refs to stable mutation functions (avoids re-triggering effects)
  const onStartedRef = useRef(onStarted)
  onStartedRef.current = onStarted
  const approvePlanRef = useRef(approvePlan)
  approvePlanRef.current = approvePlan
  const startPlanRef = useRef(startPlan)
  startPlanRef.current = startPlan
  // Guard against re-entry (effect dependencies like plan object identity can re-trigger)
  const isCompletingFlowRef = useRef(false)
 
  const resetMutations = useCallback(() => {
    generatePlan.reset()
    approvePlan.reset()
    startPlan.reset()
    setIsStartFlow(false)
    isCompletingFlowRef.current = false
  }, [generatePlan, approvePlan, startPlan])
 
  // When the background task completes with a plan, continue the start flow
  // (approve → start → navigate)
  useEffect(() => {
    if (!isStartFlow) return
    if (!generatePlan.plan) return
    if (isCompletingFlowRef.current) return
    isCompletingFlowRef.current = true

    // Plan is ready — continue with approve and start
    const plan = generatePlan.plan
    ;(async () => {
      try {
        await approvePlanRef.current.mutateAsync({ playerId: studentId, planId: plan.id })
        await startPlanRef.current.mutateAsync({ playerId: studentId, planId: plan.id })
        onStartedRef.current?.()
        router.push(`/practice/${studentId}`, { scroll: false })
      } catch {
        // Error will show in UI
      } finally {
        setIsStartFlow(false)
        isCompletingFlowRef.current = false
      }
    })()
  }, [isStartFlow, generatePlan.plan, studentId, router])
 
  // If the task fails, stop the start flow
  useEffect(() => {
    if (isStartFlow && generatePlan.taskError) {
      setIsStartFlow(false)
    }
  }, [isStartFlow, generatePlan.taskError])
 
  const generatePlanParams = useCallback(() => {
    const comfortAdj = COMFORT_ADJUSTMENTS[problemLengthPreference]
    return {
      playerId: studentId,
      durationMinutes,
      comfortAdjustment: comfortAdj !== 0 ? comfortAdj : undefined,
      enabledParts,
      partTimeWeights,
      purposeTimeWeights,
      shufflePurposes,
      problemGenerationMode: 'adaptive-bkt' as const,
      sessionMode,
      gameBreakSettings: {
        enabled: gameBreakEnabled,
        maxDurationMinutes: gameBreakMinutes,
        selectionMode: gameBreakSelectionMode,
        selectedGame: gameBreakEnabled ? gameBreakSelectedGame : null,
        gameConfig:
          gameBreakEnabled &&
          gameBreakSelectedGame &&
          gameBreakSelectedGame !== 'random' &&
          Object.keys(resolvedGameConfig).length > 0
            ? ({
                [gameBreakSelectedGame]: resolvedGameConfig,
              } as PracticeBreakGameConfig)
            : undefined,
        enabledGames: playerEnabledGames.map((g) => g.manifest.name),
        skipSetupPhase: true,
      },
    }
  }, [
    studentId,
    durationMinutes,
    problemLengthPreference,
    enabledParts,
    partTimeWeights,
    purposeTimeWeights,
    shufflePurposes,
    sessionMode,
    gameBreakEnabled,
    gameBreakMinutes,
    gameBreakSelectionMode,
    gameBreakSelectedGame,
    resolvedGameConfig,
    playerEnabledGames,
  ])
 
  const handleStart = useCallback(async () => {
    resetMutations()
 
    try {
      // When not starting fresh, reuse existing plan if duration matches
      if (!startFresh && existingPlan && existingPlan.targetDurationMinutes === durationMinutes) {
        setIsStartFlow(true)
        await approvePlan.mutateAsync({ playerId: studentId, planId: existingPlan.id })
        await startPlan.mutateAsync({ playerId: studentId, planId: existingPlan.id })
        onStarted?.()
        router.push(`/practice/${studentId}`, { scroll: false })
        setIsStartFlow(false)
        return
      }
 
      // If starting fresh, abandon the existing session first
      if (startFresh && existingPlan) {
        await abandonSession.mutateAsync({ playerId: studentId, planId: existingPlan.id })
      }
 
      try {
        setIsStartFlow(true)
        await generatePlan.mutateAsync(generatePlanParams())
        // Don't set isStartFlow to false — the effect will handle the rest
      } catch (err) {
        if (err instanceof ActiveSessionExistsClientError) {
          if (startFresh) {
            // Abandon and retry — shouldn't normally happen since we abandoned above,
            // but handles race conditions
            const plan = err.existingPlan
            await abandonSession.mutateAsync({ playerId: studentId, planId: plan.id })
            await generatePlan.mutateAsync(generatePlanParams())
          } else {
            const plan = err.existingPlan
            queryClient.setQueryData(sessionPlanKeys.active(studentId), plan)
            await approvePlan.mutateAsync({ playerId: studentId, planId: plan.id })
            await startPlan.mutateAsync({ playerId: studentId, planId: plan.id })
            onStarted?.()
            router.push(`/practice/${studentId}`, { scroll: false })
            setIsStartFlow(false)
          }
        } else {
          setIsStartFlow(false)
          throw err
        }
      }
    } catch {
      // Error will show in UI
      setIsStartFlow(false)
    }
  }, [
    studentId,
    durationMinutes,
    startFresh,
    existingPlan,
    generatePlanParams,
    generatePlan,
    approvePlan,
    startPlan,
    abandonSession,
    queryClient,
    router,
    onStarted,
    resetMutations,
  ])
 
  const value: StartPracticeModalContextValue = {
    // Read-only props
    studentId,
    studentName,
    focusDescription,
    sessionMode,
    existingPlan,
 
    // Session config
    durationMinutes,
    setDurationMinutes,
    enabledParts,
    partWeights,
    cyclePartWeight,
    disablePart,
    problemLengthPreference,
    setProblemLengthPreference,
    comfortLevel: comfortLevelProp,
    comfortByMode: comfortByModeProp,
 
    // Purpose weight config
    purposeWeights,
    cyclePurposeWeight,
    disablePurpose,
    purposeTimeWeights,
    shufflePurposes,
    setShufflePurposes,
 
    // Game break config
    gameBreakEnabled,
    setGameBreakEnabled,
    gameBreakMinutes,
    setGameBreakMinutes,
    gameBreakSelectionMode,
    setGameBreakSelectionMode,
    gameBreakSelectedGame,
    setGameBreakSelectedGame,
    // Per-game config
    gameBreakDifficultyPreset,
    setGameBreakDifficultyPreset,
    gameBreakCustomConfig,
    setGameBreakCustomConfig,
    gameBreakShowCustomize,
    setGameBreakShowCustomize,
    selectedGamePracticeConfig,
    resolvedGameConfig,
 
    // Derived values
    secondsPerTerm,
    avgTermsPerProblem,
    problemsPerType,
    estimatedProblems,
    enabledPartCount,
    showGameBreakSettings,
    practiceApprovedGames,
    playerEnabledGames,
    hasSingleGame,
    singleGame,
    modesSummary,
 
    // Tutorial/remediation
    tutorialConfig,
    showTutorialGate,
    showRemediationCta,
    nextSkill,
    canSkipTutorial,
    includeTutorial,
    setIncludeTutorial,
 
    // UI state
    isExpanded,
    setIsExpanded,
 
    // Mutation state
    isStarting,
    displayError,
    isNoSkillsError,
    isSessionLimitError,
    generationProgress: generatePlan.progress,
    generationProgressMessage: generatePlan.progressMessage,
 
    // Skill selector
    showSkillSelector,
    setShowSkillSelector,
 
    // Actions
    handleStart,
    resetMutations,
  }
 
  return (
    <StartPracticeModalContext.Provider value={value}>
      {children}
    </StartPracticeModalContext.Provider>
  )
}