All files / web/src/components/tutorial TutorialContext.tsx

75.22% Statements 580/771
92.3% Branches 48/52
37.5% Functions 3/8
75.22% Lines 580/771

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 7721x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 417x 417x 417x 417x 417x 417x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 323x 417x 417x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 417x 417x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 417x 417x 9x 9x 9x 9x 417x 417x 12x 12x 12x 12x 417x 417x 7x 7x 7x 7x 417x 417x 6x 6x 6x 6x 6x 417x 417x 2x 2x 2x 2x 417x 417x 1x 1x 1x 1x 417x 417x   417x 417x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 459x 459x 459x 459x 459x 459x 183x 183x 183x 183x 183x 183x 183x 183x 234x 234x 234x 234x 234x 234x 234x 234x 183x 183x 183x 183x 183x 183x 183x 183x       459x 459x 459x 459x 459x                         459x 459x 459x 459x 459x 459x                               459x 459x 459x 459x 459x 459x                                                                   459x 459x 459x 459x 459x 459x                 459x 459x 459x 459x 459x 459x 183x 183x 183x 459x 459x 459x 459x 459x 459x     459x 459x 459x 459x 459x 20x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 20x 459x 459x 459x 459x 459x 164x 164x 25x 24x 24x 164x 164x 164x 459x 459x 459x 15x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 3x 3x 3x 459x 459x 459x 459x 42x 8x 8x 8x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 38x 22x 22x 22x 22x 22x 22x 42x 459x 459x 459x 459x 459x                     459x 459x 459x 459x             459x 459x 459x         459x 459x 459x         459x 459x 459x         459x 459x 459x 6x 459x 459x 459x 2x 459x 459x 459x 1x 459x 459x 459x                   459x 459x 459x                         459x 459x 459x                       459x 459x 459x 167x 56x 56x 111x 111x 111x 112x 112x 112x 111x 111x 112x 112x 1x 1x 1x 1x 112x 111x 111x 111x 111x 111x 111x 111x 111x 111x 112x 112x 111x 111x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 459x 1x 1x 1x 459x 459x     459x 459x 1x 1x 1x       1x 1x       1x 1x                                                     1x 1x                             1x 1x                   1x 1x 1x  
'use client'
 
import React, {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useReducer,
  useRef,
  useState,
} from 'react'
import type { Tutorial, TutorialEvent, TutorialStep, UIState } from '../../types/tutorial'
import {
  generateUnifiedInstructionSequence,
  type UnifiedStepData,
} from '../../utils/unifiedStepGenerator'
 
// Exact same interfaces from TutorialPlayer.tsx
interface TutorialPlayerState {
  currentStepIndex: number
  currentValue: number
  isStepCompleted: boolean
  error: string | null
  events: TutorialEvent[]
  stepStartTime: number
  multiStepStartTime: number // Track when current multi-step started
  uiState: UIState
  currentMultiStep: number // Current step within multi-step instructions (0-based)
}
 
interface ExpectedStep {
  index: number
  stepIndex: number
  targetValue: number
  startValue: number
  description: string
  mathematicalTerm?: string // Pedagogical term like "10", "(5 - 1)", "-6"
  termPosition?: { startIndex: number; endIndex: number } // Position in full decomposition
}
 
type TutorialPlayerAction =
  | {
      type: 'INITIALIZE_STEP'
      stepIndex: number
      startValue: number
      stepId: string
    }
  | {
      type: 'USER_VALUE_CHANGE'
      oldValue: number
      newValue: number
      stepId: string
    }
  | { type: 'COMPLETE_STEP'; stepId: string }
  | { type: 'SET_ERROR'; error: string | null }
  | { type: 'ADD_EVENT'; event: TutorialEvent }
  | { type: 'UPDATE_UI_STATE'; updates: Partial<UIState> }
  | { type: 'ADVANCE_MULTI_STEP' }
  | { type: 'PREVIOUS_MULTI_STEP' }
  | { type: 'RESET_MULTI_STEP' }
 
