import { useState, useCallback, useRef } from 'react'; import { fetchSessionId } from '../services/chatService'; export function useChatSession(apiUrl?: string) { const [sessionId, setSessionId] = useState(''); const [loading, setLoading] = useState(false); const fetchedRef = useRef(false); const ensureSession = useCallback(async (): Promise => { if (sessionId) return sessionId; if (fetchedRef.current) return ''; fetchedRef.current = true; setLoading(true); try { const id = await fetchSessionId(apiUrl); setSessionId(id); return id; } catch { return ''; } finally { setLoading(false); } }, [sessionId, apiUrl]); const resetSession = useCallback(() => { setSessionId(''); fetchedRef.current = false; }, []); return { sessionId, loading, ensureSession, resetSession }; }