All files / web/src/components/flowchart FlowchartWalker.tsx

0% Statements 0/1186
0% Branches 0/1
0% Functions 0/1
0% Lines 0/1186

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
'use client'

import { useState, useCallback, useMemo, useEffect, useRef } from 'react'
import { Logger } from '@soroban/llm-client'
import type {
  ExecutableFlowchart,
  FlowchartState,
  ProblemValue,
  DecisionNode,
  CheckpointNode,
} from '@/lib/flowcharts/schema'
import { useVisualDebugSafe } from '@/contexts/VisualDebugContext'
import {
  initializeState,
  getNextNode,
  isDecisionCorrect,
  validateCheckpoint,
  applyStateUpdate,
  applyWorkingProblemUpdate,
  advanceState,
  isTerminal,
  formatProblemDisplay,
  createContextFromState,
  applyTransforms,
} from '@/lib/flowcharts/loader'
import { evaluate } from '@/lib/flowcharts/evaluator'
import { css } from '../../../styled-system/css'
import { vstack, hstack } from '../../../styled-system/patterns'
import { FlowchartNodeContent } from './FlowchartNodeContent'
import { FlowchartCheckpoint } from './FlowchartCheckpoint'
import { FlowchartPhaseRail } from './FlowchartPhaseRail'
import { FlowchartDecisionGraph } from './FlowchartDecisionGraph'
import { MathDisplay } from './MathDisplay'
import { TimeMachineHistory } from './TimeMachineHistory'
import { DebugStepTimeline } from './DebugStepTimeline'
import { DebugMermaidDiagram } from './DebugMermaidDiagram'

// =============================================================================
// Types
// =============================================================================

type WalkerPhase =
  | { type: 'showingNode' }
  | { type: 'awaitingDecision' }
  | { type: 'awaitingCheckpoint' }
  | {
      type: 'checkpointFeedback'
      correct: boolean
      expected: ProblemValue | [number, number]
      userAnswer: ProblemValue | [number, number]
    }
  | { type: 'complete' }

/** Track wrong decision for feedback (includes attempt counter to re-trigger animations) */
interface WrongDecisionState {
  value: string
  correctValue: string
  attempt: number
}

interface FlowchartWalkerProps {
  flowchart: ExecutableFlowchart
  problemInput: Record<string, ProblemValue>
  onComplete?: (state: FlowchartState) => void
  /** Called when user wants to try a different problem (same flowchart) */
  onRestart?: () => void
  /** Called when user wants to go back to problem selection */
  onChangeProblem?: () => void
}

// =============================================================================
// Component
// =============================================================================

/**
 * FlowchartWalker - Main component for walking through a flowchart step by step.
 *
 * Manages state, navigation, and validation as the user progresses through
 * instruction, decision, and checkpoint nodes.
 */