// Exact same reducer from TutorialPlayer.tsx
function tutorialPlayerReducer(
  state: TutorialPlayerState,
  action: TutorialPlayerAction
): TutorialPlayerState {
  switch (action.type) {
    case 'INITIALIZE_STEP':
      return {
        ...state,
        currentStepIndex: action.stepIndex,
        currentValue: action.startValue,
        isStepCompleted: false,
        error: null,
        stepStartTime: Date.now(),
        multiStepStartTime: Date.now(), // Start timing for first multi-step
        currentMultiStep: 0, // Reset to first multi-step
        events: [
          ...state.events,
          {
            type: 'STEP_STARTED',
            stepId: action.stepId,
            timestamp: new Date(),
          },
        ],
      }
 
    case 'USER_VALUE_CHANGE':
      return {
        ...state,
        currentValue: action.newValue,
        events: [
          ...state.events,
          {
            type: 'VALUE_CHANGED',
            stepId: action.stepId,
            oldValue: action.oldValue,
            newValue: action.newValue,
            timestamp: new Date(),
          },
        ],
      }
 
    case 'COMPLETE_STEP':
      return {
        ...state,
        isStepCompleted: true,
        error: null,
        events: [
          ...state.events,
          {
            type: 'STEP_COMPLETED',
            stepId: action.stepId,
            success: true,
            timestamp: new Date(),
          },
        ],
      }
 
    case 'SET_ERROR':
      return {
        ...state,
        error: action.error,
      }
 
    case 'ADD_EVENT':
      return {
        ...state,
        events: [...state.events, action.event],
      }
 
    case 'UPDATE_UI_STATE':
      return {
        ...state,
        uiState: { ...state.uiState, ...action.updates },
      }
 
    case 'ADVANCE_MULTI_STEP':
      return {
        ...state,
        currentMultiStep: state.currentMultiStep + 1,
        multiStepStartTime: Date.now(), // Reset timer for new multi-step
      }
 
    case 'PREVIOUS_MULTI_STEP':
      return {
        ...state,
        currentMultiStep: Math.max(0, state.currentMultiStep - 1),
      }
 
    case 'RESET_MULTI_STEP':
      return {
        ...state,
        currentMultiStep: 0,
      }
 
    default:
      return state
  }
}
 
// Context interfaces
interface TutorialContextType {
  state: TutorialPlayerState
  dispatch: React.Dispatch<TutorialPlayerAction>
  tutorial: Tutorial
  isProgrammaticChange: React.MutableRefObject<boolean>
  showHelpForCurrentStep: boolean
  setShowHelpForCurrentStep: React.Dispatch<React.SetStateAction<boolean>>
  beadRefs: React.MutableRefObject<Map<string, SVGElement>>
 
  // Computed values
  currentStep: TutorialStep
  expectedSteps: ExpectedStep[]
  fullDecomposition: string
  unifiedSteps: UnifiedStepData[] // NEW: Add unified steps with provenance
  customStyles: any
 
  // Term-to-column highlighting state
  activeTermIndices: Set<number>
  setActiveTermIndices: (indices: Set<number>) => void
  activeIndividualTermIndex: number | null
  setActiveIndividualTermIndex: (index: number | null) => void
  activeGroupTargetColumn: number | null
  setActiveGroupTargetColumn: (columnIndex: number | null) => void
  getColumnFromTermIndex: (termIndex: number, useGroupColumn?: boolean) => number | null
  getTermIndicesFromColumn: (columnIndex: number) => number[]
  getGroupTermIndicesFromTermIndex: (termIndex: number) => number[]
  handleAbacusColumnHover: (columnIndex: number, isHovering: boolean) => void
 
  // Action functions
  goToStep: (stepIndex: number) => void
  goToNextStep: () => void
  goToPreviousStep: () => void
  handleValueChange: (newValue: number) => void
  advanceMultiStep: () => void
  previousMultiStep: () => void
  resetMultiStep: () => void
  handleBeadClick: (beadInfo: any) => void
  handleBeadRef: (bead: any, element: SVGElement | null) => void
  toggleDebugPanel: () => void
  toggleStepList: () => void
  toggleAutoAdvance: () => void
  notifyEvent: (event: TutorialEvent) => void
  getCurrentStepBeads: () => any[]
  getCurrentStepSummary: () => any
  renderHighlightedDecomposition: () => any
}
 
interface TutorialProviderProps {
  tutorial: Tutorial
  initialStepIndex?: number
  showDebugPanel?: boolean
  onStepChange?: (stepIndex: number, step: TutorialStep) => void
  onStepComplete?: (stepIndex: number, step: TutorialStep, success: boolean) => void
  onTutorialComplete?: (score: number, timeSpent: number) => void
  onEvent?: (event: TutorialEvent) => void
  children: React.ReactNode
}
 
