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

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

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

import { useEffect, useRef } from 'react'
import { useTTS } from '@/hooks/useTTS'
import {
  ENCOURAGING_CLIPS,
  OFFERING_HELP_CLIPS,
  TRY_USING_HELP,
} from '@/lib/audio/clips/assistance'
import type { AssistanceStateName } from './useProgressiveAssistance'

interface UsePracticeAssistanceAudioOptions {
  assistanceState: AssistanceStateName
  showWrongAnswerSuggestion: boolean
  replayProblem: () => void
}

function pickRandom<T>(arr: readonly T[]): T {
  return arr[Math.floor(Math.random() * arr.length)]
}

/**
 * Speaks audio cues when the progressive assistance state machine transitions.
 *
 * Escalation is gentle:
 * - idle → encouraging: silent replay of the problem (no spoken text)
 * - encouraging → offeringHelp: spoken "Need some help?" prompt
 * - showWrongAnswerSuggestion becomes true: spoken "This is tricky!" prompt
 */
export function usePracticeAssistanceAudio({
  assistanceState,
  showWrongAnswerSuggestion,
  replayProblem,
}: UsePracticeAssistanceAudioOptions) {
  const prevStateRef = useRef<AssistanceStateName>(assistanceState)
  const prevWrongSuggestionRef = useRef(showWrongAnswerSuggestion)

  // Pre-register clips so they can be collected/preloaded
  const sayOfferingHelp = useTTS(pickRandom(OFFERING_HELP_CLIPS), {
    tone: 'encouragement',
  })
  const sayTryUsingHelp = useTTS(TRY_USING_HELP, {
    tone: 'encouragement',
  })

  useEffect(() => {
    const prevState = prevStateRef.current
    const prevWrong = prevWrongSuggestionRef.current
    prevStateRef.current = assistanceState
    prevWrongSuggestionRef.current = showWrongAnswerSuggestion

    // idle → encouraging: replay the problem audio (subtle nudge, no spoken text)
    if (prevState === 'idle' && assistanceState === 'encouraging') {
      replayProblem()
      return
    }

    // encouraging → offeringHelp: speak a help prompt
    if (prevState === 'encouraging' && assistanceState === 'offeringHelp') {
      sayOfferingHelp(pickRandom(OFFERING_HELP_CLIPS))
      return
    }

    // Wrong answer suggestion just appeared: speak "try using help"
    if (!prevWrong && showWrongAnswerSuggestion) {
      sayTryUsingHelp()
      return
    }
  }, [assistanceState, showWrongAnswerSuggestion, replayProblem, sayOfferingHelp, sayTryUsingHelp])
}