File size: 23,666 Bytes
69524c2
 
da3aae2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e0e984
 
69524c2
 
 
 
 
3446868
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
 
69524c2
 
 
 
 
 
 
 
 
 
3446868
 
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfd716c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
320a9c2
 
 
 
 
 
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
 
 
69524c2
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
 
 
69524c2
 
 
 
 
 
 
ab11183
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3446868
 
69524c2
 
 
3446868
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69524c2
 
926fa08
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b9576b
69524c2
 
6b9576b
 
 
 
 
69524c2
 
 
 
 
 
 
6b9576b
69524c2
 
 
 
6b9576b
69524c2
 
 
 
 
 
 
 
28674f1
 
 
 
 
 
 
 
 
 
69524c2
 
 
 
 
 
 
 
 
 
 
28674f1
 
 
 
 
 
 
69524c2
 
 
 
 
6b9576b
 
 
 
 
 
 
 
 
 
 
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b9576b
 
69524c2
 
 
 
 
 
 
28674f1
69524c2
 
 
 
 
28674f1
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f962ed0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfd716c
 
 
 
 
 
 
 
 
9e0e984
 
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab11183
 
 
 
 
 
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f962ed0
 
 
69524c2
ab11183
69524c2
 
 
 
 
 
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
import { useState, useRef, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
const logo = "https://huggingface.co/spaces/JenishMakwana/RAG/resolve/main/frontend-react/public/logo.png";
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import { 
  Send, 
  Paperclip, 
  Mic, 
  MicOff, 
  PanelLeftClose, 
  PanelLeftOpen,
  Sparkles,
  Search,
  Users,
  FileText,
  Volume2,
  VolumeX,
  ChevronRight,
  CheckCircle,
  MessageSquare,
  BrainCircuit,
  ShieldCheck,
  Scale,
  AlertCircle
} from 'lucide-react';
import { 
  chatQuery, 
  fetchChatHistory, 
  uploadDocument, 
  transcribeVoice,
  getTtsAudio
} from '../api';

// ... (existing functions)

export default function ChatWindow({ 
  token, 
  messages, 
  setMessages, 
  sessionId, 
  onFirstMessage, 
  setIsUploading,
  onUploadSuccess,
  isSidebarCollapsed,
  setIsSidebarCollapsed,
  sessionDocuments,
  setSessionDocuments,
  onLogout
}) {
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [historyLoading, setHistoryLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [isProcessingVoice, setIsProcessingVoice] = useState(false);
  const [speakingIdx, setSpeakingIdx] = useState(null);
  const messagesEndRef = useRef(null);
  const audioRef = useRef(null);
  const mediaRecorderRef = useRef(null);
  const audioChunksRef = useRef([]);
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [pendingSelectionQuery, setPendingSelectionQuery] = useState(null);
  
  // TTS Highlighting State
  const [highlightedInfo, setHighlightedInfo] = useState({ 
    msgIdx: null, 
    sentence: null, 
    wordIdx: -1 
  });
  const highlightTimerRef = useRef(null);

  /**
   * Injects <mark> tags into raw markdown while preserving formatting.
   * This handles the core logic of 'Seamless Highlighting'
   */
  const injectHighlighting = (rawText, msgIdx) => {
    if (highlightedInfo.msgIdx !== msgIdx || !highlightedInfo.sentence) {
      return rawText;
    }

    const { sentence } = highlightedInfo;
    
    // Find the exact sentence block. 
    const sentencePos = rawText.indexOf(sentence);
    if (sentencePos === -1) return rawText;

    const highlightedSentence = `<mark class="highlight-sentence">${sentence}</mark>`;
    const before = rawText.substring(0, sentencePos);
    const after = rawText.substring(sentencePos + sentence.length);
    return before + highlightedSentence + after;
  };

  const toggleFileSelection = (filename) => {
    setSelectedFiles(prev => {
      const exists = prev.includes(filename);
      if (exists) return prev.filter(f => f !== filename);
      return [...prev, filename];
    });
  };

  const renderMessageContent = (text, msgIdx) => {
    if (!text || typeof text !== 'string') return text;
    
    const sourceMarker = '[Source:';
    let content = text;
    let source = '';

    if (text.includes(sourceMarker)) {
      const parts = text.split(sourceMarker);
      content = parts[0];
      source = sourceMarker + parts.slice(1).join(sourceMarker);
    }

    const processedContent = injectHighlighting(content, msgIdx);

    return (
      <>
        <ReactMarkdown 
          remarkPlugins={[remarkGfm]} 
          rehypePlugins={[rehypeRaw]}
        >
          {processedContent}
        </ReactMarkdown>
        {source && (
          <div className="message-citation">
            {source}
          </div>
        )}
      </>
    );
  };

  const renderErrorMessage = (text) => {
    if (!text || typeof text !== 'string') return text;
    const lines = text.split('\n');
    const headerText = lines[0];
    const detailText = lines.slice(1).join('\n');

    return (
      <div className="error-body">
        <div className="error-header">
          <AlertCircle size={16} className="error-header-icon" />
          <span className="error-header-title">{headerText}</span>
        </div>
        {detailText && (
          <div className="error-details">
            <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>
              {detailText}
            </ReactMarkdown>
          </div>
        )}
      </div>
    );
  };

  const handleUpload = async (e) => {
    const files = Array.from(e.target.files);
    if (files.length === 0) return;
    
    setUploading(true);
    setIsUploading(true);
    
    try {
      const results = await Promise.allSettled(
        files.map(async (file) => {
          try {
            const result = await uploadDocument(token, file, sessionId);
            return { file, result, success: true };
          } catch (err) {
            return { file, error: err.message, status: err.status, success: false };
          }
        })
      );

      const successful = results.filter(r => r.value && r.value.success);
      const failed = results.filter(r => (r.value && !r.value.success) || r.status === 'rejected');

      const isUnauthorized = failed.some(r => r.value?.status === 401);
      if (isUnauthorized && onLogout) {
        onLogout();
        return;
      }

      if (successful.length > 0) {
        if (onUploadSuccess) onUploadSuccess();
        
        const newDocs = successful.map(r => ({ 
          filename: r.value.file.name, 
          chunks: r.value.result.chunks 
        }));
        
        setSessionDocuments(prev => [...prev, ...newDocs]);
        
        const successMsg = successful.length === 1 
          ? `✅ Attached document: **${successful[0].value.file.name}**`
          : `✅ Attached **${successful.length}** documents successfully.`;
        
        setMessages(prev => [...prev, { role: 'assistant', text: successMsg }]);
      }

      if (failed.length > 0) {
        const errorMsg = failed.map(r => {
          const name = r.value?.file?.name || "Unknown file";
          const error = r.value?.error || "Upload failed";
          return `- ${name}: ${error}`;
        }).join('\n');
        
        setMessages(prev => [...prev, { role: 'error', text: `Failed to upload some documents:\n${errorMsg}` }]);
      }
    } catch (err) {
      alert("An unexpected error occurred during upload.");
    } finally {
      setUploading(false);
      setIsUploading(false);
      e.target.value = null;
    }
  };

  useEffect(() => {
    const loadHistory = async () => {
      setHistoryLoading(true);
      try {
        const data = await fetchChatHistory(token, sessionId);
        setMessages(data.history);
        setSessionDocuments(data.documents || []);
        setSelectedFiles([]); // Reset selection when switching chats
      } catch (err) {
        setMessages([]);
        setSessionDocuments([]);
        if (err.status === 401 && onLogout) {
          onLogout();
        }
      } finally {
        setHistoryLoading(false);
      }
    };
    if (token && sessionId) loadHistory();
  }, [token, sessionId, setMessages, setSessionDocuments, onLogout]);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const handleStartChat = () => {
    setMessages([
      {
        role: 'assistant',
        text: 'Hello! I am your Legal Case Assistant. How can I help you with your case analysis or document research today?'
      }
    ]);
  };

  const submitQuery = async (queryText, force = false) => {
    if (!queryText.trim() || loading) return;

    // Check if we need to "ask" for document focus
    if (!force && sessionDocuments.length > 1 && selectedFiles.length === 0) {
      setPendingSelectionQuery(queryText);
      return;
    }

    const isFirstMessage = !messages.some(m => m.role === 'user');
    setMessages(prev => [...prev, { role: 'user', text: queryText }]);
    setLoading(true);

    try {
      // Send the list of selected filenames (if any)
      const filenames = selectedFiles.length > 0 ? selectedFiles : null;
      
      const response = await chatQuery(token, queryText, sessionId, null, filenames);
      const aiMessage = { role: 'assistant', text: '' };
      setMessages(prev => [...prev, aiMessage]);
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let fullText = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        fullText += decoder.decode(value, { stream: true });
        
        setMessages(prev => {
          const newMessages = [...prev];
          newMessages[newMessages.length - 1] = { ...newMessages[newMessages.length - 1], text: fullText };
          return newMessages;
        });
      }
      
      if (isFirstMessage) onFirstMessage();
    } catch (err) {
      setMessages(prev => [...prev, { role: 'error', text: err.message }]);
      if (err.status === 401 && onLogout) {
        onLogout();
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (uploading) return;
    const queryText = input;
    if (!queryText.trim()) return;
    setInput('');
    submitQuery(queryText);
  };

  const handleConfirmSelection = () => {
    if (pendingSelectionQuery) {
      const queryToSubmit = pendingSelectionQuery;
      setPendingSelectionQuery(null);
      submitQuery(queryToSubmit, true);
    }
  };

  const toggleVoice = async () => {
    if (isRecording) {
      if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'recording') {
        mediaRecorderRef.current.stop();
      }
    } else {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        const mediaRecorder = new MediaRecorder(stream);
        mediaRecorderRef.current = mediaRecorder;
        audioChunksRef.current = [];

        mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            audioChunksRef.current.push(event.data);
          }
        };

        mediaRecorder.onstop = async () => {
          const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/webm' });
          setIsRecording(false);
          setIsProcessingVoice(true);

          // Stop all audio tracks to release the microphone
          stream.getTracks().forEach(track => track.stop());

          try {
            const result = await transcribeVoice(token, audioBlob);
            if (result.query) setInput(result.query);
          } catch (err) {
            alert('Voice processing failed: ' + err.message);
          } finally {
            setIsProcessingVoice(false);
          }
        };

        mediaRecorder.start();
        setIsRecording(true);
      } catch (err) {
        setIsRecording(false);
        alert('Microphone error: ' + (err.name || 'Unknown') + ' - ' + (err.message || err));
      }
    }
  };

  const audioQueueRef = useRef([]);
  const abortControllerRef = useRef(null);
  const [isPlaying, setIsPlaying] = useState(false);

  // Play next item in queue
  const playNextInQueue = () => {
    if (highlightTimerRef.current) clearInterval(highlightTimerRef.current);
    
    if (audioQueueRef.current.length === 0) {
      setIsPlaying(false);
      setSpeakingIdx(null);
      setHighlightedInfo({ msgIdx: null, sentence: null, wordIdx: -1 });
      return;
    }

    const { url, text: sentenceText } = audioQueueRef.current.shift();
    setIsPlaying(true);

    // Update the single audio element's source (iOS/Mobile compatible)
    audioRef.current.src = url;
    audioRef.current.load();

    audioRef.current.onplay = () => {
      setHighlightedInfo(prev => ({ 
        ...prev, 
        sentence: sentenceText,
        wordIdx: 0 
      }));
    };

    audioRef.current.onended = () => {
      URL.revokeObjectURL(url);
      playNextInQueue();
    };

    audioRef.current.play().catch(err => {
      console.error("Playback error", err);
      playNextInQueue();
    });
  };

  const handleSpeak = async (text, index) => {
    // If clicking same button while playing, STOP everything
    if (speakingIdx === index) {
      if (audioRef.current) {
        audioRef.current.onplay = null;
        audioRef.current.onended = null;
        audioRef.current.pause();
        audioRef.current.src = "";
        audioRef.current.load();
      }
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
      if (highlightTimerRef.current) clearTimeout(highlightTimerRef.current);
      
      audioQueueRef.current.forEach(item => URL.revokeObjectURL(item.url));
      audioQueueRef.current = [];
      setSpeakingIdx(null);
      setIsPlaying(false);
      setHighlightedInfo({ msgIdx: null, sentence: null, wordIdx: -1 });
      return;
    }

    // Stop current if any
    if (audioRef.current) {
      audioRef.current.onplay = null;
      audioRef.current.onended = null;
      audioRef.current.pause();
      audioRef.current.src = "";
      audioRef.current.load();
    }
    if (abortControllerRef.current) abortControllerRef.current.abort();
    if (highlightTimerRef.current) clearTimeout(highlightTimerRef.current);

    audioQueueRef.current.forEach(item => URL.revokeObjectURL(item.url));
    audioQueueRef.current = [];

    // Create & unlock the single Audio element synchronously in the user gesture context
    if (!audioRef.current) {
      audioRef.current = new Audio();
    }
    // Mobile browsers require a synchronous play/pause on a user gesture to lift restriction
    audioRef.current.play().then(() => {
      audioRef.current.pause();
    }).catch(() => {
      // Ignore initial play error on empty source
    });
    
    setSpeakingIdx(index);
    setHighlightedInfo({ msgIdx: index, sentence: null, wordIdx: -1 });
    const controller = new AbortController();
    abortControllerRef.current = controller;

    try {
      const response = await getTtsAudio(token, text, controller.signal);
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      let startedPlaying = false;

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop(); // Keep last partial line

        for (const line of lines) {
          if (!line.trim()) continue;
          try {
            const { audio: b64, text: sentenceText } = JSON.parse(line);
            const byteCharacters = atob(b64);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
              byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            const blob = new Blob([byteArray], { type: 'audio/wav' });
            const url = URL.createObjectURL(blob);
            
            // Queue only the url and text (avoiding creating new Audio elements asynchronously)
            audioQueueRef.current.push({ url, text: sentenceText });

            // If we haven't started playing, start now
            if (!startedPlaying) {
              startedPlaying = true;
              playNextInQueue();
            }
          } catch (e) {
            console.error("Error parsing audio chunk JSON:", e);
          }
        }
      }
    } catch (err) {
      if (err.name !== 'AbortError') {
        console.error("TTS Stream error:", err);
        setSpeakingIdx(null);
      }
    }
  };

  return (
    <div className="chat-main">
      <header className="chat-header">
        <div className="header-left">
          <button 
            className="sidebar-toggle" 
            onClick={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
            title={isSidebarCollapsed ? "Show sidebar" : "Hide sidebar"}
          >
            {isSidebarCollapsed ? <PanelLeftOpen size={20} /> : <PanelLeftClose size={20} />}
          </button>
          <h1>Legal Case Analysis</h1>
        </div>
      </header>
      <div className="chat-messages">
        {historyLoading ? (
          <div className="welcome-screen">
             <div className="loader-ring" style={{ width: '40px', height: '40px', margin: '0 auto 1rem' }}></div>
             <p>Restoring conversation...</p>
          </div>
        ) : (
          <>
            {messages.length === 0 && (
              <div className="welcome-screen">
                <div className="welcome-logo-container" style={{ 
                  width: '64px', 
                  height: '64px', 
                  margin: '0 auto 1.5rem', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  background: '#000000',
                  border: '1.5px solid rgba(168, 85, 247, 0.45)',
                  boxShadow: '0 12px 32px rgba(168, 85, 247, 0.25), inset 0 0 16px rgba(168, 85, 247, 0.2)',
                  padding: '4px',
                  borderRadius: '16px'
                }}>
                  <img src={logo} alt="Logo" style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: '12px' }} />
                </div>
                <h2>Legal Case Assistant</h2>
                <p className="welcome-subtitle">
                  Analyze complex case files, retrieve precise legal citations, and verify precedents securely.
                </p>

                <div className="system-pills-row">
                  <div className="system-pill">
                    <BrainCircuit size={16} className="pill-icon" />
                    <span>Always Online</span>
                  </div>
                  <div className="system-pill">
                    <Scale size={16} className="pill-icon" />
                    <span>Smart Search</span>
                  </div>
                  <div className="system-pill">
                    <ShieldCheck size={16} className="pill-icon" />
                    <span>Ironclad Privacy</span>
                  </div>
                </div>

                <button 
                  className="start-chat-btn" 
                  onClick={handleStartChat}
                >
                  <MessageSquare size={16} style={{ marginRight: '8px' }} />
                  <span>Start Chat</span>
                </button>
              </div>
            )}
            
            {messages.map((m, i) => (
              <div key={i} className={`message-bubble ${m.role}`}>
                {m.role === 'error' ? (
                  renderErrorMessage(m.text)
                ) : (
                  <div className="message-content">
                    {m.role === 'assistant' ? (
                      renderMessageContent(m.text, i)
                    ) : (
                      m.text
                    )}
                  </div>
                )}
                {m.role === 'assistant' && !m.text.startsWith('✅') && !m.text.includes('No documents found') && (
                  <button 
                    className={`speak-btn ${speakingIdx === i ? 'speaking' : ''}`}
                    onClick={() => handleSpeak(m.text, i)}
                    title="Read Aloud"
                  >
                    {speakingIdx === i ? <VolumeX size={16} /> : <Volume2 size={16} />}
                  </button>
                )}
              </div>
            ))}
            
            {loading && (
              <div className="message-bubble assistant">
                <div className="loading-dots">Analyzing</div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </>
        )}
      </div>

      {messages.length > 0 && (
        <div className="chat-input-area">
          {sessionDocuments.length > 0 && pendingSelectionQuery && (
            <div className="selector-panel prompt">
              <div className="selector-header">
                <h3>Select focus for your question</h3>
                <div className="selector-pagination">
                  <span>{selectedFiles.length === 0 ? 'All Documents' : `${selectedFiles.length} selected`}</span>
                </div>
              </div>
              
              <div className="selector-list">
                <div 
                  className={`selector-item ${selectedFiles.length === 0 ? 'active' : ''}`}
                  onClick={() => setSelectedFiles([])}
                >
                  <div className="item-number">
                    {selectedFiles.length === 0 ? <CheckCircle size={16} /> : 1}
                  </div>
                  <div className="item-info">
                    <span className="item-name">All Documents</span>
                  </div>
                  <ChevronRight className="item-arrow" size={18} />
                </div>
                
                {sessionDocuments.map((doc, idx) => {
                  const isActive = selectedFiles.includes(doc.filename);
                  return (
                    <div 
                      key={idx} 
                      className={`selector-item ${isActive ? 'active' : ''}`}
                      onClick={() => toggleFileSelection(doc.filename)}
                    >
                      <div className="item-number">
                        {isActive ? <CheckCircle size={16} /> : idx + 2}
                      </div>
                      <div className="item-info">
                        <span className="item-name">{doc.filename}</span>
                      </div>
                      <ChevronRight className="item-arrow" size={18} />
                    </div>
                  );
                })}
              </div>

              <div className="selector-footer">
                 <button className="selector-confirm-btn" onClick={handleConfirmSelection}>
                   Analyze selected documents
                 </button>
              </div>
            </div>
          )}
          {uploading && (
            <div className="embedding-status">
              <div className="mini-spinner"></div>
              <span>Processing and embedding documents... Please wait.</span>
            </div>
          )}
          <form onSubmit={handleSubmit} className="chat-input-wrapper">
            <label className="icon-btn" title="Attach Document">
              <input type="file" accept=".pdf" multiple style={{display: 'none'}} onChange={handleUpload} disabled={loading || uploading} />
              <Paperclip size={20} />
            </label>
            <button 
              type="button" 
              className={`icon-btn voice-btn ${isRecording ? 'recording' : ''}`}
              onClick={toggleVoice}
              disabled={loading || uploading || isProcessingVoice}
            >
              {isRecording ? <MicOff size={20} /> : <Mic size={20} />}
            </button>
            <input
              type="text"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder={
                isProcessingVoice ? "Processing voice..." : 
                selectedFiles.length > 0 ? `Searching ${selectedFiles.length} doc${selectedFiles.length > 1 ? 's' : ''}...` :
                sessionDocuments.length > 0 ? "Search documents..." :
                "Ask a question..."
              }
              disabled={loading || isProcessingVoice}
            />
            <button type="submit" className="send-btn" disabled={loading || uploading || !input.trim()}>
              <Send size={18} />
            </button>
          </form>
        </div>
      )}
    </div>
  );
}