// Create context
const TutorialContext = createContext<TutorialContextType | null>(null)
 
// Provider component
export function TutorialProvider({
  tutorial,
  initialStepIndex = 0,
  showDebugPanel = false,
  onStepChange,
  onStepComplete,
  onTutorialComplete,
  onEvent,
  children,
}: TutorialProviderProps) {
  const isProgrammaticChange = useRef(false)
  const [showHelpForCurrentStep, setShowHelpForCurrentStep] = useState(false)
  const beadRefs = useRef<Map<string, SVGElement>>(new Map())
 
  // Term-to-column highlighting state
  const [activeTermIndices, setActiveTermIndices] = useState<Set<number>>(new Set())
  const [activeIndividualTermIndex, setActiveIndividualTermIndex] = useState<number | null>(null)
  const [activeGroupTargetColumn, setActiveGroupTargetColumn] = useState<number | null>(null)
 
  const [state, dispatch] = useReducer(tutorialPlayerReducer, {
    currentStepIndex: initialStepIndex,
    currentValue: 0,
    isStepCompleted: false,
    error: null,
    events: [],
    stepStartTime: Date.now(),
    multiStepStartTime: Date.now(),
    currentMultiStep: 0,
    uiState: {
      isPlaying: true,
      isPaused: false,
      isEditing: false,
      showDebugPanel,
      showStepList: false,
      autoAdvance: false,
      playbackSpeed: 1,
    },
  })
 
  // Initialize the first step on mount
  React.useEffect(() => {
    if (tutorial.steps.length > 0) {
      const step = tutorial.steps[initialStepIndex]
 
      // Mark as programmatic change to prevent AbacusReact feedback loop
      isProgrammaticChange.current = true
 
      dispatch({
        type: 'INITIALIZE_STEP',
        stepIndex: initialStepIndex,
        startValue: step.startValue,
        stepId: step.id,
      })
      onStepChange?.(initialStepIndex, step)
    }
  }, [initialStepIndex, onStepChange, tutorial.steps.length, tutorial.steps[initialStepIndex]]) // Empty dependency array - only run on mount
 
  // Current step and computed values
  const currentStep = tutorial.steps[state.currentStepIndex]
 
  const { expectedSteps, fullDecomposition, unifiedSteps } = useMemo(() => {
    try {
      const unifiedSequence = generateUnifiedInstructionSequence(
        currentStep.startValue,
        currentStep.targetValue
      )
 
      // Map UnifiedStepData to ExpectedStep format
      const mappedSteps: ExpectedStep[] = unifiedSequence.steps.map((step, index) => ({
        index,
        stepIndex: step.stepIndex,
        targetValue: step.expectedValue,
        startValue:
          index === 0 ? currentStep.startValue : unifiedSequence.steps[index - 1].expectedValue,
        description: step.englishInstruction,
        mathematicalTerm: step.mathematicalTerm,
        termPosition: step.termPosition,
      }))
 
      return {
        expectedSteps: mappedSteps,
        fullDecomposition: unifiedSequence.fullDecomposition,
        unifiedSteps: unifiedSequence.steps, // NEW: Include raw steps with provenance
      }
    } catch (error) {
      console.warn('Failed to generate unified sequence:', error)
      return { expectedSteps: [], fullDecomposition: '', unifiedSteps: [] }
    }
  }, [currentStep.startValue, currentStep.targetValue])
 
  // Term-to-column mapping function
  const getColumnFromTermIndex = useCallback(
    (termIndex: number, useGroupColumn = false) => {
      const step = unifiedSteps[termIndex]
      if (!step?.provenance) return null

      // For group highlighting: use rhsPlace (target column)
      // For individual highlighting: use termPlace (individual term column)
      const placeValue = useGroupColumn
        ? step.provenance.rhsPlace
        : (step.provenance.termPlace ?? step.provenance.rhsPlace)

      // Convert place value (0=ones, 1=tens, 2=hundreds) to columnIndex (4=ones, 3=tens, 2=hundreds)
      return 4 - placeValue
    },
    [unifiedSteps]
  )
 
  // Column-to-terms mapping function (for bidirectional interaction)
  const getTermIndicesFromColumn = useCallback(
    (columnIndex: number) => {
      const termIndices: number[] = []

      unifiedSteps.forEach((step, index) => {
        if (step.provenance) {
          // Use termPlace if available, otherwise fallback to rhsPlace
          const placeValue = step.provenance.termPlace ?? step.provenance.rhsPlace
          const stepColumnIndex = 4 - placeValue
          if (stepColumnIndex === columnIndex) {
            termIndices.push(index)
          }
        }
      })

      return termIndices
    },
    [unifiedSteps]
  )
 
  // Group-to-terms mapping function (for complement groups)
  const getGroupTermIndicesFromTermIndex = useCallback(
    (termIndex: number) => {
      console.log('🔍 getGroupTermIndicesFromTermIndex called with termIndex:', termIndex)

      const step = unifiedSteps[termIndex]
      console.log('  - Step data:', {
        mathematicalTerm: step?.mathematicalTerm,
        hasProvenance: !!step?.provenance,
        groupId: step?.provenance?.groupId,
        rhsPlace: step?.provenance?.rhsPlace,
        rhsValue: step?.provenance?.rhsValue,
      })

      if (!step?.provenance?.groupId) {
        console.log('  - No groupId found, returning empty array')
        return []
      }

      const groupId = step.provenance.groupId
      console.log('  - Found groupId:', groupId)

      const groupTermIndices: number[] = []

      unifiedSteps.forEach((groupStep, index) => {
        if (groupStep.provenance?.groupId === groupId) {
          groupTermIndices.push(index)
          console.log(
            `    - Found group member: term ${index} "${groupStep.mathematicalTerm}" (rhsPlace: ${groupStep.provenance.rhsPlace})`
          )
        }
      })

      console.log('  - Final group term indices:', groupTermIndices)
      return groupTermIndices
    },
    [unifiedSteps]
  )
 
  // Abacus column hover handler for bidirectional interaction
  const handleAbacusColumnHover = useCallback(
    (columnIndex: number, isHovering: boolean) => {
      if (isHovering) {
        // Find all terms that correspond to this column
        const relatedTerms = getTermIndicesFromColumn(columnIndex)
        setActiveTermIndices(new Set(relatedTerms))
      } else {
        setActiveTermIndices(new Set())
      }
    },
    [getTermIndicesFromColumn]
  )
 
  // Navigation state
  const navigationState = useMemo(
    () => ({
      canGoNext: state.currentStepIndex < tutorial.steps.length - 1,
      canGoPrevious: state.currentStepIndex > 0,
    }),
    [state.currentStepIndex, tutorial.steps.length]
  )
 
  // Action functions
  const notifyEvent = useCallback(
    (event: TutorialEvent) => {
      onEvent?.(event)
    },
    [onEvent]
  )
 
  const goToStep = useCallback(
    (stepIndex: number) => {
      if (stepIndex >= 0 && stepIndex < tutorial.steps.length) {
        const step = tutorial.steps[stepIndex]
 
        // Mark as programmatic change to prevent AbacusReact feedback loop
        isProgrammaticChange.current = true
 
        dispatch({
          type: 'INITIALIZE_STEP',
          stepIndex,
          startValue: step.startValue,
          stepId: step.id,
        })
        onStepChange?.(stepIndex, step)
      }
    },
    [tutorial.steps, onStepChange]
  )
 
  // Clear isProgrammaticChange flag after external value changes have settled
  React.useEffect(() => {
    // Use a small timeout to ensure the AbacusReact has processed the value change
    const timeoutId = setTimeout(() => {
      if (isProgrammaticChange.current) {
        isProgrammaticChange.current = false
      }
    }, 100)
 
    return () => clearTimeout(timeoutId)
  }, [])
 
  const goToNextStep = useCallback(() => {
    if (navigationState.canGoNext) {
      goToStep(state.currentStepIndex + 1)
    } else if (state.isStepCompleted && state.currentStepIndex === tutorial.steps.length - 1) {
      // On the last step and step is completed - trigger tutorial completion
      const startTime =
        state.events.length > 0 ? new Date(state.events[0].timestamp).getTime() : Date.now() - 60000 // fallback to 1 minute ago
      const timeSpent = Math.round((Date.now() - startTime) / 1000)
 
      // Calculate score based on completed steps (100% for completing all steps)
      const score = 100
 
      onTutorialComplete?.(score, timeSpent)
    }
  }, [
    navigationState.canGoNext,
    goToStep,
    state.currentStepIndex,
    state.isStepCompleted,
    state.events,
    tutorial.steps.length,
    onTutorialComplete,
  ])
 
  const goToPreviousStep = useCallback(() => {
    if (navigationState.canGoPrevious) {
      goToStep(state.currentStepIndex - 1)
    }
  }, [navigationState.canGoPrevious, goToStep, state.currentStepIndex])
 
  const handleValueChange = useCallback(
    (newValue: number) => {
      if (isProgrammaticChange.current) {
        isProgrammaticChange.current = false
        return
      }
 
      const oldValue = state.currentValue
      dispatch({
        type: 'USER_VALUE_CHANGE',
        oldValue,
        newValue,
        stepId: currentStep.id,
      })
 
      // Check if step is completed
      if (newValue === currentStep.targetValue) {
        dispatch({
          type: 'COMPLETE_STEP',
          stepId: currentStep.id,
        })
        onStepComplete?.(state.currentStepIndex, currentStep, true)
      }
    },
    [state.currentValue, currentStep, onStepComplete, state.currentStepIndex]
  )
 
  const handleBeadClick = useCallback(
    (beadInfo: any) => {
      dispatch({
        type: 'ADD_EVENT',
        event: {
          type: 'BEAD_CLICKED',
          stepId: currentStep.id,
          timestamp: new Date(),
          beadInfo,
        },
      })
    },
    [currentStep.id]
  )
 
  const handleBeadRef = useCallback((bead: any, element: SVGElement | null) => {
    const key = `${bead.placeValue}-${bead.type}-${bead.position}`
    if (element) {
      beadRefs.current.set(key, element)
    } else {
      beadRefs.current.delete(key)
    }
  }, [])
 
  const toggleDebugPanel = useCallback(() => {
    dispatch({
      type: 'UPDATE_UI_STATE',
      updates: { showDebugPanel: !state.uiState.showDebugPanel },
    })
  }, [state.uiState.showDebugPanel])
 
  const toggleStepList = useCallback(() => {
    dispatch({
      type: 'UPDATE_UI_STATE',
      updates: { showStepList: !state.uiState.showStepList },
    })
  }, [state.uiState.showStepList])
 
  const toggleAutoAdvance = useCallback(() => {
    dispatch({
      type: 'UPDATE_UI_STATE',
      updates: { autoAdvance: !state.uiState.autoAdvance },
    })
  }, [state.uiState.autoAdvance])
 
  const advanceMultiStep = useCallback(() => {
    dispatch({ type: 'ADVANCE_MULTI_STEP' })
  }, [])
 
  const previousMultiStep = useCallback(() => {
    dispatch({ type: 'PREVIOUS_MULTI_STEP' })
  }, [])
 
  const resetMultiStep = useCallback(() => {
    dispatch({ type: 'RESET_MULTI_STEP' })
  }, [])
 
  const getCurrentStepBeads = useCallback(() => {
    if (expectedSteps.length === 0) return currentStep.stepBeadHighlights || []

    if (state.currentMultiStep < expectedSteps.length) {
      // Since we mapped from UnifiedStepData, we need to get the original step data
      // to access beadMovements. For now, fall back to existing stepBeadHighlights
      return currentStep.stepBeadHighlights || []
    }

    return []
  }, [expectedSteps, currentStep.stepBeadHighlights, state.currentMultiStep])
 
  const getCurrentStepSummary = useCallback(() => {
    if (expectedSteps.length === 0) return null

    if (state.currentMultiStep < expectedSteps.length) {
      const currentExpectedStep = expectedSteps[state.currentMultiStep]
      return {
        description: currentExpectedStep.description,
        mathematicalTerm: currentExpectedStep.mathematicalTerm,
        termPosition: currentExpectedStep.termPosition,
      }
    }

    return null
  }, [expectedSteps, state.currentMultiStep])
 
  const renderHighlightedDecomposition = useCallback(() => {
    if (!fullDecomposition || expectedSteps.length === 0) return null

    const currentExpectedStep = expectedSteps[state.currentMultiStep]
    if (!currentExpectedStep?.termPosition) return fullDecomposition

    const { startIndex, endIndex } = currentExpectedStep.termPosition
    const before = fullDecomposition.slice(0, startIndex)
    const highlighted = fullDecomposition.slice(startIndex, endIndex + 1)
    const after = fullDecomposition.slice(endIndex + 1)

    return { before, highlighted, after }
  }, [fullDecomposition, expectedSteps, state.currentMultiStep])
 
  const customStyles = useMemo(() => {
    if (!currentStep.highlightBeads || !Array.isArray(currentStep.highlightBeads)) {
      return undefined
    }
 
    return {
      beads: currentStep.highlightBeads.reduce((acc, highlight) => {
        const columnIndex = 4 - highlight.placeValue
 
        if (!acc[columnIndex]) {
          acc[columnIndex] = {}
        }
 
        if (highlight.beadType === 'heaven') {
          acc[columnIndex].heaven = {
            backgroundColor: '#ffeb3b',
            border: '2px solid #ff9800',
          }
        } else if (highlight.beadType === 'earth') {
          if (!acc[columnIndex].earth) {
            acc[columnIndex].earth = {}
          }
          const position = highlight.position || 0
          acc[columnIndex].earth[position] = {
            backgroundColor: '#ffeb3b',
            border: '2px solid #ff9800',
          }
        }
 
        return acc
      }, {} as any),
    }
  }, [currentStep.highlightBeads])
 
  const value: TutorialContextType = {
    state,
    dispatch,
    tutorial,
    isProgrammaticChange,
    showHelpForCurrentStep,
    setShowHelpForCurrentStep,
    beadRefs,
 
    // Computed values
    currentStep,
    expectedSteps,
    fullDecomposition,
    unifiedSteps,
    customStyles,
 
    // Term-to-column highlighting state
    activeTermIndices,
    setActiveTermIndices,
    activeIndividualTermIndex,
    setActiveIndividualTermIndex,
    activeGroupTargetColumn,
    setActiveGroupTargetColumn,
    getColumnFromTermIndex,
    getTermIndicesFromColumn,
    getGroupTermIndicesFromTermIndex,
    handleAbacusColumnHover,
 
    // Action functions
    goToStep,
    goToNextStep,
    goToPreviousStep,
    handleValueChange,
    advanceMultiStep,
    previousMultiStep,
    resetMultiStep,
    handleBeadClick,
    handleBeadRef,
    toggleDebugPanel,
    toggleStepList,
    toggleAutoAdvance,
    notifyEvent,
    getCurrentStepBeads,
    getCurrentStepSummary,
    renderHighlightedDecomposition,
  }
 
  return <TutorialContext.Provider value={value}>{children}</TutorialContext.Provider>
}
 