export function FlowchartWalker({
  flowchart,
  problemInput,
  onComplete,
  onRestart,
  onChangeProblem,
}: FlowchartWalkerProps) {
  // Initialize state and apply transforms for entry node
  const [state, setState] = useState<FlowchartState>(() => {
    const initialState = initializeState(flowchart, problemInput)
    // Apply transforms for the entry node
    return applyTransforms(initialState, initialState.currentNode, flowchart)
  })

  const [phase, setPhase] = useState<WalkerPhase>({ type: 'showingNode' })
  const [wrongAttempts, setWrongAttempts] = useState(0)
  const [wrongDecision, setWrongDecision] = useState<WrongDecisionState | null>(null)
  // History stack for back navigation (stores full state snapshots)
  const [stateHistory, setStateHistory] = useState<FlowchartState[]>([])
  // Redo stack for forward navigation (when user goes back)
  const [redoStack, setRedoStack] = useState<FlowchartState[]>([])
  // Track checked checklist items for the current node
  const [checkedItems, setCheckedItems] = useState<Set<number>>(new Set())
  // Debug mode: pause auto-advance to inspect nodes
  const [autoAdvancePaused, setAutoAdvancePaused] = useState(false)
  // Feedback state for wrong decision answers
  const [showDecisionFeedback, setShowDecisionFeedback] = useState(false)
  // Track browser history depth for this walker session
  const historyDepthRef = useRef(0)
  // Flag to prevent double-handling when we programmatically go back
  const isNavigatingBackRef = useRef(false)

  // Visual debug mode
  const { isVisualDebugEnabled } = useVisualDebugSafe()

  // Create logger that is enabled when visual debug mode is on
  const logger = useMemo(
    () =>
      new Logger({
        enabled: isVisualDebugEnabled,
        minLevel: 'info',
      }),
    [isVisualDebugEnabled]
  )

  // Log state changes when visual debug mode is enabled
  useEffect(() => {
    logger.info('State snapshots updated', { snapshots: state.snapshots })
    logger.info('Accumulated values', { values: state.values })
  }, [logger, state.snapshots, state.values])

  // Current node
  const currentNode = useMemo(
    () => flowchart.nodes[state.currentNode],
    [flowchart.nodes, state.currentNode]
  )

  // Check if current node has an interactive checklist
  const currentChecklist = currentNode?.content?.checklist
  const hasInteractiveChecklist =
    currentNode?.definition.type === 'instruction' &&
    currentChecklist &&
    currentChecklist.length > 0

  // Build timeline steps for visual debug mode
  const timelineSteps = useMemo(() => {
    if (!isVisualDebugEnabled) return []

    const steps: Array<{ state: FlowchartState; nodeTitle: string }> = []

    // Add states from history (past steps)
    for (const s of stateHistory) {
      const node = flowchart.nodes[s.currentNode]
      steps.push({
        state: s,
        nodeTitle: node?.content?.title || s.currentNode,
      })
    }

    // Add current state
    steps.push({
      state,
      nodeTitle: currentNode?.content?.title || state.currentNode,
    })

    // Add states from redo stack (future steps) - reversed so oldest redo is first
    for (const s of redoStack.slice().reverse()) {
      const node = flowchart.nodes[s.currentNode]
      steps.push({
        state: s,
        nodeTitle: node?.content?.title || s.currentNode,
      })
    }

    return steps
  }, [isVisualDebugEnabled, stateHistory, state, redoStack, flowchart.nodes, currentNode])

  // Reset checked items when node changes
  useEffect(() => {
    setCheckedItems(new Set())
  }, [state.currentNode])

  // Handle wrong decision feedback timer
  useEffect(() => {
    if (wrongDecision) {
      setShowDecisionFeedback(true)
      const timer = setTimeout(() => setShowDecisionFeedback(false), 1500)
      return () => clearTimeout(timer)
    }
  }, [wrongDecision?.attempt])

  // Browser history integration - allow back button to go to previous step
  useEffect(() => {
    const handlePopState = () => {
      // If we have history to go back to, go back
      if (historyDepthRef.current > 0 && stateHistory.length > 0) {
        historyDepthRef.current--
        isNavigatingBackRef.current = true

        // Push current state to redo stack before going back
        setState((currentState) => {
          setRedoStack((prev) => [...prev, currentState])
          return currentState
        })

        const previousState = stateHistory[stateHistory.length - 1]
        setStateHistory((prev) => prev.slice(0, -1))
        setState(previousState)
        setPhase({ type: 'showingNode' })
        setWrongAttempts(0)
        setWrongDecision(null)
        setCheckedItems(new Set())

        isNavigatingBackRef.current = false
      } else if (historyDepthRef.current === 0) {
        // At the beginning - let browser handle it (go to problem selection)
        // Push a dummy state to prevent actually navigating away, then call onChangeProblem
        if (onChangeProblem) {
          onChangeProblem()
        }
      }
    }

    window.addEventListener('popstate', handlePopState)
    return () => window.removeEventListener('popstate', handlePopState)
  }, [stateHistory, onChangeProblem])

  // Problem display
  const problemDisplay = formatProblemDisplay(flowchart, state.problem)

  // =============================================================================
  // Navigation
  // =============================================================================

  const advanceToNext = useCallback(
    (userChoice?: string, userInput?: ProblemValue, correct?: boolean) => {
      const nextNodeId = getNextNode(flowchart, state, userChoice)

      if (!nextNodeId) {
        // No next node - might be terminal
        if (isTerminal(flowchart, state.currentNode)) {
          setPhase({ type: 'complete' })
          onComplete?.(state)
        }
        return
      }

      const action =
        currentNode?.definition.type === 'decision'
          ? 'decision'
          : currentNode?.definition.type === 'checkpoint'
            ? 'checkpoint'
            : 'advance'

      // Save current state to history before advancing
      setStateHistory((prev) => [...prev, state])

      // Clear redo stack - user has made a new choice, branching invalidates redo
      setRedoStack([])

      // Push browser history entry so back button works
      historyDepthRef.current++
      window.history.pushState({ flowchartStep: historyDepthRef.current }, '')

      // Apply working problem update if configured (before advancing)
      let stateWithWorkingProblem = state
      if (correct !== false) {
        stateWithWorkingProblem = applyWorkingProblemUpdate(
          state,
          state.currentNode,
          flowchart,
          userInput
        )
      }

      // Advance state to next node
      let newState = advanceState(stateWithWorkingProblem, nextNodeId, action, userInput, correct)

      // Apply transforms for the new node (new unified computation model)
      newState = applyTransforms(newState, nextNodeId, flowchart)

      logger.info('Advancing to node', {
        from: state.currentNode,
        to: nextNodeId,
        action,
        userInput,
        correct,
        values: newState.values,
      })

      setState(newState)
      setPhase({ type: 'showingNode' })
      setWrongAttempts(0)
      setWrongDecision(null)

      // Check if new node is terminal
      if (isTerminal(flowchart, nextNodeId)) {
        // If auto-advance is paused, don't auto-complete - let user inspect the terminal node
        if (!autoAdvancePaused) {
          setTimeout(() => {
            setPhase({ type: 'complete' })
            onComplete?.(newState)
          }, 500)
        }
      }
    },
    [flowchart, state, currentNode, onComplete, autoAdvancePaused, logger]
  )

  // Auto-advance for embellishment and milestone nodes
  // Using useEffect ensures proper cleanup and prevents multiple timeouts on re-renders
  useEffect(() => {
    if (!currentNode || autoAdvancePaused) return

    const nodeType = currentNode.definition.type
    if (nodeType === 'embellishment') {
      const timer = setTimeout(() => advanceToNext(), 800)
      return () => clearTimeout(timer)
    } else if (nodeType === 'milestone') {
      const timer = setTimeout(() => advanceToNext(), 500)
      return () => clearTimeout(timer)
    }
  }, [currentNode, autoAdvancePaused, advanceToNext])

  // Go back to the previous step (uses browser history so back button stays in sync)
  const goBack = useCallback(() => {
    if (stateHistory.length === 0 || historyDepthRef.current === 0) {
      // No history - go back to problem selection
      onChangeProblem?.()
      return
    }

    // Use browser's back to trigger popstate, which handles the state update
    window.history.back()
  }, [stateHistory, onChangeProblem])

  // Go forward to the next step (from redo stack) - for visual debug mode
  const goForward = useCallback(() => {
    if (redoStack.length === 0) return

    // Push current state to history
    setStateHistory((prev) => [...prev, state])

    // Pop next state from redo stack
    const nextState = redoStack[redoStack.length - 1]
    setRedoStack((prev) => prev.slice(0, -1))
    setState(nextState)
    setPhase({ type: 'showingNode' })
    setWrongAttempts(0)
    setWrongDecision(null)
    setCheckedItems(new Set())

    historyDepthRef.current++
    window.history.pushState({ flowchartStep: historyDepthRef.current }, '')
  }, [redoStack, state])

  // Navigate to a specific step in the full timeline (for visual debug mode)
  // The timeline is: stateHistory + [current] + redoStack (reversed)
  const navigateToHistoryStep = useCallback(
    (targetIndex: number) => {
      // Build full timeline: stateHistory + [current] + redoStack (reversed)
      const fullTimeline = [...stateHistory, state, ...redoStack.slice().reverse()]
      const currentIndex = stateHistory.length

      if (targetIndex === currentIndex) return // Already there
      if (targetIndex < 0 || targetIndex >= fullTimeline.length) return

      const targetState = fullTimeline[targetIndex]
      if (!targetState) return

      // Calculate new stateHistory (everything before target)
      const newHistory = fullTimeline.slice(0, targetIndex)
      // Calculate new redoStack (everything after target, reversed back)
      const newRedo = fullTimeline.slice(targetIndex + 1).reverse()

      setStateHistory(newHistory)
      setRedoStack(newRedo)
      setState(targetState)
      setPhase({ type: 'showingNode' })
      setWrongAttempts(0)
      setWrongDecision(null)
      setCheckedItems(new Set())

      // Update browser history depth to match
      historyDepthRef.current = targetIndex
      window.history.replaceState({ flowchartStep: historyDepthRef.current }, '')
    },
    [stateHistory, state, redoStack]
  )

  // Debug skip - auto-advance through the current node (for visual debug mode)
  // For decision nodes: picks the first option
  // For checkpoint nodes: computes and submits the correct answer
  // For instruction nodes: just advances
  const debugSkipStep = useCallback(() => {
    if (!currentNode) return

    const def = currentNode.definition

    switch (def.type) {
      case 'instruction':
      case 'milestone':
      case 'embellishment':
        // Just advance
        advanceToNext()
        break

      case 'decision': {
        // Pick the first option
        const decisionDef = def as DecisionNode
        if (decisionDef.options.length > 0) {
          const firstOption = decisionDef.options[0]
          advanceToNext(firstOption.value, firstOption.value, true)
        }
        break
      }

      case 'checkpoint': {
        // Compute the correct answer and submit it
        const checkpointDef = def as CheckpointNode
        try {
          const context = createContextFromState(state)

          if (checkpointDef.inputType === 'two-numbers' && Array.isArray(checkpointDef.expected)) {
            // Two-number checkpoint
            const twoNumberAnswer: [number, number] = [
              evaluate(checkpointDef.expected[0], context) as number,
              evaluate(checkpointDef.expected[1], context) as number,
            ]
            const newState = applyStateUpdate(
              state,
              state.currentNode,
              flowchart,
              twoNumberAnswer as unknown as ProblemValue
            )
            setState(newState)
            advanceToNext(undefined, twoNumberAnswer as unknown as ProblemValue, true)
          } else if (typeof checkpointDef.expected === 'string') {
            // Single value checkpoint - expected is a string expression
            const correctAnswer = evaluate(checkpointDef.expected, context) as number
            const newState = applyStateUpdate(state, state.currentNode, flowchart, correctAnswer)
            setState(newState)
            advanceToNext(undefined, correctAnswer, true)
          } else {
            // Shouldn't reach here, but just advance if we do
            advanceToNext()
          }
        } catch {
          // If we can't compute the answer, just try to advance
          advanceToNext()
        }
        break
      }

      case 'terminal':
        // Complete
        setPhase({ type: 'complete' })
        onComplete?.(state)
        break

      default:
        advanceToNext()
    }
  }, [currentNode, state, flowchart, advanceToNext, onComplete])

  // Check if we can skip (not at terminal)
  const canDebugSkip = useMemo(() => {
    if (!currentNode) return false
    return !isTerminal(flowchart, state.currentNode)
  }, [currentNode, flowchart, state.currentNode])

  // Get decision options for current node if it's a decision
  const decisionOptions = useMemo(() => {
    const node = flowchart.nodes[state.currentNode]
    if (!node || node.definition.type !== 'decision') return null

    const def = node.definition as DecisionNode
    return def.options.map((opt) => {
      const nextNode = flowchart.nodes[opt.next]
      return {
        label: opt.label,
        value: opt.value,
        pathLabel: opt.pathLabel,
        leadsTo: nextNode?.content?.title || opt.next,
      }
    })
  }, [flowchart.nodes, state.currentNode])

  // Navigate to a specific step in the working problem history
  // Clicking on ledger entry i takes you to the state right after that entry was created
  const navigateToStep = useCallback(
    (targetIndex: number) => {
      // If clicking the latest entry, do nothing
      if (targetIndex >= state.workingProblemHistory.length - 1) {
        return
      }

      // Find the state in history where workingProblemHistory.length === targetIndex + 1
      // This is the state right after that entry was created, before any further advances
      const targetHistoryIndex = stateHistory.findIndex(
        (s) => s.workingProblemHistory.length === targetIndex + 1
      )

      if (targetHistoryIndex !== -1) {
        // Found exact match - restore that state
        const targetState = stateHistory[targetHistoryIndex]
        setStateHistory((prev) => prev.slice(0, targetHistoryIndex))
        setState(targetState)
      } else {
        // Fallback: find the first state with at least targetIndex + 1 entries
        // and manually truncate the workingProblemHistory
        const fallbackIndex = stateHistory.findIndex(
          (s) => s.workingProblemHistory.length > targetIndex
        )

        if (fallbackIndex !== -1) {
          const baseState = stateHistory[fallbackIndex]
          const restoredState: FlowchartState = {
            ...baseState,
            workingProblemHistory: baseState.workingProblemHistory.slice(0, targetIndex + 1),
          }
          setStateHistory((prev) => prev.slice(0, fallbackIndex))
          setState(restoredState)
        }
      }

      setPhase({ type: 'showingNode' })
      setWrongAttempts(0)
      setWrongDecision(null)
    },
    [state.workingProblemHistory.length, stateHistory]
  )

  // =============================================================================
  // Handlers
  // =============================================================================

  const handleInstructionAdvance = useCallback(() => {
    advanceToNext()
  }, [advanceToNext])

  const handleDecisionSelect = useCallback(
    (value: string) => {
      const correct = isDecisionCorrect(flowchart, state, state.currentNode, value)

      logger.info('Decision selected', {
        nodeId: state.currentNode,
        selectedValue: value,
        correct,
      })

      if (correct === null || correct === true) {
        // No validation defined or correct answer
        setWrongDecision(null)
        advanceToNext(value, value, true)
      } else {
        // Wrong answer - find correct value for feedback
        const node = flowchart.nodes[state.currentNode]
        const def = node?.definition
        let correctValue = ''
        if (def?.type === 'decision') {
          for (const opt of def.options) {
            if (isDecisionCorrect(flowchart, state, state.currentNode, opt.value) === true) {
              correctValue = opt.value
              break
            }
          }
        }

        setWrongAttempts((prev) => prev + 1)
        setState((prev) => ({ ...prev, mistakes: prev.mistakes + 1 }))
        // Set wrongDecision with incremented attempt to re-trigger animation
        setWrongDecision((prev) => ({
          value,
          correctValue,
          attempt: (prev?.attempt ?? 0) + 1,
        }))
      }
    },
    [flowchart, state, advanceToNext, logger]
  )

  const handleCheckpointSubmit = useCallback(
    (value: number | string | [number, number]) => {
      const result = validateCheckpoint(flowchart, state, state.currentNode, value)

      logger.info('Checkpoint submitted', {
        nodeId: state.currentNode,
        userValue: value,
        expected: result?.expected,
        correct: result?.correct ?? true,
      })

      if (result === null || result.correct) {
        // No validation or correct
        const newState = applyStateUpdate(
          state,
          state.currentNode,
          flowchart,
          value as ProblemValue
        )
        setState(newState)
        setPhase({
          type: 'checkpointFeedback',
          correct: true,
          expected: result?.expected ?? value,
          userAnswer: value,
        })
        // Auto-advance after short delay (unless auto-advance is paused)
        if (!autoAdvancePaused) {
          setTimeout(() => {
            advanceToNext(undefined, value as ProblemValue, true)
          }, 1000)
        }
      } else {
        // Wrong answer
        setWrongAttempts((prev) => prev + 1)
        setState((prev) => ({ ...prev, mistakes: prev.mistakes + 1 }))
        setPhase({
          type: 'checkpointFeedback',
          correct: false,
          expected: result.expected,
          userAnswer: value,
        })
      }
    },
    [flowchart, state, advanceToNext, autoAdvancePaused, logger]
  )

  const handleChecklistToggle = useCallback(
    (index: number) => {
      setCheckedItems((prev) => {
        const next = new Set(prev)
        if (next.has(index)) {
          next.delete(index)
        } else {
          next.add(index)
        }

        // Check if all items are now checked - if so, auto-advance (unless auto-advance is paused)
        const totalItems = currentChecklist?.length ?? 0
        if (next.size === totalItems && totalItems > 0 && !autoAdvancePaused) {
          // Small delay so the user sees the final checkbox check
          setTimeout(() => {
            advanceToNext()
          }, 300)
        }

        return next
      })
    },
    [currentChecklist, advanceToNext, autoAdvancePaused]
  )

  // =============================================================================
  // Determine what to show based on node type and phase
  // =============================================================================

  const renderNodeInteraction = () => {
    if (!currentNode) return null

    const def = currentNode.definition

    switch (def.type) {
      case 'instruction':
        // If there's an interactive checklist, don't show the button - checking all items advances
        if (hasInteractiveChecklist) {
          return null
        }
        return (
          <button
            data-testid="instruction-advance-button"
            onClick={handleInstructionAdvance}
            className={css({
              paddingY: '4',
              paddingX: '8',
              fontSize: 'lg',
              fontWeight: 'semibold',
              borderRadius: 'lg',
              backgroundColor: { base: 'green.500', _dark: 'green.600' },
              color: 'white',
              cursor: 'pointer',
              transition: 'all 0.2s',
              _hover: {
                backgroundColor: { base: 'green.600', _dark: 'green.500' },
                transform: 'scale(1.02)',
              },
              _active: {
                transform: 'scale(0.98)',
              },
            })}
          >
            I did it!
          </button>
        )

      case 'decision':
        // Decision is rendered in the FlowchartPhaseRail as a flowchart-style graph
        // No interaction needed here
        return null

      case 'checkpoint': {
        const checkpointDef = def as CheckpointNode
        const showHint = wrongAttempts >= 2
        const isTwoNumbers = checkpointDef.inputType === 'two-numbers'

        // Pre-compute expected values for immediate per-field validation
        let expectedValues: number | [number, number] | undefined
        try {
          const context = createContextFromState(state)
          if (isTwoNumbers && Array.isArray(checkpointDef.expected)) {
            expectedValues = [
              evaluate(checkpointDef.expected[0], context) as number,
              evaluate(checkpointDef.expected[1], context) as number,
            ]
          } else if (
            checkpointDef.inputType === 'number' &&
            typeof checkpointDef.expected === 'string'
          ) {
            // Only pre-compute if the expression doesn't reference user input
            if (!checkpointDef.expected.includes('input')) {
              expectedValues = evaluate(checkpointDef.expected, context) as number
            }
          }
        } catch {
          // Can't pre-compute, fall back to validate-on-submit
          expectedValues = undefined
        }

        // Format feedback values based on input type
        const formatFeedback = () => {
          if (isTwoNumbers) {
            return {
              expected:
                phase.type === 'checkpointFeedback'
                  ? (phase.expected as [number, number])
                  : undefined,
              userAnswer:
                phase.type === 'checkpointFeedback'
                  ? (phase.userAnswer as [number, number])
                  : undefined,
            }
          }
          return {
            expected: phase.type === 'checkpointFeedback' ? String(phase.expected) : undefined,
            userAnswer: phase.type === 'checkpointFeedback' ? String(phase.userAnswer) : undefined,
          }
        }

        // Format hint text
        const getHintText = () => {
          if (!showHint || phase.type !== 'checkpointFeedback') return undefined
          if (isTwoNumbers && Array.isArray(phase.expected)) {
            return `Hint: The answers are ${phase.expected[0]} and ${phase.expected[1]}`
          }
          return `Hint: The answer is ${phase.expected}`
        }

        if (phase.type === 'checkpointFeedback') {
          if (phase.correct) {
            return (
              <div
                data-testid="checkpoint-correct-feedback"
                className={css({
                  padding: '4',
                  backgroundColor: { base: 'green.100', _dark: 'green.800' },
                  borderRadius: 'lg',
                  color: { base: 'green.800', _dark: 'green.200' },
                  fontSize: 'lg',
                  fontWeight: 'semibold',
                  textAlign: 'center',
                })}
              >
                Correct! Moving on...
              </div>
            )
          }

          // Show checkpoint ready for retry with passive feedback message
          const feedbackMessage = isTwoNumbers
            ? 'Not quite - check the denominators and try again'
            : `Not quite (you entered ${phase.userAnswer}) - try again`

          return (
            <div data-testid="checkpoint-wrong-feedback" className={vstack({ gap: '3' })}>
              {/* Passive feedback message */}
              <div
                className={css({
                  paddingY: '2',
                  paddingX: '3',
                  borderRadius: 'md',
                  backgroundColor: { base: 'orange.100', _dark: 'orange.900' },
                  color: { base: 'orange.800', _dark: 'orange.200' },
                  fontSize: 'sm',
                  textAlign: 'center',
                })}
              >
                {feedbackMessage}
                {showHint && (
                  <span className={css({ display: 'block', marginTop: '1', fontWeight: 'medium' })}>
                    {getHintText()}
                  </span>
                )}
              </div>
              {/* Checkpoint ready for immediate retry - no feedback prop so inputs are fresh */}
              <FlowchartCheckpoint
                prompt={checkpointDef.prompt}
                inputType={checkpointDef.inputType}
                inputLabels={checkpointDef.inputLabels}
                onSubmit={handleCheckpointSubmit}
                expectedValues={expectedValues}
                orderMatters={checkpointDef.orderMatters}
              />
            </div>
          )
        }

        return (
          <FlowchartCheckpoint
            prompt={checkpointDef.prompt}
            inputType={checkpointDef.inputType}
            inputLabels={checkpointDef.inputLabels}
            onSubmit={handleCheckpointSubmit}
            expectedValues={expectedValues}
            orderMatters={checkpointDef.orderMatters}
          />
        )
      }

      case 'milestone':
        // Auto-advance handled by useEffect above
        return (
          <div
            data-testid="milestone-display"
            className={css({
              fontSize: '4xl',
              textAlign: 'center',
            })}
          >
            {currentNode.content.title}
          </div>
        )

      case 'embellishment':
        // Auto-advance handled by useEffect above
        // Display is handled in the content card, nothing needed here
        return null

      case 'terminal':
        return null // Handled by complete phase

      default:
        return null
    }
  }

  // =============================================================================
  // Render
  // =============================================================================

  if (phase.type === 'complete') {
    return (
      <div
        data-testid="completion-screen"
        data-mistakes={state.mistakes}
        className={vstack({
          gap: '6',
          padding: '8',
          alignItems: 'center',
          justifyContent: 'center',
          minHeight: '400px',
        })}
      >
        <div data-testid="celebration-emoji" className={css({ fontSize: '6xl' })}>
          🎉
        </div>
        <h2
          className={css({
            fontSize: '2xl',
            fontWeight: 'bold',
            color: { base: 'green.700', _dark: 'green.300' },
          })}
        >
          Great job!
        </h2>
        <p className={css({ color: { base: 'gray.600', _dark: 'gray.400' } })}>
          You completed the problem: {problemDisplay}
        </p>
        <p className={css({ color: { base: 'gray.500', _dark: 'gray.500' }, fontSize: 'sm' })}>
          {state.mistakes === 0
            ? 'Perfect - no mistakes!'
            : `Finished with ${state.mistakes} mistake${state.mistakes === 1 ? '' : 's'}`}
        </p>
        {onRestart && (
          <button
            data-testid="restart-button"
            onClick={onRestart}
            className={css({
              paddingY: '3',
              paddingX: '6',
              fontSize: 'lg',
              fontWeight: 'semibold',
              borderRadius: 'lg',
              backgroundColor: { base: 'blue.500', _dark: 'blue.600' },
              color: 'white',
              cursor: 'pointer',
              marginTop: '4',
            })}
          >
            Try another problem
          </button>
        )}
      </div>
    )
  }

  // Can go back if there's history OR if we can go to problem selection
  const canGoBack = stateHistory.length > 0 || onChangeProblem

  const handleDecisionOptionClick = (value: string) => {
    if (showDecisionFeedback) return
    handleDecisionSelect(value)
  }

  return (
    <div
      data-testid="flowchart-walker"
      data-current-node={state.currentNode}
      data-phase={phase.type}
      className={css({
        display: 'flex',
        flexDirection: 'column',
        minHeight: '100vh',
        backgroundColor: { base: 'gray.50', _dark: 'gray.900' },
      })}
    >
      {/* Top bar: Phase Rail (centered) + Back/New buttons (right side) */}
      {/* Note: Hamburger menu is handled by parent page in top-left corner */}
      <header
        data-testid="walker-header"
        className={css({
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          paddingY: '3',
          paddingX: '4',
          // Leave space for floating hamburger menu on the left
          paddingLeft: '70px',
          backgroundColor: { base: 'white', _dark: 'gray.800' },
          borderBottom: '1px solid',
          borderColor: { base: 'gray.200', _dark: 'gray.700' },
          position: 'relative',
        })}
      >
        {/* Compact Phase Rail - centered */}
        <FlowchartPhaseRail flowchart={flowchart} state={state} compact={true} />

        {/* Right side controls: Back + New Problem */}
        <div
          className={css({
            position: 'absolute',
            right: '16px',
            top: '50%',
            transform: 'translateY(-50%)',
            display: 'flex',
            alignItems: 'center',
            gap: '2',
          })}
        >
          {/* Back button - for step navigation within flowchart */}
          {stateHistory.length > 0 && (
            <button
              data-testid="back-button"
              onClick={goBack}
              className={css({
                display: 'flex',
                alignItems: 'center',
                gap: '1',
                padding: '1.5 2.5',
                fontSize: 'sm',
                fontWeight: 'medium',
                color: { base: 'gray.600', _dark: 'gray.400' },
                backgroundColor: 'transparent',
                border: 'none',
                borderRadius: 'md',
                cursor: 'pointer',
                transition: 'all 0.15s',
                _hover: {
                  color: { base: 'gray.900', _dark: 'gray.200' },
                  backgroundColor: { base: 'gray.100', _dark: 'gray.700' },
                },
              })}
            >
              <span className={css({ fontSize: 'md' })}>←</span>
              <span className={css({ display: { base: 'none', sm: 'inline' } })}>Back</span>
            </button>
          )}

          {/* New Problem button */}
          {onChangeProblem && (
            <button
              data-testid="change-problem-button"
              onClick={onChangeProblem}
              className={css({
                padding: '1.5 2.5',
                fontSize: 'sm',
                fontWeight: 'medium',
                color: { base: 'blue.600', _dark: 'blue.400' },
                backgroundColor: 'transparent',
                border: 'none',
                borderRadius: 'md',
                cursor: 'pointer',
                transition: 'all 0.15s',
                _hover: {
                  backgroundColor: { base: 'blue.50', _dark: 'blue.900/30' },
                },
              })}
            >
              <span className={css({ display: { base: 'none', sm: 'inline' } })}>New Problem</span>
              <span className={css({ display: { base: 'inline', sm: 'none' } })}>New</span>
            </button>
          )}
        </div>
      </header>

      {/* Debug step timeline - only visible when visual debug mode is enabled */}
      {isVisualDebugEnabled && timelineSteps.length > 0 && (
        <DebugStepTimeline
          steps={timelineSteps}
          currentIndex={stateHistory.length}
          onNavigate={navigateToHistoryStep}
          canGoBack={stateHistory.length > 0}
          canGoForward={redoStack.length > 0}
          canSkip={canDebugSkip}
          onBack={goBack}
          onForward={goForward}
          onSkip={debugSkipStep}
          autoAdvancePaused={autoAdvancePaused}
          onToggleAutoAdvance={() => setAutoAdvancePaused((prev) => !prev)}
        />
      )}

      {/* Debug mermaid diagram - shows flowchart with current node highlighted */}
      {isVisualDebugEnabled && flowchart.rawMermaid && (
        <DebugMermaidDiagram
          mermaidContent={flowchart.rawMermaid}
          currentNodeId={state.currentNode}
        />
      )}

      {/* Main content - centered column */}
      <main
        data-testid="main-content-area"
        className={css({
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          padding: '4',
          paddingTop: '6',
          gap: '5',
          maxWidth: '700px',
          width: '100%',
          margin: '0 auto',
        })}
      >
        {/* Instructions section - node content above the Time Machine */}
        {currentNode?.definition.type !== 'milestone' &&
          currentNode?.definition.type !== 'embellishment' &&
          currentNode?.definition.type !== 'decision' && (
            <div
              data-testid="instructions-section"
              data-node-type={currentNode?.definition.type}
              className={css({
                width: '100%',
                paddingY: '4',
                paddingX: '5',
                backgroundColor: { base: 'white', _dark: 'gray.800' },
                borderRadius: 'xl',
                boxShadow: 'md',
                border: '1px solid',
                borderColor: { base: 'gray.200', _dark: 'gray.700' },
              })}
            >
              {currentNode && (
                <FlowchartNodeContent
                  content={currentNode.content}
                  checkedItems={hasInteractiveChecklist ? checkedItems : undefined}
                  onChecklistToggle={hasInteractiveChecklist ? handleChecklistToggle : undefined}
                />
              )}
            </div>
          )}

        {/* Embellishment display - animated emoji */}
        {currentNode?.definition.type === 'embellishment' && (
          <div
            data-testid="embellishment-display"
            className={css({
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              minHeight: '120px',
            })}
          >
            <span
              className={css({
                fontSize: '6xl',
                animation: 'embellishmentPop 0.6s ease-out',
              })}
            >
              {currentNode.content.title}
            </span>
          </div>
        )}

        {/* Milestone display */}
        {currentNode?.definition.type === 'milestone' && (
          <div
            data-testid="milestone-display"
            className={css({
              fontSize: '5xl',
              textAlign: 'center',
              padding: '6',
            })}
          >
            {currentNode.content.title}
          </div>
        )}

        {/* TIME MACHINE: Problem evolution stack - the hero of the page */}
        {state.workingProblemHistory.length > 0 && (
          <TimeMachineHistory
            history={state.workingProblemHistory}
            onNavigate={navigateToStep}
            fontSize="xl"
          />
        )}

        {/* Decision graph - when at a decision node */}
        {decisionOptions && currentNode?.definition.type === 'decision' && (
          <div
            data-testid="decision-area"
            data-element="decision-graph-container"
            data-option-count={decisionOptions.length}
            className={css({
              width: '100%',
              maxWidth: '500px',
            })}
          >
            <FlowchartDecisionGraph
              nodeTitle={currentNode.content?.title || 'Choose'}
              nodeBody={currentNode.content?.body || []}
              options={decisionOptions.map((opt) => ({
                label: opt.label,
                value: opt.value,
                pathLabel: opt.pathLabel,
                leadsTo: opt.leadsTo,
              }))}
              onSelect={handleDecisionOptionClick}
              wrongAnswer={showDecisionFeedback ? wrongDecision?.value : undefined}
              correctAnswer={showDecisionFeedback ? wrongDecision?.correctValue : undefined}
              disabled={showDecisionFeedback}
              hasPreviousNode={state.history.length > 0}
            />
          </div>
        )}

        {/* Interaction area: Checkpoint / "I did it" button */}
        {currentNode?.definition.type !== 'decision' && (
          <div
            data-testid="interaction-area"
            className={css({
              display: 'flex',
              justifyContent: 'center',
              width: '100%',
              maxWidth: '400px',
            })}
          >
            {renderNodeInteraction()}
          </div>
        )}
      </main>
    </div>
  )
}