import { useState, useEffect, useRef, useCallback } from 'react' /** * useVoiceCommand — continuously listens for voice commands via SpeechRecognition. * Chrome/Edge only (webkit prefix). */ export function useVoiceCommand(onCommand: (transcript: string) => void, enabled: boolean = false) { const [listening, setListening] = useState(false) const [transcript, setTranscript] = useState('') const recRef = useRef(null) useEffect(() => { if (!enabled) { recRef.current?.stop?.(); return } const SR = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition if (!SR) return const rec = new SR() rec.continuous = true rec.interimResults = true rec.lang = 'en-US' rec.onstart = () => setListening(true) rec.onend = () => setListening(false) rec.onresult = (e: any) => { const last = e.results[e.results.length - 1] const text = last[0].transcript setTranscript(text) if (last.isFinal) onCommand(text.trim()) } rec.onerror = () => setListening(false) recRef.current = rec try { rec.start() } catch {} return () => { try { rec.stop() } catch {} } }, [enabled, onCommand]) const start = useCallback(() => { try { recRef.current?.start() } catch {} }, []) const stop = useCallback(() => { try { recRef.current?.stop() } catch {} }, []) return { listening, transcript, start, stop } }