File size: 58,757 Bytes
a205f59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Research Interface</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/9.1.5/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.6.1/mermaid.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/contrib/auto-render.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.css">
    <script src="https://cdn.tailwindcss.com?plugins=typography"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.0/es5/tex-mml-chtml.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <style>
        /* Additional mobile-friendly styles */
        @media (max-width: 640px) {
          pre {
            max-width: 100%;
            overflow-x: auto;
          }
          .mermaid {
            max-width: 100%;
            overflow-x: auto;
          }
          table {
            display: block;
            width: 100%;
            overflow-x: auto;
          }
        }
        
        /* Improve touch target sizes */
        @media (max-width: 640px) {
          button {
            min-height: 44px;
          }
          
          input, textarea {
            font-size: 16px; /* Prevents iOS zoom on focus */
          }
        }
        
        /* Improve text reading on small screens */
        @media (max-width: 480px) {
          .markdown-content {
            font-size: 15px;
            line-height: 1.6;
          }
        }
    
        /* Fix Mermaid diagram overflow issues */
        .mermaid-container {
          width: 100%;
          overflow-x: auto;
        }
      </style>
</head>
<body>
    <div id="root"></div>
    
    <script type="text/babel">
        const { useState, useEffect, useRef } = React;

        let finalReport = '';

        const ResearchInterface = () => {
            const [isLoading, setIsLoading] = useState(false);
            const [researchLoading, setResearchLoading] = useState(false);
            const [countdown, setCountdown] = useState(0);
            const [researchCountdown, setResearchCountdown] = useState(0);
            const [currentStep, setCurrentStep] = useState(1);
            const [responseContent, setResponseContent] = useState('');
            const [expandedSections, setExpandedSections] = useState({});
            const [researchTopic, setResearchTopic] = useState('');
            const [thinkingOutput, setThinkingOutput] = useState('');
            const [researchSections, setResearchSections] = useState([]);
            const [userThoughts, setUserThoughts] = useState('');
            const responseRef = useRef(null);
            const [taskResults, setTaskResults] = useState({});
            const [currentTaskIndex, setCurrentTaskIndex] = useState(-1);
            const [taskLoading, setTaskLoading] = useState(false);
            const stepRefs = useRef([]);

            // Toggle section expansion
            const toggleSection = (sectionId) => {
                setExpandedSections(prev => ({
                    ...prev,
                    [sectionId]: !prev[sectionId]
                }));
            };


            // Fetch from the API with streaming response
            const fetchThinkingData = async () => {
                setIsLoading(true);
                setCountdown(3);
                setThinkingOutput('');
                
                try {
                    const response = await fetch('/api/think', {
                        method: 'POST',
                        headers: {
                        'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ topic: researchTopic }),
                    });
                    
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let buffer = '';
                    
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        
                        const chunk = decoder.decode(value);
                        buffer += chunk;
                        
                        // Process the accumulated buffer
                        const processedContent = processSSEContent(buffer);
                        
                        if (processedContent) {
                            setThinkingOutput(prev => prev + processedContent);
                            // Clear the processed content from the buffer
                            buffer = buffer.replace(/data: {"content": "[^"]*"}(?:\r?\n)?/g, '');
                        }
                    }
                    
                    // Process any remaining content in the buffer
                    if (buffer) {
                        const finalContent = processSSEContent(buffer);
                        if (finalContent) {
                            setThinkingOutput(prev => prev + finalContent);
                        }
                    }
                } catch (error) {
                    console.error('Error with stream:', error);
                    setThinkingOutput('请求发生错误,请重试...');
                } finally {
                    setIsLoading(false);
                    goToNextStep();
                }
            };

            // Fetch research results
            const fetchResearchData = async () => {
                setResearchLoading(true);
                setResearchCountdown(3);
                const prompt = [
                    `Initial Query: `+researchTopic,
                    `Follow-up Questions: `+thinkingOutput,
                    `Follow-up Feedback: `+userThoughts
                ].join("\n\n");
                console.log(prompt);
                try {
                    const response = await fetch('/api/research', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ query: prompt }),
                    });
                    
                    const data = await response.json();
                    
                    // Parse the OpenAI response format
                    const contentString = data.choices[0].message.content;
                    
                    // Extract the JSON array from markdown code block format ```json ... ```
                    const jsonMatch = contentString.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
                    
                    if (jsonMatch && jsonMatch[1]) {
                        const parsedData = JSON.parse(jsonMatch[1]);
                        setResearchSections(parsedData);
                        // Initialize the first task execution after sections are loaded
                        setCurrentTaskIndex(0);
                    } else {
                        throw new Error('Invalid response format from API');
                    }
                    
                } catch (error) {
                    console.error('Error fetching research data:', error);
                    setResearchSections([{
                        id: 'error',
                        query: '获取数据错误',
                        researchGoal: '无法获取研究数据,请重试...'
                    }]);
                } finally {
                    setResearchLoading(false);
                    goToNextStep();
                }
            };

            // Add this new function to fetch the report data
            const fetchReportData = async () => {
                setIsLoading(true);
                setResponseContent('');
                
                // 准备API调用的数据
                const learnings = researchSections.map(section => {
                    return taskResults[section.id || researchSections.indexOf(section)] || '';
                });
                
                try {
                    const response = await fetch("/api/report", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify({
                            query: researchTopic,
                            learnings: learnings
                        }),
                    });
                    
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let buffer = '';
                    
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        
                        const chunk = decoder.decode(value);
                        buffer += chunk;
                        
                        // 处理完整的SSE消息
                        const messages = buffer.split(/\n\n/);
                        buffer = messages.pop() || ''; // 保留最后一个可能不完整的消息
                        
                        let newContent = '';
                        
                        for (const message of messages) {
                            const dataLines = message.split('\n')
                                .filter(line => line.startsWith('data: '))
                                .map(line => {
                                    try {
                                        return JSON.parse(line.substring(6)).content || '';
                                    } catch (e) {
                                        console.error('Error parsing JSON:', e);
                                        return '';
                                    }
                                })
                                .filter(content => content);
                            
                            // 累积新内容
                            const messageContent = dataLines.join('');
                            newContent += messageContent;
                            finalReport += messageContent; // 同时累积到完整内容中
                        }
                        
                        // 实时更新UI显示
                        if (newContent) {
                            setResponseContent(prev => prev + newContent);
                        }
                    }
                    
                    // 处理缓冲区中剩余的数据
                    if (buffer) {
                        const remainingContent = buffer.split('\n')
                            .filter(line => line.startsWith('data: '))
                            .map(line => {
                                try {
                                    return JSON.parse(line.substring(6)).content || '';
                                } catch (e) {
                                    return '';
                                }
                            })
                            .filter(content => content)
                            .join('');
                            
                        if (remainingContent) {
                            setResponseContent(prev => prev + remainingContent);
                            finalReport += remainingContent;
                        }
                    }
                    
                    // 数据流结束后,短暂延迟再进行最终的完整渲染
                    setTimeout(() => {
                        // 使用完整累积的内容进行最终渲染
                        setResponseContent(finalReport);
                        console.log(finalReport);
                    }, 300); // 短暂延迟,让用户感知到流程已完成
                    
                } catch (error) {
                    console.error('Error generating report:', error);
                    setResponseContent('生成报告时发生错误,请重试...');
                } finally {
                    setIsLoading(false);
                }
            };

            

            const convertToPDFFormat = (content) => {
                if (!content) return "<p>No content available</p>";
                // Process content for PDF-friendly format
                let processedContent = content;
                
                // Process mermaid diagrams specially for PDF
                processedContent = processedContent.replace(/```mermaid([\s\S]*?)```/g, (match, diagramCode) => {
                    // For PDF export, we could replace with a note about diagrams
                    return '<div class="pdf-note" style="padding: 10px; background-color: #f5f5f5; border-left: 4px solid #4a5568; margin: 10px 0;">' +
                    '<p><strong>Note:</strong> This document contains a diagram that may not render in PDF format. ' +
                    'Please refer to the original online report to view all diagrams.</p></div>';
                });
                
                // Process math expressions for PDF
                processedContent = processedContent.replace(/\$\$([\s\S]*?)\$\$/g, '<div class="math">$1</div>');
                processedContent = processedContent.replace(/\$([^\$]*?)\$/g, '<span class="math">$1</span>');
                
                // Add PDF-specific styling
                const styledContent = `<style>
                    body {
                    font-family: 'Arial', sans-serif;
                    font-size: 12pt;
                    line-height: 1.5;
                    color: #333;
                    margin: 1cm;
                    }
                    h1, h2, h3, h4, h5, h6 {
                    margin-top: 1.5em;
                    margin-bottom: 0.5em;
                    color: #1a365d;
                    }
                    h1 { font-size: 20pt; }
                    h2 { font-size: 16pt; }
                    h3 { font-size: 14pt; }
                    p { margin: 0.5em 0; }
                    ul, ol { margin: 0.5em 0; padding-left: 2em; }
                    code {
                    font-family: 'Courier New', monospace;
                    background-color: #f5f5f5;
                    padding: 2px 4px;
                    border-radius: 3px;
                    }
                    pre {
                    background-color: #f5f5f5;
                    padding: 10px;
                    border-radius: 5px;
                    white-space: pre-wrap;
                    font-family: 'Courier New', monospace;
                    margin: 1em 0;
                    }
                    table {
                    border-collapse: collapse;
                    width: 100%;
                    margin: 1em 0;
                    }
                    th, td {
                    border: 1px solid #ddd;
                    padding: 8px;
                    text-align: left;
                    }
                    th {
                    background-color: #f2f2f2;
                    }
                    blockquote {
                    border-left: 4px solid #e2e8f0;
                    margin: 1em 0;
                    padding-left: 1em;
                    color: #4a5568;
                    }
                    .pdf-note {
                    padding: 10px;
                    background-color: #f5f5f5;
                    border-left: 4px solid #4a5568;
                    margin: 1em 0;
                    }
                    img {
                    max-width: 100%;
                    height: auto;
                    }
                    .page-break {
                    page-break-after: always;
                    }
                    .report-title {
                    font-size: 24pt;
                    text-align: center;
                    margin-bottom: 2em;
                    color: #1a365d;
                    }
                    .report-date {
                    text-align: right;
                    margin-bottom: 2em;
                    font-style: italic;
                    }
                    .report-summary {
                    margin: 2em 0;
                    padding: 1em;
                    background-color: #f8f9fa;
                    border-radius: 5px;
                    }</style><div class="report-title">${researchTopic}</div><div class="report-date">Generated on: ${new Date().toLocaleDateString()}</div><div class="report-content">
                    ${window.marked ? window.marked.parse(processedContent) : processedContent.replace(/\n/g, "<br>")}
                </div>
                `;
                
                return styledContent;
            };

            const handleDownloadPDF = async () => {
                if (!responseContent.trim()) {
                    alert("报告内容为空,无法导出");
                    return;
                }
                try {
                    // Add loading indicator
                    setIsLoading(true);
                    const filename = researchTopic ? `${researchTopic}.pdf` : "report.pdf";
                    const response = await fetch("/api/pdf", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({
                        text: finalReport,
                        filename
                    }),

                    });
                    
                    if (!response.ok) {
                        const errorText = await response.text();
                        throw new Error(`生成 PDF 失败: ${errorText}`);
                    }
                    
                    // Create Blob for downloading the PDF
                    const blob = await response.blob();
                    const link = document.createElement("a");
                    link.href = window.URL.createObjectURL(blob);
                    link.download = filename;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                } catch (error) {
                    console.error("PDF 生成失败:", error);
                    alert("导出失败,请稍后重试");
                } finally {
                    setIsLoading(false);
                }
            };


            // Execute tasks sequentially
            useEffect(() => {
                const executeTask = async (index) => {
                    if (index < 0 || index >= researchSections.length) {
                        // All tasks are complete or no tasks to execute
                        setTaskLoading(false);
                        return;
                    }

                    setTaskLoading(true);
                    const section = researchSections[index];
                    
                    // Automatically expand the section being processed
                    setExpandedSections(prev => ({
                        ...prev,
                        [section.id || index]: true
                    }));

                    try {
                        const response = await fetch('/api/taskExec', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ 
                                query: section.query, 
                                researchGoal: section.researchGoal 
                            }),
                        });
                        
                        const reader = response.body.getReader();
                        const decoder = new TextDecoder();
                        let buffer = '';
                        
                        while (true) {
                            const { done, value } = await reader.read();
                            if (done) break;
                            
                            const chunk = decoder.decode(value);
                            buffer += chunk;
                            
                            // Process the buffer for SSE format content
                            const processedContent = processSSEContent(buffer);
                            
                            if (processedContent) {
                                setTaskResults(prev => {
                                    const currentContent = prev[section.id || index] || '';
                                    return {
                                        ...prev,
                                        [section.id || index]: currentContent + processedContent
                                    };
                                });
                                
                                // Remove processed parts from buffer
                                const regex = /data: {"content": "[^"]*"}(?:\r?\n)?/g;
                                buffer = buffer.replace(regex, '');
                            }
                        }
                        
                        // Process any remaining content
                        if (buffer) {
                            const finalContent = processSSEContent(buffer);
                            if (finalContent) {
                                setTaskResults(prev => {
                                    const currentContent = prev[section.id || index] || '';
                                    return {
                                        ...prev,
                                        [section.id || index]: currentContent + finalContent
                                    };
                                });
                            }
                        }
                        
                        // Once done, move to the next task
                        setCurrentTaskIndex(index + 1);
                    } catch (error) {
                        console.error(`Error executing task for section ${section.id || index}:`, error);
                        setTaskResults(prev => ({
                            ...prev,
                            [section.id || index]: '获取数据失败,请重试...'
                        }));
                        
                        // Even on error, move to the next task
                        setCurrentTaskIndex(index + 1);
                    }
                };

                // Only execute if we have a valid index and are in step 3
                if (currentTaskIndex >= 0 && currentStep === 3) {
                    executeTask(currentTaskIndex);
                }
            }, [currentTaskIndex, researchSections, currentStep]);

            useEffect(() => {
                if (stepRefs.current[currentStep]) {
                    stepRefs.current[currentStep].scrollIntoView({
                        behavior: "smooth",
                        block: "start"
                    });
                }
            }, [currentStep]);

            useEffect(() => {
                if ((currentStep === 3 || currentStep === 4) && responseRef.current) {
                    responseRef.current.scrollTop = responseRef.current.scrollHeight;
                }
            }, [taskResults,responseContent]);

            // Countdown timer for thinking
            useEffect(() => {
                let timer;
                if (countdown > 0) {
                    timer = setTimeout(() => setCountdown(countdown - 1), 1000);
                }
                
                return () => clearTimeout(timer);
            }, [countdown]);

            // Countdown timer for research
            useEffect(() => {
                let timer;
                if (researchCountdown > 0) {
                    timer = setTimeout(() => setResearchCountdown(researchCountdown - 1), 1000);
                }
                
                return () => clearTimeout(timer);
            }, [researchCountdown]);

            // Move to next step
            const goToNextStep = () => {
                if (currentStep < 4) {
                    setCurrentStep(currentStep + 1);
                }
            };

            // Initialize marked and mermaid after component mounts
            useEffect(() => {
                // Initialize mermaid with improved configuration
                if (window.mermaid) {
                    window.mermaid.initialize({
                        startOnLoad: true,
                        theme: 'neutral',
                        securityLevel: 'loose',
                        fontSize: 16,
                        fontFamily: 'sans-serif',
                        flowchart: {
                            htmlLabels: true,
                            curve: 'basis'
                        },
                        er: {
                            useMaxWidth: true
                        },
                        sequence: {
                            useMaxWidth: true,
                            diagramMarginX: 50,
                            diagramMarginY: 10,
                            actorMargin: 50,
                            width: 150,
                            height: 65
                        },
                        pie: {
                            useWidth: true
                        }
                    });
                }
            }, []);

            // Function to process mermaid diagrams after markdown is rendered
            useEffect(() => {
                const processMermaidDiagrams = () => {
                    // Check if the mermaid library is available
                    if (window.mermaid) {
                        // Find all mermaid diagram containers that haven't been processed
                        const mermaidDiagrams = document.querySelectorAll('.mermaid:not(.processed)');
                        
                        if (mermaidDiagrams.length > 0) {
                            // Mark diagrams as processed to avoid reprocessing
                            mermaidDiagrams.forEach(diagram => {
                                diagram.classList.add('processed');
                            });
                            
                            // Run mermaid to render the diagrams
                            try {
                                window.mermaid.init(undefined, mermaidDiagrams);
                            } catch (e) {
                                console.error('Error rendering mermaid diagrams:', e);
                            }
                        }
                    }
                };

                // Process diagrams when task results change
                if (Object.keys(taskResults).length > 0) {
                    // Use a small timeout to ensure the DOM has updated
                    setTimeout(processMermaidDiagrams, 100);
                }
            }, [taskResults, expandedSections]);

            // Add this useEffect to process mermaid diagrams in the final report
            useEffect(() => {
                const processFinalReportMermaid = () => {
                    // Only process if we have response content and we're in step 4
                    if (responseContent && currentStep === 4 && responseRef.current) {
                    if (window.mermaid) {
                        try {
                        // Find all mermaid diagram containers in the final report
                        const mermaidDiagrams = responseRef.current.querySelectorAll('.mermaid:not(.processed)');
                        
                        if (mermaidDiagrams.length > 0) {
                            // Mark diagrams as processed to avoid reprocessing
                            mermaidDiagrams.forEach(diagram => {
                            diagram.classList.add('processed');
                            });
                            
                            // Run mermaid to render the diagrams
                            window.mermaid.init(undefined, mermaidDiagrams);
                        }
                        } catch (e) {
                        console.error('Error rendering mermaid diagrams in final report:', e);
                        }
                    }
                    }
                };

                // Use a small delay to ensure the DOM has been updated with the content
                if (responseContent && currentStep === 4) {
                    // First processing attempt
                    processFinalReportMermaid();
                    
                    // Additional attempts with increasing delays to ensure rendering
                    setTimeout(processFinalReportMermaid, 100);
                    setTimeout(processFinalReportMermaid, 500);
                    setTimeout(processFinalReportMermaid, 1000);
                }
            }, [responseContent, currentStep]);

            useEffect(() => {
                // Process MathJax rendering after markdown content is updated
                if (window.MathJax && (responseContent || Object.keys(taskResults).length > 0)) {
                    setTimeout(() => {
                    if (window.MathJax.typeset) {
                        window.MathJax.typeset();
                    }
                    }, 100);
                }
            }, [responseContent, taskResults, expandedSections]);

            // Advanced markdown renderer with support for tables, diagrams, and code
            const renderMarkdown = (text) => {
                if (!text) return <div>No content to display</div>;
                
                // Use marked library if available, otherwise fallback to basic rendering
                if (window.marked) {
                    // Configure marked with custom renderer
                    const renderer = new window.marked.Renderer();
                    const originalCodeRenderer = renderer.code.bind(renderer);
                    
                    // Override code block rendering
                    renderer.code = (code, language) => {
                        // Special handling for mermaid diagrams - improved detection
                        if (language === 'mermaid' || 
                            code.trim().startsWith('graph ') || 
                            code.trim().startsWith('pie ') || 
                            code.trim().startsWith('flowchart ') || 
                            code.trim().startsWith('sequenceDiagram ') ||
                            code.trim().startsWith('gantt ') ||
                            code.trim().startsWith('classDiagram ') ||
                            code.trim().startsWith('stateDiagram') ||
                            code.trim().startsWith('erDiagram') ||
                            code.trim().startsWith('journey') ||
                            code.trim().startsWith('gitGraph') ||
                            /graph\s+TD\s*\n/.test(code)) { // Specific pattern for your case
                            
                            // Ensure language is set for better processing
                            if (language !== 'mermaid') {
                                language = 'mermaid';
                            }
                            const id = 'mermaid-diagram-' + Math.random().toString(36).substring(2, 15);
                            return `<div class="mermaid-container" style="margin:1rem 0;text-align:center;"><pre class="mermaid" id="${id}">${code}</pre></div>`;
                        }
                        // For other languages, use the original renderer with better styling
                        return `<pre style="margin:0.75rem 0;padding:1rem;overflow-x:auto;background-color:#f8f9fa;border-radius:0.25rem;"><code class="language-${language || ''}">${originalCodeRenderer(code, language)}</code></pre>`;
                    };

                    // Process LaTeX formulas before passing to marked
                    const processLatex = (text) => {
                        // Avoid processing already escaped dollar signs
                        let processed = text.replace(/\\\$/g, 'ESCAPED_DOLLAR');
                        
                        // Process display math ($$...$$)
                        processed = processed.replace(/\$\$([\s\S]*?)\$\$/g, '<div class="math-display">$$$$1$$</div>');
                        
                        // Process inline math ($...$)
                        processed = processed.replace(/\$([^\$]*?)\$/g, '<span class="math-inline">\\($1\\)</span>');
                        
                        // Restore escaped dollar signs
                        processed = processed.replace(/ESCAPED_DOLLAR/g, '\\$');
                        
                        return processed;
                    };

                    text = processLatex(text);
                    
                    // Rest of the renderer configuration remains the same
                    renderer.paragraph = (text) => {
                    return `<p style="margin-top:0.5rem;margin-bottom:0.5rem;">${text}</p>`;
                    };
                    
                    renderer.heading = (text, level) => {
                    return `<h${level} style="margin-top:1.25rem;margin-bottom:0.75rem;font-weight:600;">${text}</h${level}>`;
                    };
                    
                    renderer.list = (body, ordered) => {
                    const type = ordered ? 'ol' : 'ul';
                    return `<${type} style="margin-top:0.5rem;margin-bottom:0.5rem;padding-left:1.5rem;">${body}</${type}>`;
                    };
                    
                    renderer.listitem = (text) => {
                    return `<li style="margin-bottom:0.25rem;">${text}</li>`;
                    };
                    
                    renderer.blockquote = (quote) => {
                    return `<blockquote style="margin:0.75rem 0;padding-left:1rem;border-left:4px solid #e2e8f0;color:#4a5568;">${quote}</blockquote>`;
                    };
                    
                    // Use the custom renderer for this specific rendering
                    const customMarked = window.marked.setOptions({
                    renderer: renderer,
                    highlight: function(code, lang) {
                        if (window.hljs && lang) {
                        try {
                            return window.hljs.highlight(code, { language: lang }).value;
                        } catch (e) {
                            return code;
                        }
                        }
                        return code;
                    },
                    pedantic: false,
                    gfm: true,
                    breaks: true,
                    sanitize: false,
                    smartypants: true,
                    xhtml: false
                    });
                    
                    return (
                    <div 
                        className="markdown-content" 
                        style={{fontSize: '16px', lineHeight: '1.5'}}
                        dangerouslySetInnerHTML={{ __html: customMarked.parse(text) }}
                    />
                    );
                } else {
                    // Basic fallback if marked is not loaded
                    return (
                    <div 
                        style={{fontSize: '16px', lineHeight: '1.5'}}
                        dangerouslySetInnerHTML={{ __html: text.replace(/\n/g, '<br/>') }}
                    />
                    );
                }
            };

            const processSSEContent = (text) => {
                let result = '';
                const regex = /data: {"content": "([^"]*)"}(?:\r?\n)?/g;
                let match;
                
                while ((match = regex.exec(text)) !== null) {
                    try {
                        // Properly decode escaped characters, especially important for code blocks
                        const decodedContent = JSON.parse(`"${match[1]}"`);
                        result += decodedContent;
                    } catch (e) {
                        // Fallback if parsing fails
                        result += match[1];
                    }
                }
                
                return result;
            };

            const processMarkdownWithMermaid = (content) => {
                if (!content) return <div>No content to display</div>;
                
                // First, look for Mermaid blocks and extract them
                const blocks = [];
                let lastIndex = 0;
                
                // Match for "```mermaid ... ```" style blocks
                const mermaidRegex = /```(?:mermaid)?\s*([\s\S]*?)```/g;
                let match;
                
                while ((match = mermaidRegex.exec(content)) !== null) {
                    // Add text before the mermaid block
                    if (match.index > lastIndex) {
                        blocks.push({
                            type: 'text',
                            content: content.substring(lastIndex, match.index)
                        });
                    }
                    
                    // Check if it's actually mermaid content
                    const mermaidCode = match[1].trim();
                    const isMermaid = 
                        mermaidCode.startsWith('graph ') ||
                        mermaidCode.startsWith('pie ') ||
                        mermaidCode.startsWith('flowchart ') ||
                        mermaidCode.startsWith('sequenceDiagram') ||
                        mermaidCode.startsWith('gantt') ||
                        mermaidCode.startsWith('classDiagram') ||
                        mermaidCode.startsWith('stateDiagram') ||
                        mermaidCode.startsWith('erDiagram') ||
                        mermaidCode.startsWith('journey') ||
                        mermaidCode.startsWith('gitGraph');
                    
                    if (isMermaid) {
                        blocks.push({
                            type: 'mermaid',
                            content: mermaidCode
                        });
                    } else {
                        // Not a mermaid block, treat as regular code
                        blocks.push({
                            type: 'text',
                            content: match[0]  // Include the complete code block
                        });
                    }
                    
                    lastIndex = match.index + match[0].length;
                }
                
                // Add any remaining content
                if (lastIndex < content.length) {
                    blocks.push({
                        type: 'text',
                        content: content.substring(lastIndex)
                    });
                }
                
                // Render the blocks
                return blocks.map((block, index) => {
                    if (block.type === 'mermaid') {
                        return renderMermaidDiagram(block.content, `final-mermaid-${index}`);
                    } else {
                        return renderMarkdown(block.content);
                    }
                });
            };

            const renderMermaidDiagram = (code, customId) => {
                const id = customId || 'mermaid-direct-' + Math.random().toString(36).substring(2, 15);
                
                const MermaidDiagram = () => {
                    useEffect(() => {
                        const renderDiagram = () => {
                            if (window.mermaid) {
                                try {
                                    const element = document.getElementById(id);
                                    if (element && !element.classList.contains('processed')) {
                                        element.classList.add('processed');
                                        window.mermaid.init(undefined, element);
                                    }
                                } catch (e) {
                                    console.error('Error rendering mermaid diagram:', e, code);
                                }
                            }
                        };
                        
                        // Multiple attempts with delays to ensure rendering
                        renderDiagram();
                        const timers = [
                            setTimeout(renderDiagram, 100),
                            setTimeout(renderDiagram, 500),
                            setTimeout(renderDiagram, 1000)
                        ];
                        
                        return () => timers.forEach(timer => clearTimeout(timer));
                    }, []);
                    
                    return (
                        <div className="mermaid-container my-4 text-center border border-blue-100 p-4 rounded">
                            <pre className="mermaid" id={id}>{code}</pre>
                        </div>
                    );
                };
                
                return <MermaidDiagram key={id} />;
            };

            // Then in your component where you handle the final report rendering:
            const processReportContent = (content) => {
                return processMarkdownWithMermaid(content);
            };



            return (
                <div className="flex flex-col h-screen bg-blue-50 text-blue-900">
                    <header className="bg-blue-800 text-white p-4 shadow-md">
                        <h1 className="text-xl font-bold">深度研究</h1>
                    </header>
                    
                    <div className="flex-grow overflow-auto p-4">
                        {/* Step 1: Research Direction */}
                        <div ref={(el) => stepRefs.current[1] = el} className={`mb-6 p-4 bg-white rounded-lg shadow-md transition-all duration-300 ${currentStep === 1 ? 'opacity-100' : 'opacity-50'}`}>
                            <h2 className="text-lg font-bold border-b border-blue-200 pb-2 mb-4">1. 研究方向</h2>
                            
                            <div className="mb-4">
                                <label className="block text-sm font-medium mb-1">研究主题</label>
                                <input 
                                type="text" 
                                className="w-full p-2 border border-blue-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                disabled={currentStep !== 1 || isLoading}
                                value={researchTopic}
                                onChange={(e) => setResearchTopic(e.target.value)}
                                />
                            </div>
                            
                            <button 
                                className={`w-full py-2 rounded text-white font-medium transition-all duration-300 ${
                                currentStep === 1 && !isLoading && researchTopic.trim()
                                    ? 'bg-blue-600 hover:bg-blue-700 active:bg-blue-800' 
                                    : 'bg-gray-400 cursor-not-allowed'
                                }`}
                                onClick={() => {
                                    if (currentStep === 1 && !isLoading && researchTopic.trim()) {
                                        fetchThinkingData();
                                    }
                                }}
                                disabled={currentStep !== 1 || !researchTopic.trim() || isLoading}
                            >
                                {isLoading ? `开始思考中 (${countdown > 0 ? countdown : '...'})` : '开始思考'}
                            </button>
                        </div>
                        
                        {/* Step 2: Research Method */}
                        <div ref={(el) => stepRefs.current[2] = el} className={`mb-6 p-4 bg-white rounded-lg shadow-md transition-all duration-300 ${currentStep === 2 ? 'opacity-100' : 'opacity-50'}`}>
                            <h2 className="text-lg font-bold border-b border-blue-200 pb-2 mb-4">2. 提出您的想法</h2>
                            
                            <div className="mb-4 text-sm">
                                {thinkingOutput ? (
                                <div className="p-3 bg-blue-50 rounded shadow-inner">
                                    {renderMarkdown(thinkingOutput)}
                                </div>
                                ) : (
                                <p className="text-gray-500 italic">AI 思考的结果将在这里显示...</p>
                                )}
                            </div>
                            
                            <div className="mb-4">
                                <textarea 
                                className="w-full p-2 border border-blue-300 rounded h-24 focus:outline-none focus:ring-2 focus:ring-blue-500"
                                placeholder="输入回答,读取您的想法..."
                                disabled={currentStep !== 2 || researchLoading}
                                value={userThoughts}
                                onChange={(e) => setUserThoughts(e.target.value)}
                                />
                            </div>
                            
                            <button 
                                className={`w-full py-2 rounded text-white font-medium transition-all duration-300 ${
                                currentStep === 2 && !researchLoading && userThoughts.trim()
                                    ? 'bg-blue-600 hover:bg-blue-700 active:bg-blue-800' 
                                    : 'bg-gray-400 cursor-not-allowed'
                                }`}
                                onClick={() => {
                                    if (currentStep === 2 && !researchLoading && userThoughts.trim()) {
                                        fetchResearchData();
                                    }
                                }}
                                disabled={currentStep !== 2 || researchLoading || !userThoughts.trim()}
                            >
                                {researchLoading ? `开始研究中 (${researchCountdown > 0 ? researchCountdown : '...'})` : '开始研究'}
                            </button>
                        </div>
                        
                        {/* Step 3: Information Sources */}
                        <div ref={(el) => stepRefs.current[3] = el} className={`mb-6 p-4 bg-white rounded-lg shadow-md transition-all duration-300 ${currentStep === 3 ? 'opacity-100' : 'opacity-50'}`}>
                            <h2 className="text-lg font-bold border-b border-blue-200 pb-2 mb-4">3. 信息搜集</h2>
                            
                            <div className="mb-4">
                                {researchSections.length > 0 ? (
                                    researchSections.map((section, index) => (
                                        <div 
                                        key={section.id || index} 
                                        className="mb-2 border border-blue-200 rounded overflow-hidden"
                                        >
                                        <div 
                                            className="flex items-center justify-between p-3 bg-blue-100 cursor-pointer"
                                            onClick={() => toggleSection(section.id || index)}
                                        >
                                            <div className="flex items-center">
                                            <div className="w-6 h-6 rounded-full flex items-center justify-center bg-blue-500 text-white mr-2">
                                                {expandedSections[section.id || index] ? '▼' : '►'}
                                            </div>
                                            <span>{section.query}</span>
                                            </div>
                                            <div className="flex items-center">
                                            {/* Status indicator */}
                                            {currentTaskIndex > index ? (
                                                <span className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full flex items-center">
                                                <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
                                                </svg>
                                                完成
                                                </span>
                                            ) : currentTaskIndex === index && taskLoading ? (
                                                <span className="px-2 py-1 bg-yellow-100 text-yellow-700 text-xs rounded-full flex items-center">
                                                <svg className="w-4 h-4 mr-1 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                                                </svg>
                                                处理中
                                                </span>
                                            ) : currentTaskIndex < index ? (
                                                <span className="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full flex items-center">
                                                <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                                </svg>
                                                等待中
                                                </span>
                                            ) : null}
                                            </div>
                                        </div>
                                        
                                        {expandedSections[section.id || index] && (
                                            <div className="p-3 bg-white">
                                            <p className="text-sm text-gray-700 mb-2">{section.researchGoal}</p>
                                            {taskResults[section.id || index] ? (
                                                <div className="mt-4 p-3 bg-blue-50 rounded">
                                                {renderMarkdown(taskResults[section.id || index])}
                                                </div>
                                            ) : (
                                                currentTaskIndex === index && taskLoading ? (
                                                <div className="mt-4 p-3 bg-blue-50 rounded text-gray-600">
                                                    <div className="flex items-center">
                                                    <svg className="w-5 h-5 mr-2 animate-spin text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                                                    </svg>
                                                    <p>正在获取研究结果,请稍候...</p>
                                                    </div>
                                                </div>
                                                ) : (
                                                <div className="mt-4 p-3 bg-blue-50 rounded text-gray-600">
                                                    <div className="flex items-center">
                                                    <svg className="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                                    </svg>
                                                    <p>尚未获取研究结果</p>
                                                    </div>
                                                </div>
                                                )
                                            )}
                                            </div>
                                        )}
                                        </div>
                                    ))
                                    ) : (
                                    <p className="text-gray-500 italic">研究结果将在这里显示...</p>
                                    )}
                            </div>
                            
                            <div className="flex space-x-2">
                                <button 
                                className={`flex-1 py-2 rounded text-white font-medium transition-all duration-300 ${
                                    currentStep === 3 && !isLoading && !(currentTaskIndex < researchSections.length && currentTaskIndex >= 0)
                                    ? 'bg-green-600 hover:bg-green-700 active:bg-green-800' 
                                    : 'bg-gray-400 cursor-not-allowed'
                                }`}
                                onClick={() => {
                                    if (currentStep === 3 && !isLoading && !(currentTaskIndex < researchSections.length && currentTaskIndex >= 0)) {
                                    fetchReportData();
                                    goToNextStep();
                                    }
                                }}
                                disabled={currentStep !== 3 || isLoading || (currentTaskIndex < researchSections.length && currentTaskIndex >= 0)}
                                >
                                生成报告
                                </button>
                            </div>
                        </div>
                        
                        {/* Step 4: Final Report */}
                        <div ref={(el) => stepRefs.current[4] = el} className={`p-4 bg-white rounded-lg shadow-md transition-all duration-300 ${currentStep === 4 ? 'opacity-100' : 'opacity-50'}`}>
                            <h2 className="text-lg font-bold border-b border-blue-200 pb-2 mb-4">4. 最终报告</h2>
                            
                            <div 
                                ref={responseRef}
                                className="p-4 bg-blue-50 rounded min-h-64 mb-4 overflow-auto"
                            >
                                {responseContent ? processReportContent(responseContent) : '等待数据加载...'}
                            </div>
                            
                            <div className="flex space-x-2">
                                <button 
                                className={`flex-1 py-2 rounded text-white font-medium transition-all duration-300 ${
                                    currentStep === 4 && !isLoading
                                    ? 'bg-green-600 hover:bg-green-700 active:bg-green-800' 
                                    : 'bg-gray-400 cursor-not-allowed'
                                }`}
                                onClick={() => {
                                    handleDownloadPDF()
                                }}
                                >
                                导出报告
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="mt-6 py-4 bg-gray-100">
                        <div class="container mx-auto max-w-5xl px-4 text-center text-gray-600">
                            <p>© 2025 Deep Research. Create By 飙猪狂</p>
                        </div>
                    </div>
                </div>
            );
        };

        ReactDOM.render(<ResearchInterface />, document.getElementById('root'));
    </script>
</body>
</html>