import { useState, useRef, useEffect } from 'react'; import { ArrowUp } from 'lucide-react'; import type { PBLChatMessage, PBLIssue } from '@/lib/pbl/types'; import { useI18n } from '@/lib/hooks/use-i18n'; import { MessageResponse } from '@/components/ai-elements/message'; import { useDraftCache } from '@/lib/hooks/use-draft-cache'; import { SpeechButton } from '@/components/audio/speech-button'; interface ChatPanelProps { readonly messages: PBLChatMessage[]; readonly currentIssue: PBLIssue | null; readonly userRole: string; readonly isLoading: boolean; readonly onSendMessage: (text: string) => void; } export function ChatPanel({ messages, currentIssue, userRole, isLoading, onSendMessage, }: ChatPanelProps) { const { t } = useI18n(); const [input, setInput] = useState(''); const messagesEndRef = useRef(null); const inputRef = useRef(null); const composingRef = useRef(false); // Draft cache const { cachedValue: cachedDraft, updateCache: updateDraftCache, clearCache: clearDraftCache, } = useDraftCache({ key: 'pblChatDraft' }); // Restore draft: use lazy initializer for first render, then sync via derived state const [prevCachedDraft, setPrevCachedDraft] = useState(cachedDraft); if (cachedDraft !== prevCachedDraft) { setPrevCachedDraft(cachedDraft); if (cachedDraft) { setInput(cachedDraft); } } // Auto-scroll on new messages useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages.length]); const handleInputChange = (value: string) => { setInput(value); updateDraftCache(value); }; const handleSubmit = () => { if (!input.trim() || isLoading) return; onSendMessage(input.trim()); setInput(''); clearDraftCache(); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey && !composingRef.current) { e.preventDefault(); handleSubmit(); } }; return (
{/* Header */}

{t('pbl.chat.title')}

{currentIssue && (

{t('pbl.chat.currentIssue')}: {currentIssue.title}

)}
{/* Messages */}
{messages.map((msg) => ( ))} {isLoading && (
. . .
)}
{/* Input */}
{t('pbl.chat.mentionHint')}