File size: 26,055 Bytes
7a1c9d6
 
2dde49f
 
 
 
 
102c540
 
026d850
7a1c9d6
de8c812
 
d1d56a2
 
 
de8c812
d1d56a2
de8c812
d1d56a2
de8c812
 
 
d1d56a2
 
 
de8c812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1d56a2
 
 
de8c812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d28468
7a1c9d6
 
 
026d850
 
 
 
 
 
de8c812
d1d56a2
026d850
7a1c9d6
d62d58c
2dde49f
7a1c9d6
 
 
 
 
 
 
 
 
d62d58c
 
 
 
 
 
 
 
7a1c9d6
 
 
 
de8c812
 
 
 
 
 
 
7a1c9d6
 
 
 
 
 
 
 
5d28468
d1d56a2
 
 
7a1c9d6
 
d1d56a2
7a1c9d6
 
026d850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1d56a2
026d850
 
 
 
de8c812
 
 
026d850
 
 
 
 
 
 
 
7a1c9d6
 
 
d1d56a2
 
 
7a1c9d6
 
 
de8c812
d1d56a2
de8c812
 
d1d56a2
 
 
 
de8c812
7a1c9d6
026d850
d1d56a2
 
 
 
026d850
d1d56a2
5d28468
 
 
 
 
 
 
 
 
 
 
 
d1d56a2
 
 
 
 
 
 
 
 
 
d3dec26
d1d56a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a1c9d6
 
 
 
 
 
 
 
 
de8c812
 
7a1c9d6
 
d1d56a2
7a1c9d6
 
 
 
026d850
 
 
 
 
 
 
5d28468
 
026d850
 
 
 
 
 
 
 
 
 
 
 
 
de8c812
 
 
026d850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de8c812
 
 
026d850
 
 
 
 
 
 
 
 
 
 
 
 
 
de8c812
 
 
026d850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de8c812
 
 
 
 
 
026d850
 
 
 
 
 
 
2dde49f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a9031
2dde49f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
026d850
 
 
 
 
7a1c9d6
24bbad4
 
7a1c9d6
102c540
47bd0d6
 
102c540
ac3613d
47bd0d6
 
 
102c540
7a1c9d6
 
24bbad4
 
102c540
de8c812
24bbad4
102c540
24bbad4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a9031
24bbad4
 
d1d56a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de8c812
d1d56a2
de8c812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24bbad4
d1d56a2
 
 
 
24bbad4
 
2dde49f
7a1c9d6
24bbad4
026d850
 
 
 
 
 
 
c8a9031
026d850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24bbad4
7a1c9d6
c8a9031
026d850
 
 
 
 
 
 
 
 
 
c8a9031
026d850
 
 
 
7a1c9d6
 
 
24bbad4
 
102c540
d62d58c
 
102c540
 
 
47bd0d6
026d850
47bd0d6
102c540
 
 
026d850
24bbad4
102c540
47bd0d6
24bbad4
102c540
 
7a1c9d6
 
 
 
 
 
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
import React, { useState, useRef, useEffect } from 'react';
import axios from 'axios';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneLight, oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { useTheme } from './ui/theme-provider';
import { Button } from './ui/button';
import { Input } from './ui/input';
import Quiz from './Quiz';

// Helper function to parse thinking and answer sections
const parseThinkingAnswer = (text) => {
  // Try to match the think tag, even if it's incomplete
  const thinkingRegex = /<think>([\s\S]*?)(?:<\/think>|$)/i;
  const thinkingMatch = thinkingRegex.exec(text);
  
  // If thinking section is found (even partially)
  if (thinkingMatch) {
    // Get the text after the thinking section, including if </think> is not yet complete
    const thinkingEndIndex = thinkingMatch.index + thinkingMatch[0].length;
    const restOfText = text.substring(thinkingEndIndex).trim();
    
    // Check for explicit answer tag, even if incomplete
    const answerRegex = /<answer>([\s\S]*?)(?:<\/answer>|$)/i;
    const answerMatch = answerRegex.exec(restOfText);
    
    if (answerMatch) {
      // Both thinking and answer tags found
      return {
        thinking: thinkingMatch[1].trim(),
        answer: answerMatch[1].trim(),
        hasFormatting: true
      };
    } else {
      // Only thinking tag found, treat the rest as the answer
      return {
        thinking: thinkingMatch[1].trim(),
        answer: restOfText,
        hasFormatting: true
      };
    }
  }
  
  // Check if there's just an answer tag, even if incomplete
  const answerRegex = /<answer>([\s\S]*?)(?:<\/answer>|$)/i;
  const answerMatch = answerRegex.exec(text);
  if (answerMatch) {
    return {
      thinking: "",
      answer: answerMatch[1].trim(),
      hasFormatting: true
    };
  }
  
  // If no formatting is found, return the original text as the answer
  return {
    thinking: '',
    answer: text,
    hasFormatting: false
  };
};

