All files / web/src/arcade-games/type-racer-jr/components PlayingPhase.tsx

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

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

import { useCallback, useEffect, useRef } from 'react'
import { css } from '../../../../styled-system/css'
import { useTypeRacerJr } from '../Provider'
import { useKeyboardInput } from '../hooks/useKeyboardInput'
import { useTypingTTS } from '../hooks/useTypingTTS'
import { LetterDisplay } from './LetterDisplay'
import { WordProgress } from './WordProgress'
import { TimerBar } from './TimerBar'
import { CelebrationBurst } from './CelebrationBurst'
import { OnScreenKeyboard } from './OnScreenKeyboard'
import { AbacusScoreCounter } from './AbacusScoreCounter'
import { StreakEffect } from './StreakEffect'

export function PlayingPhase() {
  const { state, localState, currentWord, typeLetter, endGame, dismissCelebration } =
    useTypeRacerJr()

  const tts = useTypingTTS()

  // Track previous values for transition detection
  const prevGamePhaseRef = useRef(state.gamePhase)
  const prevWordRef = useRef<string | null>(null)
  const prevCelebrationRef = useRef(false)
  const prevDifficultyRef = useRef(state.currentDifficulty)

  // TTS: speak on game start
  useEffect(() => {
    if (state.gamePhase === 'playing' && prevGamePhaseRef.current !== 'playing') {
      tts.speakGameStart()
    }
    prevGamePhaseRef.current = state.gamePhase
  }, [state.gamePhase, tts])

  // TTS: announce the word when it appears (say it, then spell for first few)
  // Only update prevWordRef when we actually speak — otherwise celebration
  // blocking causes us to "see" the word without speaking it, and then
  // when celebration clears the word is already marked as spoken.
  useEffect(() => {
    const wordText = currentWord?.word ?? null
    if (wordText && wordText !== prevWordRef.current && !localState.showCelebration) {
      tts.announceWord(wordText)
      prevWordRef.current = wordText
    }
  }, [currentWord?.word, localState.showCelebration, tts])

  // TTS: encourage on word completion
  useEffect(() => {
    if (localState.showCelebration && !prevCelebrationRef.current) {
      tts.speakWordComplete()
    }
    prevCelebrationRef.current = localState.showCelebration
  }, [localState.showCelebration, tts])

  // TTS: speak on difficulty advance
  useEffect(() => {
    if (state.currentDifficulty !== prevDifficultyRef.current) {
      tts.speakDifficultyAdvance()
    }
    prevDifficultyRef.current = state.currentDifficulty
  }, [state.currentDifficulty, tts])

  // Physical keyboard input
  const { hasPhysicalKeyboard } = useKeyboardInput({
    enabled: state.gamePhase === 'playing' && !localState.showCelebration,
    onKeyPress: typeLetter,
  })

  const handleTimerUp = useCallback(() => {
    endGame('timer-expired')
  }, [endGame])

  const handleTimerWarning = useCallback(() => {
    tts.speakTimerWarning()
  }, [tts])

  if (!currentWord && !localState.showCelebration) {
    return null
  }

  const wordNumber = state.completedWords.length + 1
  const totalWords = state.wordQueue.length

  return (
    <div
      data-component="PlayingPhase"
      className={css({
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '4',
        p: '4',
        flex: 1,
        position: 'relative',
      })}
    >
      {/* Timer bar for beat-the-clock */}
      {state.gameMode === 'beat-the-clock' && state.timeLimit && state.gameStartTime && (
        <TimerBar
          totalSeconds={state.timeLimit}
          startTime={state.gameStartTime}
          onTimeUp={handleTimerUp}
          onWarning={handleTimerWarning}
        />
      )}

      {/* Score overlay */}
      <div
        className={css({
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          width: '100%',
          maxWidth: '400px',
          fontSize: 'sm',
          color: 'gray.600',
        })}
      >
        <span>
          Word {wordNumber}/{totalWords}
        </span>
        <AbacusScoreCounter
          totalStars={state.totalStars}
          celebrate={state.consecutiveCleanWords >= 3}
        />
        <div className={css({ display: 'flex', alignItems: 'center', gap: '2' })}>
          {state.bestStreak > 1 && <span>🔥 {state.bestStreak}</span>}
          <button
            data-action="toggle-mute"
            onClick={tts.toggleMute}
            className={css({
              background: 'none',
              border: 'none',
              cursor: 'pointer',
              fontSize: 'lg',
              lineHeight: 1,
              p: '1',
              borderRadius: 'md',
              opacity: tts.isMuted ? 0.5 : 1,
              _hover: { bg: 'gray.100' },
            })}
            aria-label={tts.isMuted ? 'Unmute' : 'Mute'}
          >
            {tts.isMuted ? '🔇' : '🔊'}
          </button>
        </div>
      </div>

      {/* Streak-wrapped play area */}
      <StreakEffect streak={state.consecutiveCleanWords}>
        {/* Emoji */}
        {currentWord && (
          <div
            className={css({
              display: 'flex',
              justifyContent: 'center',
              fontSize: '80px',
              lineHeight: 1,
              animation: 'bob 2s ease-in-out infinite',
              userSelect: 'none',
            })}
          >
            {currentWord.emoji}
          </div>
        )}

        {/* Letter display */}
        {currentWord && (
          <div
            className={css({
              display: 'flex',
              gap: '2',
              flexWrap: 'wrap',
              justifyContent: 'center',
              mb: '2',
              mt: '4',
            })}
          >
            {currentWord.word.split('').map((letter, i) => {
              let letterState: 'upcoming' | 'current' | 'correct' | 'wrong'
              if (i < localState.currentLetterIndex) {
                letterState = 'correct'
              } else if (i === localState.currentLetterIndex) {
                // Check if last typed letter at this position was wrong
                const lastTyped = localState.typedLetters[localState.typedLetters.length - 1]
                letterState =
                  lastTyped && !lastTyped.correct && i === localState.currentLetterIndex
                    ? 'wrong'
                    : 'current'
              } else {
                letterState = 'upcoming'
              }
              return <LetterDisplay key={i} letter={letter} state={letterState} />
            })}
          </div>
        )}
      </StreakEffect>

      {/* Word progress */}
      {currentWord && (
        <WordProgress
          totalLetters={currentWord.word.length}
          completedLetters={localState.currentLetterIndex}
        />
      )}

      {/* Difficulty badge */}
      <div
        className={css({
          fontSize: 'xs',
          color: 'gray.500',
          bg: 'gray.100',
          px: '3',
          py: '1',
          borderRadius: 'full',
        })}
      >
        {state.currentDifficulty === 'level1'
          ? 'Easy'
          : state.currentDifficulty === 'level2'
            ? 'Medium'
            : 'Hard'}
      </div>

      {/* On-screen keyboard — shown on touch devices, or when user forces it on */}
      {(state.showVirtualKeyboard || !hasPhysicalKeyboard) &&
        !localState.showCelebration &&
        currentWord && (
          <OnScreenKeyboard
            onKeyPress={typeLetter}
            highlightedLetter={currentWord.word[localState.currentLetterIndex]}
            layout={state.keyboardLayout}
          />
        )}

      {/* Celebration overlay */}
      {localState.showCelebration && (
        <CelebrationBurst stars={localState.celebrationStars} onDone={dismissCelebration} />
      )}
    </div>
  )
}