// Hook to use the context
export function useTutorialContext() {
  const context = useContext(TutorialContext)
  if (!context) {
    throw new Error('useTutorialContext must be used within a TutorialProvider')
  }
  return context
}
 
// Custom hooks for convenient access to specific context parts
export function useTutorialState() {
  const { state } = useTutorialContext()
  return state
}
 
export function useTutorialData() {
  const { tutorial, currentStep, expectedSteps, fullDecomposition } = useTutorialContext()
  return { tutorial, currentStep, expectedSteps, fullDecomposition }
}
 
export function useTutorialActions() {
  const {
    goToStep,
    goToNextStep,
    goToPreviousStep,
    handleValueChange,
    handleBeadClick,
    handleBeadRef,
    toggleDebugPanel,
    toggleStepList,
    toggleAutoAdvance,
    notifyEvent,
  } = useTutorialContext()

  return {
    goToStep,
    goToNextStep,
    goToPreviousStep,
    handleValueChange,
    handleBeadClick,
    handleBeadRef,
    toggleDebugPanel,
    toggleStepList,
    toggleAutoAdvance,
    notifyEvent,
  }
}
 
export function useTutorialHelpers() {
  const {
    getCurrentStepBeads,
    getCurrentStepSummary,
    renderHighlightedDecomposition,
    customStyles,
  } = useTutorialContext()

  return {
    getCurrentStepBeads,
    getCurrentStepSummary,
    renderHighlightedDecomposition,
    customStyles,
  }
}
 
export function useTutorialRefs() {
  const { isProgrammaticChange, beadRefs, showHelpForCurrentStep, setShowHelpForCurrentStep } =
    useTutorialContext()
  return {
    isProgrammaticChange,
    beadRefs,
    showHelpForCurrentStep,
    setShowHelpForCurrentStep,
  }
}
 
// Export types for use in other components
export type { TutorialPlayerState, TutorialPlayerAction, ExpectedStep }