const Chat = ({ sessionId, userId, docDescription, suggestedQuestions, selectedQuestion, onQuestionSelected }) => {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [userQuestionCount, setUserQuestionCount] = useState(0);
  const [showQuizPrompt, setShowQuizPrompt] = useState(false);
  const [showQuiz, setShowQuiz] = useState(false);
  const [quizQuestions, setQuizQuestions] = useState([]);
  const [quizLoading, setQuizLoading] = useState(false);
  const [quizResults, setQuizResults] = useState(null);
  const [expandedThinking, setExpandedThinking] = useState({});
  const [activeEventSource, setActiveEventSource] = useState(null);
  
  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);
  const { theme } = useTheme();

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // Handle when a suggested question is selected
  useEffect(() => {
    if (selectedQuestion) {
      setInput(selectedQuestion);
      onQuestionSelected(); // Clear the selected question after setting it
    }
  }, [selectedQuestion, onQuestionSelected]);

  const handleInputChange = (e) => {
    setInput(e.target.value);
  };

  const toggleThinking = (messageId) => {
    setExpandedThinking(prev => ({
      ...prev,
      [messageId]: !prev[messageId]
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!input.trim()) return;
    
    const userMessage = input;
    setInput('');
    
    // Add user message to chat
    const userMessageId = Date.now();
    console.log('Adding user message:', userMessageId, userMessage);
    
    setMessages(prevMessages => [
      ...prevMessages, 
      { text: userMessage, sender: 'user', id: userMessageId }
    ]);
    
    // Check if user is explicitly asking for a quiz
    const quizRequestPatterns = [
      /quiz me/i,
      /take (a|the) quiz/i,
      /start (a|the) quiz/i,
      /test (my )?knowledge/i,
      /give me (a|the) quiz/i,
      /create (a|the) quiz/i,
      /can (i|you) (do|have|take) (a|the) quiz/i
    ];
    
    const isQuizRequest = quizRequestPatterns.some(pattern => pattern.test(userMessage));
    
    if (isQuizRequest && !showQuiz && !quizLoading) {
      // Add user message acknowledging quiz request
      const messageId = Date.now() + 1;
      setMessages(prevMessages => [
        ...prevMessages, 
        { 
          text: "I'd be happy to create a quiz based on this document! Generating questions now...", 
          sender: 'ai',
          id: messageId,
          hasFormatting: false
        }
      ]);
      
      // Start quiz generation
      handleQuizGeneration();
      return;
    }
    
    setIsLoading(true);
    
    try {
      // Create placeholder message for streaming content with a guaranteed unique ID
      const messageId = userMessageId + 100;
      console.log('Creating AI message placeholder:', messageId);
      
      setMessages(prevMessages => [
        ...prevMessages, 
        { 
          text: "", 
          sender: 'ai',
          id: messageId,
          thinking: "",
          answer: "",
          hasFormatting: false,
          isStreaming: true
        }
      ]);
      
      // Close any existing EventSource before creating a new one
      if (activeEventSource) {
        console.log('Closing existing EventSource');
        activeEventSource.close();
      }
      
      // Create EventSource for streaming connection - Include user ID if available
      const queryParams = new URLSearchParams({
        session_id: sessionId,
        query: userMessage
      });
      
      // Add user ID if available
      if (userId) {
        queryParams.append('user_id', userId);
      }
      
      const eventSource = new EventSource(`/stream?${queryParams.toString()}`, { 
        withCredentials: true 
      });
      
      // Store the event source in state
      setActiveEventSource(eventSource);
      
      let streamedText = "";
      
      eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data);
        streamedText += data.text;
        
        // Parse current content
        const parsedResponse = parseThinkingAnswer(streamedText);
        
        console.log('Updating message with chunk, ID:', messageId);
        
        // Update message with streamed content
        setMessages(prevMessages => prevMessages.map(msg => 
          msg.id === messageId
            ? { 
                ...msg, 
                text: streamedText,
                thinking: parsedResponse.thinking,
                answer: parsedResponse.answer,
                hasFormatting: parsedResponse.hasFormatting,
                isStreaming: true,
                sender: 'ai'
              }
            : msg
        ));
      };
      
      // Listen for stream completion event
      eventSource.addEventListener('complete', (event) => {
        console.log('Stream complete, closing EventSource');
        eventSource.close();
        setActiveEventSource(null);
        
        const parsedResponse = parseThinkingAnswer(streamedText);
        
        // Update message with final streamed content
        setMessages(prevMessages => 
          prevMessages.map(msg => 
            msg.id === messageId
              ? { 
                  ...msg, 
                  text: streamedText,
                  thinking: parsedResponse.thinking,
                  answer: parsedResponse.answer,
                  hasFormatting: parsedResponse.hasFormatting,
                  isStreaming: false,
                  sender: 'ai'
                }
              : msg
          )
        );
        
        // Increment question count after successful response
        const newCount = userQuestionCount + 1;
        setUserQuestionCount(newCount);
        
        // Check if we should show quiz prompt (after 3+ questions and not already shown)
        if (newCount >= 3 && !showQuizPrompt && !showQuiz && !quizResults) {
          setShowQuizPrompt(true);
        }
        
        setIsLoading(false);
      });
      
      eventSource.onerror = (error) => {
        console.error('EventSource error:', error);
        eventSource.close();
        setActiveEventSource(null);
        
        // If we got a partial response, keep it
        if (streamedText) {
          const parsedResponse = parseThinkingAnswer(streamedText);
          
          // Update message with final streamed content
          setMessages(prevMessages => 
            prevMessages.map(msg => 
              msg.id === messageId
                ? { 
                    ...msg, 
                    text: streamedText,
                    thinking: parsedResponse.thinking,
                    answer: parsedResponse.answer,
                    hasFormatting: parsedResponse.hasFormatting,
                    isStreaming: false,
                    sender: 'ai'
                  }
                : msg
            )
          );
        } else {
          // If we got no response, show error
          setMessages(prevMessages => [
            ...prevMessages.filter(msg => msg.id !== messageId), // Remove placeholder
            { 
              text: 'Sorry, there was an error processing your request.', 
              sender: 'ai', 
              isError: true,
              id: Date.now() 
            }
          ]);
        }
        
        setIsLoading(false);
      };
      
      eventSource.onopen = () => {
        console.log('EventSource connected');
      };
      
    } catch (error) {
      console.error('Error getting response:', error);
      
      // Add error message to chat
      setMessages(prevMessages => [
        ...prevMessages, 
        { 
          text: 'Sorry, there was an error processing your request.', 
          sender: 'ai', 
          isError: true,
          id: Date.now() 
        }
      ]);
      
      setIsLoading(false);
    }
  };

  const handleQuizGeneration = async () => {
    setQuizLoading(true);
    setShowQuizPrompt(false);
    
    try {
      const response = await axios.post('/generate-quiz', {
        session_id: sessionId,
        num_questions: 5,
        user_id: userId // Include user ID if available
      });
      
      setQuizQuestions(response.data.questions);
      setShowQuiz(true);
    } catch (error) {
      console.error('Error generating quiz:', error);
      
      // Add error message to chat
      setMessages(prevMessages => [
        ...prevMessages, 
        { 
          text: 'Sorry, there was an error generating the quiz. Please try again later.', 
          sender: 'ai', 
          isError: true,
          id: Date.now(),
          hasFormatting: false
        }
      ]);
    } finally {
      setQuizLoading(false);
    }
  };

  const handleAcceptQuiz = async () => {
    setShowQuizPrompt(false);
    setQuizLoading(true);
    
    // Add message about starting quiz generation
    setMessages(prevMessages => [
      ...prevMessages,
      { 
        text: "I'll create a knowledge quiz based on this document. Please wait a moment...", 
        sender: 'ai',
        id: Date.now(),
        hasFormatting: false 
      }
    ]);
    
    handleQuizGeneration();
  };

  const handleDeclineQuiz = () => {
    setShowQuizPrompt(false);
    
    // Add message acknowledging user's choice
    setMessages(prevMessages => [
      ...prevMessages,
      { 
        text: "No problem! Feel free to continue asking questions about the document.", 
        sender: 'ai',
        id: Date.now(),
        hasFormatting: false
      }
    ]);
  };

  const handleQuizComplete = (results) => {
    setQuizResults(results);
    setShowQuiz(false);
    
    // Add quiz results to chat
    const resultMessage = `
## Quiz Results πŸ“Š

You answered **${results.correctAnswers}** out of **${results.totalQuestions}** questions correctly (**${Math.round(results.score)}%**).

${results.score >= 80 
  ? "Great job! You have a solid understanding of the material." 
  : results.score >= 60 
    ? "Good work! You're on the right track." 
    : "Keep learning! Review the document to improve your understanding."}
`;
    
    setMessages(prevMessages => [
      ...prevMessages,
      { 
        text: resultMessage, 
        sender: 'ai',
        id: Date.now(),
        hasFormatting: false
      }
    ]);
  };

  const handleCloseQuiz = () => {
    setShowQuiz(false);
  };

  // Component for rendering markdown with custom styles
  const MarkdownContent = ({ content }) => (
    <ReactMarkdown
      remarkPlugins={[remarkGfm]}
      components={{
        p: ({ node, ...props }) => <p className="mb-2" {...props} />,
        h1: ({ node, ...props }) => <h1 className="text-lg font-bold mb-2 mt-3" {...props} />,
        h2: ({ node, ...props }) => <h2 className="text-md font-bold mb-2 mt-3" {...props} />,
        h3: ({ node, ...props }) => <h3 className="text-sm font-bold mb-1 mt-2" {...props} />,
        ul: ({ node, ...props }) => <ul className="list-disc pl-4 mb-2" {...props} />,
        ol: ({ node, ...props }) => <ol className="list-decimal pl-4 mb-2" {...props} />,
        li: ({ node, ...props }) => <li className="mb-1" {...props} />,
        a: ({ node, ...props }) => <a className="text-primary underline" target="_blank" rel="noopener noreferrer" {...props} />,
        code: ({ node, inline, className, children, ...props }) => {
          const match = /language-(\w+)/.exec(className || '');
          const language = match ? match[1] : '';
          
          return !inline ? (
            <div className="rounded-md overflow-hidden my-2">
              <div className="bg-secondary/70 px-3 py-1 text-xs flex justify-between items-center border-b border-border">
                <span>{language || 'code'}</span>
                <button 
                  onClick={() => {
                    navigator.clipboard.writeText(String(children).replace(/\n$/, ''));
                  }}
                  className="px-2 py-0.5 text-xs hover:bg-secondary rounded"
                  title="Copy code"
                >
                  πŸ“‹ Copy
                </button>
              </div>
              <SyntaxHighlighter
                style={theme === 'dark' ? oneDark : oneLight}
                language={language || 'text'}
                PreTag="div"
                customStyle={{
                  margin: 0,
                  padding: '0.75rem',
                  fontSize: '0.8rem',
                  borderRadius: '0 0 0.375rem 0.375rem',
                }}
                {...props}
              >
                {String(children).replace(/\n$/, '')}
              </SyntaxHighlighter>
            </div>
          ) : (
            <code className="px-1 py-0.5 bg-secondary rounded text-sm font-mono" {...props}>
              {children}
            </code>
          );
        },
        pre: ({ node, ...props }) => <div className="my-2" {...props} />,
        blockquote: ({ node, ...props }) => <blockquote className="border-l-2 border-primary/20 pl-2 italic my-2" {...props} />,
        table: ({ node, ...props }) => <div className="overflow-x-auto my-2"><table className="border-collapse w-full" {...props} /></div>,
        thead: ({ node, ...props }) => <thead className="bg-secondary/30" {...props} />,
        tbody: ({ node, ...props }) => <tbody {...props} />,
        tr: ({ node, ...props }) => <tr className="border-b border-border" {...props} />,
        th: ({ node, ...props }) => <th className="p-1.5 text-left text-xs font-medium" {...props} />,
        td: ({ node, ...props }) => <td className="p-1.5 text-xs" {...props} />,
        img: ({ node, ...props }) => <img className="max-w-full h-auto rounded my-2" {...props} />
      }}
    >
      {content}
    </ReactMarkdown>
  );

  // If quiz is active, show the quiz component
  if (showQuiz) {
    return <Quiz questions={quizQuestions} onComplete={handleQuizComplete} onClose={handleCloseQuiz} />;
  }

  return (
    <div className="flex flex-col rounded-lg border border-border bg-card/50 transition-colors duration-300 h-[600px]">
      <div className="flex-1 overflow-y-auto p-4 w-full">
        {messages.length === 0 ? (
          <div className="flex h-full flex-col items-center justify-center text-center">
            <div className="mb-4 rounded-full bg-primary/10 p-6 transition-all duration-300">
              <span role="img" aria-label="chat" className="text-4xl">πŸ’¬</span>
            </div>
            <h3 className="mb-2 text-xl font-semibold">Welcome to Quick Understand!</h3>
            <p className="text-sm text-muted-foreground max-w-md">
              Ask questions about your document or click one of the suggested questions above.
              I'm here to help you understand the content! ✨
            </p>
          </div>
        ) : (
          <div className="w-full">
            {messages.map((message, index) => (
              <div 
                key={message.id || index} 
                className={`mb-4 flex ${message.sender === 'user' ? 'justify-end' : 'justify-start'} w-full`}
              >
                <div 
                  className={`
                    flex items-start gap-2 max-w-[80%] rounded-lg px-4 py-3 shadow-sm
                    ${message.sender === 'user' 
                      ? 'bg-primary text-primary-foreground' 
                      : message.isError 
                        ? 'bg-destructive text-destructive-foreground' 
                        : 'bg-secondary text-secondary-foreground'
                    }
                    transition-all duration-200
                  `}
                >
                  <span className="mt-1 text-lg flex-shrink-0">
                    {message.sender === 'user' 
                      ? 'πŸ‘€' 
                      : message.isError 
                        ? '⚠️' 
                        : 'πŸ€–'}
                  </span>
                  <div className={`${message.sender === 'ai' ? 'markdown-content' : 'text-base'} overflow-hidden`}>
                    {message.sender === 'user' ? (
                      message.text
                    ) : message.isStreaming ? (
                      // Unified streaming display
                      <div>
                        {/* Show streaming content differently depending on whether formatting is detected */}
                        {message.hasFormatting ? (
                          <>
                            {message.thinking && (
                              <div className="mb-2">
                                <div 
                                  className="flex items-center gap-1 mb-1 cursor-pointer text-xs opacity-80"
                                  onClick={() => toggleThinking(message.id)}
                                >
                                  <span className="text-xs">
                                    {expandedThinking[message.id] ? 'β–Ό' : 'β–Ί'}
                                  </span>
                                  <span className="font-medium">
                                    {expandedThinking[message.id] ? 'Hide Thinking Process' : 'Show Thinking Process'}
                                  </span>
                                </div>
                                
                                {expandedThinking[message.id] && (
                                  <div className="p-2 bg-muted/40 rounded-md border border-primary/10 text-xs leading-relaxed mb-2">
                                    <MarkdownContent content={message.thinking} />
                                  </div>
                                )}
                              </div>
                            )}
                            
                            <div>
                              <MarkdownContent content={message.answer} />
                              <span className="inline-block w-1.5 h-4 ml-1 bg-primary animate-pulse rounded-sm" />
                            </div>
                          </>
                        ) : (
                          <>
                            <MarkdownContent content={message.text} />
                            <span className="inline-block w-1.5 h-4 ml-1 bg-primary animate-pulse rounded-sm" />
                          </>
                        )}
                      </div>
                    ) : message.hasFormatting ? (
                      // Non-streaming formatted display
                      <div>
                        {message.thinking && (
                          <div className="mb-2">
                            <div 
                              className="flex items-center gap-1 mb-1 cursor-pointer text-xs opacity-80"
                              onClick={() => toggleThinking(message.id)}
                            >
                              <span className="text-xs">
                                {expandedThinking[message.id] ? 'β–Ό' : 'β–Ί'}
                              </span>
                              <span className="font-medium">
                                {expandedThinking[message.id] ? 'Hide Thinking Process' : 'Show Thinking Process'}
                              </span>
                            </div>
                            
                            {expandedThinking[message.id] && (
                              <div className="p-2 bg-muted/40 rounded-md border border-primary/10 text-xs leading-relaxed mb-2">
                                <MarkdownContent content={message.thinking} />
                              </div>
                            )}
                          </div>
                        )}
                        
                        <div>
                          <MarkdownContent content={message.answer} />
                        </div>
                      </div>
                    ) : (
                      // Non-streaming, non-formatted display
                      <div>
                        <MarkdownContent content={message.text} />
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
            
            {/* Quiz prompt message */}
            {showQuizPrompt && !isLoading && (
              <div className="mb-4 flex justify-start w-full">
                <div className="flex flex-col items-start gap-2 max-w-[80%] rounded-lg px-4 py-3 bg-primary/10 text-foreground shadow-sm border border-primary/20">
                  <div className="flex items-start gap-2">
                    <span className="mt-1 text-lg flex-shrink-0">🧠</span>
                    <div className="text-base">
                      <p className="mb-3">
                        I notice you've asked several questions about this document. Would you like to test your knowledge with a quick quiz?
                      </p>
                      <div className="flex flex-wrap gap-2">
                        <Button 
                          onClick={handleAcceptQuiz} 
                          size="sm" 
                          className="flex items-center gap-1"
                        >
                          <span role="img" aria-label="quiz" className="text-sm">πŸ“</span>
                          Take a quiz
                        </Button>
                        <Button 
                          onClick={handleDeclineQuiz} 
                          variant="outline" 
                          size="sm"
                        >
                          No thanks
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
        {/* Loading indicator removed since streaming response handles this */}
        {quizLoading && (
          <div className="mb-4 flex justify-start w-full">
            <div className="flex items-start gap-2 max-w-[80%] rounded-lg px-4 py-3 bg-secondary text-secondary-foreground shadow-sm">
              <span className="mt-1 text-lg flex-shrink-0">πŸ“</span>
              <div className="flex flex-col gap-2">
                <div className="flex items-center space-x-2">
                  <div className="h-2 w-2 animate-bounce rounded-full bg-primary"></div>
                  <div className="h-2 w-2 animate-bounce rounded-full bg-primary" style={{ animationDelay: '0.2s' }}></div>
                  <div className="h-2 w-2 animate-bounce rounded-full bg-primary" style={{ animationDelay: '0.4s' }}></div>
                </div>
                <span className="text-sm">Generating quiz questions...</span>
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>
      
      <form onSubmit={handleSubmit} className="border-t border-border p-4 transition-colors duration-300 w-full">
        <div className="flex space-x-2 w-full">
          <Input
            id="chat-input"
            ref={inputRef}
            type="text"
            value={input}
            onChange={handleInputChange}
            placeholder="Ask a question about your document... πŸ”"
            disabled={isLoading || quizLoading}
            className="flex-1 transition-colors duration-300"
          />
          <Button 
            type="submit" 
            disabled={isLoading || quizLoading || !input.trim()}
            className="transition-colors duration-300 flex items-center gap-2 flex-shrink-0"
          >
            <span>Send</span>
            <span role="img" aria-label="send" className="flex-shrink-0">πŸ“€</span>
          </Button>
        </div>
      </form>
    </div>
  );
};

export default Chat;