/** * useVoiceDemo Hook * * Custom React hook for managing voice demo session lifecycle. * Handles session creation, connection state, and cleanup. */ import { useState, useCallback } from 'react'; import type { SessionState, VoiceSessionConfig, LiveKitTokens } from '../types'; import { createVoiceSession } from '../services/sessionService'; /** * Return type for the useVoiceDemo hook */ export interface UseVoiceDemoReturn { sessionState: SessionState; createSession: (config?: VoiceSessionConfig) => Promise; disconnect: () => void; isConnected: boolean; isCreating: boolean; error: string | null; } /** * Hook for managing voice demo session state * * Usage: * ```tsx * const { sessionState, createSession, disconnect, isConnected } = useVoiceDemo(); * * // Create a new session * await createSession({ customerName: 'John Doe' }); * * // Disconnect from the session * disconnect(); * ``` */ export function useVoiceDemo(): UseVoiceDemoReturn { const [sessionState, setSessionState] = useState({ status: 'idle', }); /** * Create a new voice demo session */ const createSession = useCallback( async (config: VoiceSessionConfig = {}) => { try { console.log('[useVoiceDemo] Creating session with config:', config); // Set creating state setSessionState({ status: 'creating' }); // Call API to create session and get tokens const tokens: LiveKitTokens = await createVoiceSession(config); console.log('[useVoiceDemo] Session created, tokens received'); // Set connecting state (LiveKit room will handle actual connection) setSessionState({ status: 'connecting' }); // Set connected state with tokens // Note: The actual LiveKit connection happens in the LiveKitRoom component (Stream C) // This just indicates we have valid tokens and are ready to connect setSessionState({ status: 'connected', tokens, }); console.log('[useVoiceDemo] Session ready for connection'); } catch (error) { console.error('[useVoiceDemo] Failed to create session:', error); const errorMessage = error instanceof Error ? error.message : 'Failed to create session'; setSessionState({ status: 'error', error: errorMessage, }); } }, [] ); /** * Disconnect from the current session */ const disconnect = useCallback(() => { console.log('[useVoiceDemo] Disconnecting from session'); setSessionState({ status: 'disconnected' }); // Reset to idle after a brief moment to allow cleanup setTimeout(() => { setSessionState({ status: 'idle' }); }, 500); }, []); // Computed state helpers const isConnected = sessionState.status === 'connected'; const isCreating = sessionState.status === 'creating' || sessionState.status === 'connecting'; const error = sessionState.status === 'error' ? sessionState.error : null; return { sessionState, createSession, disconnect, isConnected, isCreating, error, }; }