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

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

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

import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useTTS } from '@/hooks/useTTS'
import { useAudioManager } from '@/hooks/useAudioManager'
import { termsToClipIds } from '@/lib/audio/termsToClipIds'
import { buildFeedbackClipIds } from '@/lib/audio/buildFeedbackClipIds'
import { calculateStreak } from '@/lib/calculateStreak'

interface UsePracticeAudioHelpOptions {
  terms: number[] | null
  showingFeedback: boolean
  isCorrect: boolean | null
  correctAnswer: number | null
  results?: boolean[]
}

export function usePracticeAudioHelp({
  terms,
  showingFeedback,
  isCorrect,
  correctAnswer,
  results,
}: UsePracticeAudioHelpOptions) {
  const { stop } = useAudioManager()

  const streak = useMemo(() => (results ? calculateStreak(results) : 0), [results])

  const problemClipIds = useMemo(() => (terms ? termsToClipIds(terms) : []), [terms])

  const feedbackClipIds = useMemo(
    () =>
      showingFeedback && isCorrect !== null && correctAnswer !== null
        ? buildFeedbackClipIds(isCorrect, correctAnswer, { streak })
        : [],
    [showingFeedback, isCorrect, correctAnswer, streak]
  )

  const sayProblem = useTTS(problemClipIds, {
    tone: 'math-dictation',
  })
  const sayFeedback = useTTS(feedbackClipIds, {
    tone: isCorrect ? 'celebration' : 'corrective',
  })

  // Problem auto-play is disabled — reading terms aloud is less useful
  // than the other voice cues and creates audio contention.  The TTS
  // registration above still runs (for clip collection), and replayProblem
  // remains available for manual/assistance-triggered replays.

  // Auto-play feedback
  const playedFeedbackRef = useRef(false)
  useEffect(() => {
    if (feedbackClipIds.length === 0 || playedFeedbackRef.current) return
    playedFeedbackRef.current = true
    sayFeedback()
  }, [feedbackClipIds, sayFeedback])

  // Reset feedback flag
  useEffect(() => {
    if (!showingFeedback) playedFeedbackRef.current = false
  }, [showingFeedback])

  // Stop audio on unmount
  useEffect(() => {
    return () => stop()
  }, [stop])

  // Wrap to prevent React onClick from passing MouseEvent as overrideInput
  return { replayProblem: useCallback(() => sayProblem(), [sayProblem]) }
}