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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
// Array to store problem history versions
const problemHistory = [];
let currentHistoryIndex = -1;
// Store all refined problem suggestions
let storedRefinedProblems = {};
document.getElementById("tab1").style.display = "block";

function openTab(evt, tabName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}

function navigateProblemHistory(direction) {
    const problemInput = document.getElementById('userProblemDescription');
    console.log("Current history index:", currentHistoryIndex, "Total history:", problemHistory.length);
    
    if (direction === 'prev' && currentHistoryIndex > 0) {
        currentHistoryIndex--;
        problemInput.value = problemHistory[currentHistoryIndex];
        console.log("Moving to previous version:", currentHistoryIndex);
    } else if (direction === 'next' && currentHistoryIndex < problemHistory.length - 1) {
        currentHistoryIndex++;
        problemInput.value = problemHistory[currentHistoryIndex];
        console.log("Moving to next version:", currentHistoryIndex);
    }
    
    updateHistoryNavigation();
}

function generateQueries(event) {
    event.preventDefault();
    
    const userInput = document.getElementById('userInput').value.trim();
    if (!userInput) {
        alert('Please enter a technical problem description');
        return;
    }
    
    // Show loading indicator
    document.querySelector(".progress-text").innerHTML = "Generating key issues ... Please wait."
    document.getElementById('globalLoadingOverlay').style.display = 'flex';
    
    // Send message to Flask backend
    fetch('/generate-key-issues', {
        method: 'POST',
        body: JSON.stringify({ 'query': userInput }),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        // Hide loading indicator
        document.getElementById('globalLoadingOverlay').style.display = 'none';
        
        // Check if we have key issues in the response
        if (data.key_issues && data.key_issues.length > 0) {
            // Display the key issues
            displayKeyIssues(data.key_issues);
        } else if (data.error) {
            alert('Error: ' + data.error);
        } else {
            alert('No key issues found. Please try a different query.');
        }
    })
    .catch(error => {
        document.getElementById('globalLoadingOverlay').style.display = 'none';
        console.error('Error:', error);
        alert('There was an error communicating with the server. Please try again.');
    });
}

function performSearch(query, queryItemElement) {
    if (!query.trim()) {
        alert('Please enter a search query');
        return;
    }
    
    const loadingElement = queryItemElement.querySelector('.search-loading');
    const tableElement = queryItemElement.querySelector('.results-table');
    const tableBody = tableElement.querySelector('tbody');
    
    // Show loading and hide previous results
    loadingElement.style.display = 'block';
    tableElement.style.display = 'none';
    
    // Clear previous results
    tableBody.innerHTML = '';
    
    // Get checkbox values
    const pdfChecked = document.getElementById('pdfOption').checked;
    const patentChecked = document.getElementById('patentOption').checked;
    const webChecked = document.getElementById('webOption').checked;

    
    // Create form data with query and checkbox values
    const formData = new FormData();
    formData.append('query', query);
    formData.append('pdfOption', pdfChecked);
    formData.append('patentOption', patentChecked);
    formData.append('webOption', webChecked);

    
    // Send search request to backend
    fetch('/search', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Hide loading indicator
        loadingElement.style.display = 'none';
        
        if (data.results && data.results.length > 0) {
            // Populate table with results
            data.results.forEach(result => {
                const row = document.createElement('tr');

                const typeCell = document.createElement('td');
                typeCell.textContent = result.type;                        
                
                const titleCell = document.createElement('td');
                titleCell.textContent = result.title;
                
                const bodyCell = document.createElement('td');
                bodyCell.textContent = result.body;
                
                const urlCell = document.createElement('td');
                const urlLink = document.createElement('a');
                urlLink.href = result.url;
                urlLink.textContent = result.url;
                urlLink.className = 'url-link';
                urlLink.target = '_blank';
                urlCell.appendChild(urlLink);

                // Add "Analyze" button to the URL cell
                const analyzeButton = document.createElement('button');
                analyzeButton.textContent = 'Analyze';
                analyzeButton.className = 'action-button analyze-button';
                analyzeButton.onclick = function(e) {
                    e.preventDefault();
                    analyzePaper(result.url, queryItemElement);
                };
                urlCell.appendChild(document.createElement('br'));
                urlCell.appendChild(analyzeButton);
                
                row.appendChild(typeCell);
                row.appendChild(titleCell);
                row.appendChild(bodyCell);
                row.appendChild(urlCell);
                
                tableBody.appendChild(row);
            });
            
            // Show the table
            tableElement.style.display = 'table';
        } else {
            // No results
            const row = document.createElement('tr');
            const cell = document.createElement('td');
            cell.colSpan = 4; // Updated to 4 since we now have 4 columns with the type column
            cell.textContent = 'No results found.';
            cell.style.textAlign = 'center';
            row.appendChild(cell);
            tableBody.appendChild(row);
            tableElement.style.display = 'table';
        }
    })
    .catch(error => {
        loadingElement.style.display = 'none';
        console.error('Error:', error);
        
        // Show error in table
        const row = document.createElement('tr');
        const cell = document.createElement('td');
        cell.colSpan = 4; // Updated to 4 since we now have 4 columns with the type column
        cell.textContent = 'Error performing search. Please try again.';
        cell.style.textAlign = 'center';
        cell.style.color = 'red';
        row.appendChild(cell);
        tableBody.appendChild(row);
        tableElement.style.display = 'table';
    });
}

function analyzePaper(paperUrl, queryItemElement) {
    const patentBackground = document.getElementById('userProblemDescription').value.trim();
    if (!patentBackground) {
        alert('Please provide a patent background in the input field');
        return;
    }
    
    // Find the row containing this URL
    const rows = queryItemElement.querySelectorAll('tbody tr');
    let targetRow;
    let documentType = 'pdf'; // Default type
    
    for (const row of rows) {
        const urlLink = row.querySelector('.url-link');
        if (urlLink && urlLink.href === paperUrl) {
            targetRow = row;
            // Get the document type from the first cell of the row
            documentType = row.cells[0].textContent.toLowerCase();
            break;
        }
    }
    
    if (!targetRow) {
        alert('Could not find the paper in the results table');
        return;
    }
    
    // Check if we already have analysis columns
    let scoreCell, justificationCell;
    if (targetRow.cells.length <= 4) {
        // We need to create the cells
        scoreCell = document.createElement('td');
        scoreCell.className = 'score-cell';
        scoreCell.innerHTML = '<div class="loading-spinner"></div>';
        
        justificationCell = document.createElement('td');
        justificationCell.className = 'justification-cell';
        justificationCell.innerHTML = 'Analyzing...';
        
        targetRow.appendChild(scoreCell);
        targetRow.appendChild(justificationCell);
    } else {
        // Use existing cells
        scoreCell = targetRow.cells[4];
        justificationCell = targetRow.cells[5];
        scoreCell.innerHTML = '<div class="loading-spinner"></div>';
        justificationCell.innerHTML = 'Analyzing...';
    }
    
    // Send analysis request to backend
    fetch('/analyze', {
        method: 'POST',
        body: JSON.stringify({ 
            'patent_background': patentBackground, 
            'pdf_url': paperUrl,
            'data_type': documentType
        }),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            scoreCell.innerHTML = 'Error';
            justificationCell.innerHTML = data.error;
        } else if (data.result) {
            // Get score and justification from the result
            const result = data.result;
            const score = result.score !== undefined ? result.score : 'N/A';
            const justification = result.justification || 'No justification provided';
            
            // Update cells with results
            scoreCell.innerHTML = score;
            justificationCell.innerHTML = justification;
            
            // Color-code the score
            if (score >= 0 && score <= 5) {
                const redComponent = Math.floor((score / 5) * 255);
                const greenComponent = Math.floor(((5 - score) / 5) * 255);
                scoreCell.style.backgroundColor = `rgb(${redComponent}, ${greenComponent}, 0)`;
                scoreCell.style.color = 'white';
                scoreCell.style.fontWeight = 'bold';
                scoreCell.style.textAlign = 'center';
            }
            
            // Add "Extract Insights" button to the justify cell
            const insightsButton = document.createElement('button');
            insightsButton.textContent = 'Extract Insights';
            insightsButton.className = 'action-button insights-button';
            insightsButton.style.marginTop = '5px';
            insightsButton.style.fontSize = '0.8em';
            insightsButton.onclick = function(e) {
                e.preventDefault();
                extractInsights(paperUrl, targetRow);
            };
            justificationCell.appendChild(document.createElement('br'));
            justificationCell.appendChild(insightsButton);
        } else {
            scoreCell.innerHTML = 'No data';
            justificationCell.innerHTML = 'Analysis failed';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        scoreCell.innerHTML = 'Error';
        justificationCell.innerHTML = 'Failed to analyze paper';
    });
}

function extractInsights(paperUrl, row) {
    const patentBackground = document.getElementById('userProblemDescription').value.trim();
    if (!patentBackground) {
        alert('Please provide a patent background in the input field');
        return;
    }
    
    const documentType = row.cells[0].textContent.toLowerCase();
    
    // Check if there's already an insights row for this document
    let insightsRow = row.nextElementSibling;
    if (insightsRow && insightsRow.className === 'insights-row') {
        // Insights row already exists, get the container
        insightsContainer = insightsRow.querySelector('.insights-container');
        insightsContainer.innerHTML = '<div class="loading-spinner"></div><div>Extracting insights...</div>';
    } else {
        // Create insights row that spans across all columns
        insightsRow = document.createElement('tr');
        insightsRow.className = 'insights-row';
        
        const insightsTd = document.createElement('td');
        insightsTd.colSpan = row.cells.length;
        
        insightsContainer = document.createElement('div');
        insightsContainer.className = 'insights-container';
        insightsContainer.innerHTML = '<div class="loading-spinner"></div><div>Extracting insights...</div>';
        
        insightsTd.appendChild(insightsContainer);
        insightsRow.appendChild(insightsTd);
        
        // Insert after the current row
        row.parentNode.insertBefore(insightsRow, row.nextSibling);
    }
    
    // Store the row reference as a data attribute on the container for later access
    insightsContainer.dataset.parentRow = row.rowIndex;
    
    // Send request to extract insights
    fetch('/post_insights', {
        method: 'POST',
        body: JSON.stringify({ 
            'patent_background': patentBackground, 
            'pdf_url': paperUrl,
            'data_type': documentType
        }),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            insightsContainer.innerHTML = `<div class="error">Error: ${data.error}</div>`;
        } else if (data.result && data.result.insights) {
            // Create header with title and actions
            const insightsHeader = document.createElement('div');
            insightsHeader.className = 'insights-header';
            
            const insightsTitle = document.createElement('div');
            insightsTitle.className = 'insights-title';
            insightsTitle.textContent = 'Document Insights';
            
            const insightsActions = document.createElement('div');
            insightsActions.className = 'insights-actions';
            
            // Store the insights for this specific container
            const containerInsights = [...data.result.insights];
            insightsContainer.dataset.allInsights = JSON.stringify(containerInsights);
            
            const selectAllBtn = document.createElement('button');
            selectAllBtn.className = 'insights-button select-all-btn';
            selectAllBtn.textContent = 'Select All';
            // Use a closure to ensure the button has access to the correct container and row
            selectAllBtn.addEventListener('click', function() {
                const container = this.closest('.insights-container');
                const parentRow = row;
                const allInsights = JSON.parse(container.dataset.allInsights || '[]');
                
                const tags = container.querySelectorAll('.insight-tag');
                tags.forEach(tag => tag.classList.add('selected'));
                
                parentRow.dataset.selectedInsights = JSON.stringify(allInsights);
                parentRow.dataset.unselectedInsights = JSON.stringify([]);
                
                // Trigger check for enabling/disabling enhance button
                checkSelectedInsights();
            });
            
            const clearAllBtn = document.createElement('button');
            clearAllBtn.className = 'insights-button clear-all-btn';
            clearAllBtn.textContent = 'Clear All';
            // Use a closure to ensure the button has access to the correct container and row
            clearAllBtn.addEventListener('click', function() {
                const container = this.closest('.insights-container');
                const parentRow = row;
                const allInsights = JSON.parse(container.dataset.allInsights || '[]');
                
                const tags = container.querySelectorAll('.insight-tag');
                tags.forEach(tag => tag.classList.remove('selected'));
                
                parentRow.dataset.selectedInsights = JSON.stringify([]);
                parentRow.dataset.unselectedInsights = JSON.stringify(allInsights);
                
                // Trigger check for enabling/disabling enhance button
                checkSelectedInsights();
            });
            
            insightsActions.appendChild(selectAllBtn);
            insightsActions.appendChild(clearAllBtn);
            
            insightsHeader.appendChild(insightsTitle);
            insightsHeader.appendChild(insightsActions);
            
            // Create insight tags
            const insightsList = document.createElement('div');
            insightsList.className = 'insights-list';
            
            // Clear the container and add the new elements
            insightsContainer.innerHTML = '';
            insightsContainer.appendChild(insightsHeader);
            insightsContainer.appendChild(insightsList);
            
            // Initialize selected insights
            const selectedInsights = [];
            const unselectedInsights = [];
            
            // Add insight tags
            data.result.insights.forEach(insight => {
                const tagElement = document.createElement('div');
                tagElement.className = 'insight-tag';
                tagElement.textContent = insight;
                tagElement.addEventListener('click', function() {
                    this.classList.toggle('selected');
                    
                    // Update selected insights
                    updateSelectedInsights(row, insightsContainer);
                    
                    // Trigger check for enabling/disabling enhance button
                    checkSelectedInsights();
                });
                
                // Add to unselected by default
                // tagElement.classList.add('selected');
                unselectedInsights.push(insight);
                
                insightsList.appendChild(tagElement);
            });
            
            // Store initial selections
            row.dataset.selectedInsights = JSON.stringify(selectedInsights);
            row.dataset.unselectedInsights = JSON.stringify(unselectedInsights);
            
            // Trigger check for enabling/disabling enhance button immediately
            checkSelectedInsights();
            
        } else {
            insightsContainer.innerHTML = '<div class="error">No insights found</div>';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        insightsContainer.innerHTML = `<div class="error">Error extracting insights: ${error.message}</div>`;
    });
}

function updateSelectedInsights(row, insightsContainer) {
    const selectedInsights = [];
    const unselectedInsights = [];
    
    const tags = insightsContainer.querySelectorAll('.insight-tag');
    tags.forEach(tag => {
        if (tag.classList.contains('selected')) {
            selectedInsights.push(tag.textContent);
        } else {
            unselectedInsights.push(tag.textContent);
        }
    });
    
    row.dataset.selectedInsights = JSON.stringify(selectedInsights);
    row.dataset.unselectedInsights = JSON.stringify(unselectedInsights);
}

function checkSelectedInsights() {
    const selectedInsights = collectAllSelectedInsights();
    const enhanceButton = document.getElementById('enhanceProblemButton');
    
    if (selectedInsights.length > 0) {
        enhanceButton.classList.remove('disabled');
        enhanceButton.disabled = false;
    } else {
        enhanceButton.classList.add('disabled');
        enhanceButton.disabled = true;
    }
}

function collectAllSelectedInsights() {
    const allSelectedInsights = [];
    const queryItems = document.querySelectorAll('.query-item');
    
    queryItems.forEach(queryItem => {
        const rows = queryItem.querySelectorAll('tbody tr:not(.insights-row)');
        rows.forEach(row => {
            if (row.dataset.selectedInsights) {
                try {
                    const selectedInsights = JSON.parse(row.dataset.selectedInsights);
                    selectedInsights.forEach(insight => {
                        if (!allSelectedInsights.includes(insight)) {
                            allSelectedInsights.push(insight);
                        }
                    });
                } catch (e) {
                    console.error('Error parsing selected insights:', e);
                }
            }
        });
    });
    
    return allSelectedInsights;
}

function exportToExcel() {
    // Show loading overlay
    const loadingOverlay = document.getElementById('globalLoadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'flex';
        loadingOverlay.querySelector('.progress-text').textContent = 'Generating Excel file...';
    }
    
    try {
        // Collect all data from all tables
        const allData = [];
        const queryItems = document.querySelectorAll('.query-item');
        
        queryItems.forEach(queryItem => {
            // Get the search query text for this table
            const queryText = queryItem.querySelector('.query-field').value;
            
            // Get all rows in this table
            const rows = queryItem.querySelectorAll('tbody tr:not(.insights-row)');
            
            rows.forEach(row => {
                // Skip empty rows or error rows
                if (row.cells.length === 1 && row.cells[0].colSpan > 1) {
                    return; // Skip "No results found" rows
                }
                
                // Prepare object for this row
                const rowData = {
                    'Topic': queryText,
                    'Type': row.cells[0].textContent,
                    'Title': row.cells[1].textContent,
                    'Description': row.cells[2].textContent,
                    'URL': row.querySelector('.url-link')?.href || ''
                };
                
                // Add score and justification if they exist
                if (row.cells.length > 4) {
                    rowData['Score'] = row.cells[4].textContent;
                    rowData['Justification'] = row.cells[5].textContent.split('\n')[0]; // Only get the justification text
                } else {
                    rowData['Score'] = '';
                    rowData['Justification'] = '';
                }
                
                // Add selected and unselected insights if they exist
                if (row.dataset.selectedInsights) {
                    try {
                        const selectedInsights = JSON.parse(row.dataset.selectedInsights);
                        rowData['Selected Insights'] = selectedInsights.join('; ');
                    } catch (e) {
                        rowData['Selected Insights'] = '';
                    }
                } else {
                    rowData['Selected Insights'] = '';
                }
                
                if (row.dataset.unselectedInsights) {
                    try {
                        const unselectedInsights = JSON.parse(row.dataset.unselectedInsights);
                        rowData['Unselected Insights'] = unselectedInsights.join('; ');
                    } catch (e) {
                        rowData['Unselected Insights'] = '';
                    }
                } else {
                    rowData['Unselected Insights'] = '';
                }
                
                allData.push(rowData);
            });
        });
        
        // Check if we have any data
        if (allData.length === 0) {
            if (loadingOverlay) loadingOverlay.style.display = 'none';
            alert('No data to export. Please perform a search first.');
            return;
        }
        
        // Get all problem versions
        const problemVersions = {};
        if (problemHistory.length > 0) {
            problemHistory.forEach((problem, index) => {
                problemVersions[`Problem Version ${index + 1}`] = problem;
            });
        } else {
            // If no history, just use the current problem
            const currentProblem = document.getElementById('userProblemDescription').value.trim();
            if (currentProblem) {
                problemVersions['Problem Version 1'] = currentProblem;
            }
        }
        
        // Send to server for Excel generation
        fetch('/export-excel', {
            method: 'POST',
            body: JSON.stringify({
                'tableData': allData,
                'userQuery': document.getElementById('userProblemDescription').value,
                'problemVersions': problemVersions
            }),
            headers: { 'Content-Type': 'application/json' }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`Server error: ${response.status}`);
            }
            return response.blob();
        })
        .then(blob => {
            // Hide loading overlay
            if (loadingOverlay) loadingOverlay.style.display = 'none';
            
            // Create URL for the blob
            const url = window.URL.createObjectURL(new Blob([blob], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }));
            
            // Create a link and trigger download
            const a = document.createElement('a');
            a.href = url;
            a.download = 'patent_search_results.xlsx';
            document.body.appendChild(a);
            a.click();
            
            // Clean up
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        })
        .catch(error => {
            console.error('Error exporting to Excel:', error);
            if (loadingOverlay) loadingOverlay.style.display = 'none';
            alert(`Error exporting to Excel: ${error.message}`);
        });
    } catch (error) {
        console.error('Error preparing Excel data:', error);
        if (loadingOverlay) loadingOverlay.style.display = 'none';
        alert(`Error preparing data for export: ${error.message}`);
    }
}

function hasSearchResults() {
    const resultsContainer = document.getElementById('resultsContainer');
    const hasResults = resultsContainer && resultsContainer.style.display !== 'none';
    const hasTables = document.querySelectorAll('.results-table[style*="display: table"]').length > 0;
    return hasResults && hasTables;
}


function analyzeAllPapers() {
    // Show loading overlay
    const loadingOverlay = document.getElementById('globalLoadingOverlay');
    if (loadingOverlay) loadingOverlay.style.display = 'flex';
    if (loadingOverlay) loadingOverlay.querySelector('.progress-text').textContent = 'Analyzing all papers...';
    
    // Get all query items
    const queryItems = document.querySelectorAll('.query-item');
    let totalToAnalyze = 0;
    let completedAnalyses = 0;
    
    // Count total papers that need analysis
    queryItems.forEach(queryItem => {
        const rows = queryItem.querySelectorAll('tbody tr');
        rows.forEach(row => {
            if (row.cells.length <= 4 || row.cells[4].textContent.trim() === 'Error' || 
                row.cells[4].textContent.trim() === 'N/A' || row.cells[4].textContent.trim() === '') {
                totalToAnalyze++;
            }
        });
    });
    
    if (totalToAnalyze === 0) {
        alert('No papers need analysis');
        if (loadingOverlay) loadingOverlay.style.display = 'none';
        return;
    }
    
    // Function to update progress
    function updateProgress() {
        completedAnalyses++;
        if (loadingOverlay) {
            const progressElement = loadingOverlay.querySelector('.progress-text');
            if (progressElement) {
                progressElement.textContent = `Analyzing papers: ${completedAnalyses}/${totalToAnalyze}`;
            }
        }
        
        if (completedAnalyses >= totalToAnalyze) {
            if (loadingOverlay) loadingOverlay.style.display = 'none';
        }
    }
    
    // Analyze each paper that needs it
    queryItems.forEach(queryItem => {
        const rows = queryItem.querySelectorAll('tbody tr');
        rows.forEach(row => {
            // Check if this row needs analysis
            if (row.cells.length <= 4 || row.cells[4].textContent.trim() === 'Error' || 
                row.cells[4].textContent.trim() === 'N/A' || row.cells[4].textContent.trim() === '') {
                
                // Get the URL
                const urlLink = row.querySelector('.url-link');
                const documentType = row.cells[0].textContent.toLowerCase();
                if (urlLink && urlLink.href) {
                    // Create a promise for this analysis
                    const promise = new Promise((resolve) => {
                        // Prepare for analysis
                        const patentBackground = document.getElementById('userProblemDescription').value.trim();
                        
                        // Create score and justification cells if needed
                        let scoreCell, justificationCell;
                        if (row.cells.length <= 4) {
                            scoreCell = document.createElement('td');
                            scoreCell.className = 'score-cell';
                            scoreCell.innerHTML = '<div class="loading-spinner"></div>';
                            
                            justificationCell = document.createElement('td');
                            justificationCell.className = 'justification-cell';
                            justificationCell.innerHTML = 'Analyzing...';
                            
                            row.appendChild(scoreCell);
                            row.appendChild(justificationCell);
                        } else {
                            scoreCell = row.cells[4];
                            justificationCell = row.cells[5];
                            scoreCell.innerHTML = '<div class="loading-spinner"></div>';
                            justificationCell.innerHTML = 'Analyzing...';
                        }
                        
                        // Send analysis request
                        fetch('/analyze', {
                            method: 'POST',
                            body: JSON.stringify({ 
                                'patent_background': patentBackground, 
                                'pdf_url': urlLink.href,
                                'data_type': documentType
                            }),
                            headers: { 'Content-Type': 'application/json' }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.error) {
                                scoreCell.innerHTML = 'Error';
                                justificationCell.innerHTML = data.error;
                            } else if (data.result) {
                                // Get score and justification
                                const result = data.result;
                                const score = result.score !== undefined ? result.score : 'N/A';
                                const justification = result.justification || 'No justification provided';
                                
                                // Update cells
                                scoreCell.innerHTML = score;
                                justificationCell.innerHTML = justification;
                                
                                // Color-code score
                                if (score >= 0 && score <= 5) {
                                    const redComponent = Math.floor((score / 5) * 255);
                                    const greenComponent = Math.floor(((5 - score) / 5) * 255);
                                    scoreCell.style.backgroundColor = `rgb(${redComponent}, ${greenComponent}, 0)`;
                                    scoreCell.style.color = 'white';
                                    scoreCell.style.fontWeight = 'bold';
                                    scoreCell.style.textAlign = 'center';
                                }
                                
                                // Add "Extract Insights" button to the justify cell - for Analyze All function
                                const insightsButton = document.createElement('button');
                                insightsButton.textContent = 'Extract Insights';
                                insightsButton.className = 'action-button insights-button';
                                insightsButton.style.marginTop = '5px';
                                insightsButton.style.fontSize = '0.8em';
                                insightsButton.onclick = function(e) {
                                    e.preventDefault();
                                    extractInsights(urlLink.href, row);
                                };
                                justificationCell.appendChild(document.createElement('br'));
                                justificationCell.appendChild(insightsButton);
                            } else {
                                scoreCell.innerHTML = 'No data';
                                justificationCell.innerHTML = 'Analysis failed';
                            }
                            resolve();
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            scoreCell.innerHTML = 'Error';
                            justificationCell.innerHTML = 'Failed to analyze paper';
                            resolve();
                        });
                    });
                    
                    // When this analysis is done, update the progress
                    promise.then(() => {
                        updateProgress();
                    });
                } else {
                    // No URL found, count as completed
                    updateProgress();
                }
            }
        });
    });
}

function removeFailedAnalyses() {
    const queryItems = document.querySelectorAll('.query-item');
    let removedCount = 0;
    
    queryItems.forEach(queryItem => {
        const tbody = queryItem.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        
        rows.forEach(row => {
            if (row.cells.length > 4) {
                const scoreText = row.cells[4].textContent.trim();
                if (scoreText === 'Error' || scoreText === 'N/A' || scoreText === 'No data') {
                    tbody.removeChild(row);
                    removedCount++;
                }
            }
        });
    });
    
    // Create and display a simple notification instead of alert
    const notification = document.createElement('div');
    notification.className = 'simple-notification';
    notification.textContent = `Removed ${removedCount} papers with failed analyses`;
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.background = '#4CAF50';
    notification.style.color = 'white';
    notification.style.padding = '15px';
    notification.style.borderRadius = '5px';
    notification.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';
    notification.style.zIndex = '10000';
    
    // Add notification to the body
    document.body.appendChild(notification);
    
    // Remove notification after 3 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

function extractAllInsights() {
    const patentBackground = document.getElementById('userProblemDescription').value.trim();
    if (!patentBackground) {
        alert('Please provide a patent background in the input field');
        return;
    }
    
    // Show loading overlay
    const loadingOverlay = document.getElementById('globalLoadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'flex';
        loadingOverlay.querySelector('.progress-text').textContent = 'Extracting insights from all documents...';
    }
    
    // Get all query items
    const queryItems = document.querySelectorAll('.query-item');
    let totalDocuments = 0;
    let completedDocuments = 0;
    
    // Count total analyzed documents that need insights extraction
    const analyzedRows = [];
    queryItems.forEach(queryItem => {
        const rows = queryItem.querySelectorAll('tbody tr:not(.insights-row)');
        rows.forEach(row => {
            // Only include rows that have been analyzed (have score and justification cells)
            if (row.cells.length > 4 && row.cells[4].textContent.trim() !== 'Error' && 
                row.cells[4].textContent.trim() !== 'N/A' && row.cells[4].textContent.trim() !== '') {
                analyzedRows.push(row);
                totalDocuments++;
            }
        });
    });
    
    if (totalDocuments === 0) {
        if (loadingOverlay) loadingOverlay.style.display = 'none';
        alert('No analyzed documents found. Please analyze documents first.');
        return;
    }
    
    // Function to update progress
    function updateProgress() {
        completedDocuments++;
        if (loadingOverlay) {
            const progressElement = loadingOverlay.querySelector('.progress-text');
            if (progressElement) {
                progressElement.textContent = `Extracting insights: ${completedDocuments}/${totalDocuments}`;
            }
        }
        
        if (completedDocuments >= totalDocuments) {
            if (loadingOverlay) loadingOverlay.style.display = 'none';
            checkSelectedInsights(); // Update enhance button state based on selected insights
        }
    }
    
    // Process each analyzed document sequentially to avoid overwhelming the server
    function processNextDocument(index) {
        if (index >= analyzedRows.length) {
            return; // All documents processed
        }
        
        const row = analyzedRows[index];
        const urlLink = row.querySelector('.url-link');
        const documentType = row.cells[0].textContent.toLowerCase();
        
        if (!urlLink || !urlLink.href) {
            updateProgress();
            processNextDocument(index + 1);
            return;
        }
        
        // Check if there's already an insights row for this document
        let insightsRow = row.nextElementSibling;
        if (insightsRow && insightsRow.className === 'insights-row') {
            // Insights row already exists, get the container
            insightsContainer = insightsRow.querySelector('.insights-container');
            insightsContainer.innerHTML = '<div class="loading-spinner"></div><div>Extracting insights...</div>';
        } else {
            // Create insights row that spans across all columns
            insightsRow = document.createElement('tr');
            insightsRow.className = 'insights-row';
            
            const insightsTd = document.createElement('td');
            insightsTd.colSpan = row.cells.length;
            
            insightsContainer = document.createElement('div');
            insightsContainer.className = 'insights-container';
            insightsContainer.innerHTML = '<div class="loading-spinner"></div><div>Extracting insights...</div>';
            
            insightsTd.appendChild(insightsContainer);
            insightsRow.appendChild(insightsTd);
            
            // Insert after the current row
            row.parentNode.insertBefore(insightsRow, row.nextSibling);
        }
        
        // Store the row reference as a data attribute on the container for later access
        insightsContainer.dataset.parentRow = row.rowIndex;
        
        // Send request to extract insights
        fetch('/post_insights', {
            method: 'POST',
            body: JSON.stringify({ 
                'patent_background': patentBackground, 
                'pdf_url': urlLink.href,
                'data_type': documentType
            }),
            headers: { 'Content-Type': 'application/json' }
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                insightsContainer.innerHTML = `<div class="error">Error: ${data.error}</div>`;
            } else if (data.result && data.result.insights) {
                // Create header with title and actions
                const insightsHeader = document.createElement('div');
                insightsHeader.className = 'insights-header';
                
                const insightsTitle = document.createElement('div');
                insightsTitle.className = 'insights-title';
                insightsTitle.textContent = 'Document Insights';
                
                const insightsActions = document.createElement('div');
                insightsActions.className = 'insights-actions';
                
                // Store the insights for this specific container
                const containerInsights = [...data.result.insights];
                insightsContainer.dataset.allInsights = JSON.stringify(containerInsights);
                
                const selectAllBtn = document.createElement('button');
                selectAllBtn.className = 'insights-button select-all-btn';
                selectAllBtn.textContent = 'Select All';
                selectAllBtn.addEventListener('click', function() {
                    const container = this.closest('.insights-container');
                    const parentRow = row;
                    const allInsights = JSON.parse(container.dataset.allInsights || '[]');
                    
                    const tags = container.querySelectorAll('.insight-tag');
                    tags.forEach(tag => tag.classList.add('selected'));
                    
                    parentRow.dataset.selectedInsights = JSON.stringify(allInsights);
                    parentRow.dataset.unselectedInsights = JSON.stringify([]);
                    
                    checkSelectedInsights();
                });
                
                const clearAllBtn = document.createElement('button');
                clearAllBtn.className = 'insights-button clear-all-btn';
                clearAllBtn.textContent = 'Clear All';
                clearAllBtn.addEventListener('click', function() {
                    const container = this.closest('.insights-container');
                    const parentRow = row;
                    const allInsights = JSON.parse(container.dataset.allInsights || '[]');
                    
                    const tags = container.querySelectorAll('.insight-tag');
                    tags.forEach(tag => tag.classList.remove('selected'));
                    
                    parentRow.dataset.selectedInsights = JSON.stringify([]);
                    parentRow.dataset.unselectedInsights = JSON.stringify(allInsights);
                    
                    checkSelectedInsights();
                });
                
                insightsActions.appendChild(selectAllBtn);
                insightsActions.appendChild(clearAllBtn);
                
                insightsHeader.appendChild(insightsTitle);
                insightsHeader.appendChild(insightsActions);
                
                // Create insight tags
                const insightsList = document.createElement('div');
                insightsList.className = 'insights-list';
                
                // Clear the container and add the new elements
                insightsContainer.innerHTML = '';
                insightsContainer.appendChild(insightsHeader);
                insightsContainer.appendChild(insightsList);
                
                // Initialize selected insights
                const selectedInsights = [];
                const unselectedInsights = [];
                
                // Add insight tags
                data.result.insights.forEach(insight => {
                    const tagElement = document.createElement('div');
                    tagElement.className = 'insight-tag';
                    tagElement.textContent = insight;
                    tagElement.addEventListener('click', function() {
                        this.classList.toggle('selected');
                        updateSelectedInsights(row, insightsContainer);
                        checkSelectedInsights();
                    });
                    
                    // Add to unselected by default
                    // tagElement.classList.add('selected');
                    unselectedInsights.push(insight);
                    
                    insightsList.appendChild(tagElement);
                });
                
                // Store initial selections
                row.dataset.selectedInsights = JSON.stringify(selectedInsights);
                row.dataset.unselectedInsights = JSON.stringify(unselectedInsights);
                
            } else {
                insightsContainer.innerHTML = '<div class="error">No insights found</div>';
            }
            
            // Process next document
            updateProgress();
            processNextDocument(index + 1);
        })
        .catch(error => {
            console.error('Error:', error);
            insightsContainer.innerHTML = `<div class="error">Error extracting insights: ${error.message}</div>`;
            
            // Continue with next document even if this one failed
            updateProgress();
            processNextDocument(index + 1);
        });
    }
    
    // Start processing documents
    processNextDocument(0);
}


function groupInsightsByScore() {
    // Get all query items
    const queryItems = document.querySelectorAll('.query-item');
    let hasInsights = false;
    
    // Create structure to hold insights grouped by score
    const insightsByScore = {
        5: { insights: [], sources: [] },
        4: { insights: [], sources: [] },
        3: { insights: [], sources: [] },
        2: { insights: [], sources: [] },
        1: { insights: [], sources: [] },
        0: { insights: [], sources: [] }
    };
    
    // Collect all insights from all documents and group by score
    queryItems.forEach(queryItem => {
        const rows = queryItem.querySelectorAll('tbody tr:not(.insights-row)');
        rows.forEach(row => {
            // Skip if no score or insights
            if (row.cells.length <= 4 || !row.dataset.selectedInsights) {
                return;
            }
            
            // Get the score
            const scoreText = row.cells[4].textContent.trim();
            if (scoreText === 'Error' || scoreText === 'N/A' || isNaN(parseFloat(scoreText))) {
                return;
            }
            
            const score = Math.round(parseFloat(scoreText));
            const urlLink = row.querySelector('.url-link');
            
            if (!urlLink) return;
            
            // Get insights from this document
            try {
                const selectedInsights = JSON.parse(row.dataset.selectedInsights || '[]');
                const unselectedInsights = JSON.parse(row.dataset.unselectedInsights || '[]');
                const allInsights = [...selectedInsights, ...unselectedInsights];
                
                // Add insights to the appropriate score group
                if (score >= 0 && score <= 5 && allInsights.length > 0) {
                    hasInsights = true;
                    
                    // For all insights in this document
                    allInsights.forEach(insight => {
                        // Check if this insight is already in the group
                        const existingIndex = insightsByScore[score].insights.findIndex(i => i === insight);
                        
                        if (existingIndex === -1) {
                            // New insight
                            insightsByScore[score].insights.push(insight);
                            insightsByScore[score].sources.push({
                                url: urlLink.href,
                                title: row.cells[1].textContent.trim().substring(0, 30) + '...',
                                selected: selectedInsights.includes(insight)
                            });
                        }
                    });
                }
            } catch (e) {
                console.error('Error parsing insights:', e);
            }
        });
    });
    
    if (!hasInsights) {
        alert('No insights found. Please analyze documents and extract insights first.');
        return;
    }
    
    // Create or get the grouped insights container
    let container = document.getElementById('groupedInsightsContainer');
    if (!container) {
        container = document.createElement('div');
        container.id = 'groupedInsightsContainer';
        container.className = 'grouped-insights-container';
        
        // Insert after the problem input card
        const card = document.querySelector("#tab2 .card");
        card.parentNode.insertBefore(container, card.nextSibling);
    }
    
    // Create header
    const header = document.createElement('div');
    header.className = 'grouped-insights-header';
    header.innerHTML = `
        <div>Insights Grouped by Score</div>
        <div class="grouped-insights-actions">
            <button class="ai-select-btn pulse" id="aiSelectButton" onclick="aiSelectInsights()">AI Select Insights</button>
            <div class="grouped-insights-close" onclick="closeGroupedInsights()">&times;</div>
        </div>
    `;
    
    // Create content area
    const content = document.createElement('div');
    content.className = 'grouped-insights-content';
    
    // Create score groups
    for (let score = 5; score >= 0; score--) {
        const insights = insightsByScore[score].insights;
        const sources = insightsByScore[score].sources;
        
        if (insights.length === 0) continue;
        
        const scoreGroup = document.createElement('div');
        scoreGroup.className = 'score-group';
        scoreGroup.dataset.score = score;
        
        // Create score header
        const scoreHeader = document.createElement('div');
        scoreHeader.className = 'score-group-header';
        
        let scoreColor = '';
        if (score >= 0 && score <= 5) {
            const redComponent = Math.floor((score / 5) * 255);
            const greenComponent = Math.floor(((5 - score) / 5) * 255);
            scoreColor = `background-color: rgb(${redComponent}, ${greenComponent}, 0); color: white;`;
        }
        
        scoreHeader.innerHTML = `
            <div>
                <span style="display: inline-block; width: 25px; height: 25px; text-align: center; border-radius: 50%; ${scoreColor} font-weight: bold;">${score}</span>
                <span style="margin-left: 8px;">Score ${score} Insights (${insights.length})</span>
            </div>
            <div class="score-group-actions">
                <button class="insights-button select-score-all-btn" onclick="selectAllInScore(${score})">Select All</button>
                <button class="insights-button clear-score-all-btn" onclick="clearAllInScore(${score})">Clear All</button>
            </div>
        `;
        
        // Create insights list
        const insightsList = document.createElement('div');
        insightsList.className = 'score-insights-list';
        
        // Add each insight
        insights.forEach((insight, index) => {
            const source = sources[index];
            const tagElement = document.createElement('div');
            tagElement.className = `grouped-insight-tag${source.selected ? ' selected' : ''}`;
            tagElement.dataset.score = score;
            tagElement.dataset.index = index;
            tagElement.dataset.source = source.url;
            
            // Create insight text with source link
            tagElement.innerHTML = `
                ${insight}
                <a href="${source.url}" target="_blank" class="insight-source" title="${source.title}">${score}</a>
            `;
            
            // Add click event to toggle selection
            tagElement.addEventListener('click', function(e) {
                // Prevent clicking on the source link from toggling selection
                if (e.target.classList.contains('insight-source')) return;
                
                this.classList.toggle('selected');
                updateGroupedInsightSelections();
            });
            
            insightsList.appendChild(tagElement);
        });
        
        // Add header and list to score group
        scoreGroup.appendChild(scoreHeader);
        scoreGroup.appendChild(insightsList);
        
        // Add score group to content
        content.appendChild(scoreGroup);
    }
    
    // Clear the container and add new content
    container.innerHTML = '';
    container.appendChild(header);
    container.appendChild(content);
    
    // Show the container
    container.style.display = 'block';
    
    // Collapse all accordions
    const accordions = document.querySelectorAll('.accordion-section');
    accordions.forEach(accordion => {
        const header = accordion.querySelector('.accordion-header');
        const body = accordion.querySelector('.accordion-body');
        if (header && body && !header.classList.contains('collapsed')) {
            header.classList.add('collapsed');
            body.classList.add('collapsed');
            
            // Update the toggle icon
            const toggleIcon = header.querySelector('.toggle-icon');
            if (toggleIcon) toggleIcon.textContent = '▶';
        }
    });
    
    // Scroll to the insights container
    container.scrollIntoView({ behavior: 'smooth' });
    
    // Remove the pulse animation after a few seconds
    setTimeout(() => {
        const aiSelectBtn = document.getElementById('aiSelectButton');
        if (aiSelectBtn) {
            aiSelectBtn.classList.remove('pulse');
        }
    }, 5000);
}

function enhanceProblem() {
    const problemInput = document.getElementById('userProblemDescription');
    const originalProblem = problemInput.value.trim();
    
    if (!originalProblem) {
        alert('Please provide a technical problem description first');
        return;
    }
    
    const selectedInsights = collectAllSelectedInsights();
    if (selectedInsights.length === 0) {
        alert('Please select at least one insight to enhance the problem');
        return;
    }
    
    // Get user comments if any
    const userComments = document.getElementById('insightCommentArea')?.value || '';
    
    // If we have stored refined problems for this exact problem, just show them
    const currentProblemKey = JSON.stringify({
        problem: originalProblem,
        insights: selectedInsights.sort(),
        comments: userComments
    });
    
    if (storedRefinedProblems[currentProblemKey]) {
        showRefinedProblems(storedRefinedProblems[currentProblemKey]);
        return;
    }
    
    // Show loading overlay
    const loadingOverlay = document.getElementById('globalLoadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'flex';
        loadingOverlay.querySelector('.progress-text').textContent = 'Enhancing problem statement...';
    }
    
    // Send request to backend to refine the problem
    fetch('/refine-problem', {
        method: 'POST',
        body: JSON.stringify({
            'original_problem': originalProblem,
            'insights': selectedInsights,
            'user_comments': userComments
        }),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        // Hide loading overlay
        if (loadingOverlay) loadingOverlay.style.display = 'none';
        
        if (data.error) {
            alert(`Error: ${data.error}`);
            return;
        }
        
        if (data.result) {
            // Add current problem to history if not already there
            if (currentHistoryIndex === -1) {
                problemHistory.push(originalProblem);
                currentHistoryIndex = 0;
            }
            
            // Store the refined problems for future use
            storedRefinedProblems[currentProblemKey] = data.result;
            
            // Show refined problem options
            showRefinedProblems(data.result);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (loadingOverlay) loadingOverlay.style.display = 'none';
        alert(`Error enhancing problem: ${error.message}`);
    });
}

function closeGroupedInsights() {
    const container = document.getElementById('groupedInsightsContainer');
    if (container) {
        container.style.display = 'none';
    }
}

// Select all insights for a specific score
function selectAllInScore(score) {
    const container = document.getElementById('groupedInsightsContainer');
    const tags = container.querySelectorAll(`.grouped-insight-tag[data-score="${score}"]`);
    
    tags.forEach(tag => {
        tag.classList.add('selected');
    });
    
    updateGroupedInsightSelections();
}

// Clear all insights for a specific score
function clearAllInScore(score) {
    const container = document.getElementById('groupedInsightsContainer');
    const tags = container.querySelectorAll(`.grouped-insight-tag[data-score="${score}"]`);
    
    tags.forEach(tag => {
        tag.classList.remove('selected');
    });
    
    updateGroupedInsightSelections();
}

function updateGroupedInsightSelections() {
    // Get all selected insights from the grouped view
    const container = document.getElementById('groupedInsightsContainer');
    const selectedTags = container.querySelectorAll('.grouped-insight-tag.selected');
    
    // Create a mapping of URL to selected insights
    const selectionsBySource = {};
    
    // Process each selected tag
    selectedTags.forEach(tag => {
        const insight = tag.textContent.trim().replace(/\d+$/, '').trim(); // Remove the score number at the end
        const sourceUrl = tag.dataset.source;
        
        if (!selectionsBySource[sourceUrl]) {
            selectionsBySource[sourceUrl] = [];
        }
        
        selectionsBySource[sourceUrl].push(insight);
    });
    
    // Now update the original document rows
    const queryItems = document.querySelectorAll('.query-item');
    queryItems.forEach(queryItem => {
        const rows = queryItem.querySelectorAll('tbody tr:not(.insights-row)');
        rows.forEach(row => {
            const urlLink = row.querySelector('.url-link');
            if (!urlLink) return;
            
            const sourceUrl = urlLink.href;
            
            // If we have selections for this source
            if (selectionsBySource[sourceUrl]) {
                // Get all insights for this row
                try {
                    // Combine selected and unselected to get all insights
                    const currentSelected = JSON.parse(row.dataset.selectedInsights || '[]');
                    const currentUnselected = JSON.parse(row.dataset.unselectedInsights || '[]');
                    const allInsights = [...currentSelected, ...currentUnselected];
                    
                    // New selected and unselected based on grouped view
                    const newSelected = [];
                    const newUnselected = [];
                    
                    // Process each insight
                    allInsights.forEach(insight => {
                        if (selectionsBySource[sourceUrl].includes(insight)) {
                            newSelected.push(insight);
                        } else {
                            newUnselected.push(insight);
                        }
                    });
                    
                    // Update the dataset
                    row.dataset.selectedInsights = JSON.stringify(newSelected);
                    row.dataset.unselectedInsights = JSON.stringify(newUnselected);
                } catch (e) {
                    console.error('Error updating insights selections:', e);
                }
            }
        });
    });
    
    // Update enhance button state
    checkSelectedInsights();
}

function showRefinedProblems(result) {
    const refinedContainer = document.getElementById('refinedProblemContainer');
    const tabs = document.getElementById('refinedProblemTabs');
    const content = document.getElementById('refinedProblemContent');
    
    // Clear previous content
    tabs.innerHTML = '';
    content.innerHTML = '';
    
    // Add tabs and content for each refined problem
    let isFirst = true;
    for (const key in result) {
        if (result.hasOwnProperty(key)) {
            const problem = result[key];
            
            // Create tab
            const tab = document.createElement('div');
            tab.className = `refined-problem-tab ${isFirst ? 'active' : ''}`;
            tab.dataset.target = key;
            tab.textContent = `Option ${key.split('_')[1]}`;
            tab.onclick = function() {
                document.querySelectorAll('.refined-problem-tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.refined-problem').forEach(p => p.classList.remove('active'));
                tab.classList.add('active');
                document.getElementById(key).classList.add('active');
            };
            tabs.appendChild(tab);
            
            // Create content
            const problemDiv = document.createElement('div');
            problemDiv.className = `refined-problem ${isFirst ? 'active' : ''}`;
            problemDiv.id = key;
            
            const title = document.createElement('div');
            title.className = 'refined-problem-title';
            title.textContent = problem.title;
            
            const description = document.createElement('div');
            description.className = 'refined-problem-description';
            description.textContent = problem.description;
            
            const applyButton = document.createElement('button');
            applyButton.className = 'apply-problem-btn';
            applyButton.textContent = 'Apply This Problem';
            applyButton.onclick = function() {
                applyRefinedProblem(problem.description);
            };
            
            problemDiv.appendChild(title);
            problemDiv.appendChild(description);
            problemDiv.appendChild(applyButton);
            
            content.appendChild(problemDiv);
            
            isFirst = false;
        }
    }
    
    // Show the container
    refinedContainer.style.display = 'block';
    
    // Scroll to the container
    refinedContainer.scrollIntoView({ behavior: 'smooth' });
}

function applyRefinedProblem(problemText) {
    const problemInput = document.getElementById('userProblemDescription');
    
    // Add current problem to history
    problemHistory.push(problemInput.value);
    currentHistoryIndex = problemHistory.length - 1; // Set to latest version
    
    // Update problem text with the new version
    problemInput.value = problemText;
    
    // Now add the new version to history
    problemHistory.push(problemText);
    currentHistoryIndex = problemHistory.length - 1; // Update index to point to the newly added version
    
    // Update history navigation display
    updateHistoryNavigation();
    
    // Display is kept visible, removed: document.getElementById('refinedProblemContainer').style.display = 'none';
    
    // Focus on the problem input
    problemInput.focus();
    
    console.log("Problem history after applying:", problemHistory, "Current index:", currentHistoryIndex);
}

function updateHistoryNavigation() {
    const historyNav = document.getElementById('problemHistoryNav');
    const prevBtn = historyNav.querySelector('.history-prev');
    const nextBtn = historyNav.querySelector('.history-next');
    const status = historyNav.querySelector('.history-status');
    
    // Update buttons state
    prevBtn.classList.toggle('disabled', currentHistoryIndex <= 0);
    nextBtn.classList.toggle('disabled', currentHistoryIndex >= problemHistory.length - 1);
    
    // Update status text
    if (problemHistory.length > 0) {
        status.textContent = `Version ${currentHistoryIndex + 1} of ${problemHistory.length}`;
        historyNav.style.display = 'flex';
    } else {
        historyNav.style.display = 'none';
    }
}

function aiSelectInsights() {
    const patentBackground = document.getElementById('userProblemDescription').value.trim();
    if (!patentBackground) {
        alert('Please provide a patent background in the input field');
        return;
    }
    
    // Change button appearance to show it's working
    const aiSelectBtn = document.getElementById('aiSelectButton');
    if (aiSelectBtn) {
        aiSelectBtn.disabled = true;
        aiSelectBtn.textContent = 'AI Selecting...';
        aiSelectBtn.style.opacity = '0.7';
    }
    
    // Show loading overlay
    const loadingOverlay = document.getElementById('globalLoadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'flex';
        loadingOverlay.querySelector('.progress-text').textContent = 'AI selecting the most relevant insights...';
    }
    
    // Get all insights from all score groups
    const container = document.getElementById('groupedInsightsContainer');
    const insightTags = container.querySelectorAll('.grouped-insight-tag');
    const insights = Array.from(insightTags).map(tag => {
        return tag.textContent.trim().replace(/\d+$/, '').trim(); // Remove the score number
    });
    
    if (insights.length === 0) {
        if (loadingOverlay) loadingOverlay.style.display = 'none';
        alert('No insights found');
        return;
    }
    
    // Send request to backend to get AI selection
    fetch('/ai-select-insights', {
        method: 'POST',
        body: JSON.stringify({
            'patent_background': patentBackground,
            'insights': insights
        }),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        // Reset button appearance
        if (aiSelectBtn) {
            aiSelectBtn.disabled = false;
            aiSelectBtn.textContent = 'AI Select Insights';
            aiSelectBtn.style.opacity = '1';
        }
        
        if (loadingOverlay) loadingOverlay.style.display = 'none';
        
        if (data.error) {
            alert(`Error: ${data.error}`);
            return;
        }
        
        if (data.selected_insights && data.selected_insights.length > 0) {
            // First clear all selections
            insightTags.forEach(tag => {
                tag.classList.remove('selected');
            });
            
            // Then select the recommended insights
            insightTags.forEach(tag => {
                const insightText = tag.textContent.trim().replace(/\d+$/, '').trim();
                if (data.selected_insights.includes(insightText)) {
                    tag.classList.add('selected');
                }
            });
            
            // Update the original document rows
            updateGroupedInsightSelections();
            
            // Remove alert notification - user can see the selected insights visually
            // alert(`AI selected ${data.selected_insights.length} insights from ${insights.length} available insights`);
        } else {
            alert('AI could not identify any relevant insights to select');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        
        // Reset button appearance
        if (aiSelectBtn) {
            aiSelectBtn.disabled = false;
            aiSelectBtn.textContent = 'AI Select Insights';
            aiSelectBtn.style.opacity = '1';
        }
        
        if (loadingOverlay) loadingOverlay.style.display = 'none';
        alert(`Error using AI to select insights: ${error.message}`);
    });
}

function generateSearchQueries() {
    function addQueryField(queryText = '', container = null) {
        const queriesContainer = container || document.getElementById('queriesContainer');
        
        // Count existing query items in this container for indexing
        const queryItems = container ? 
            container.querySelectorAll('.query-item') : 
            document.getElementById('queriesContainer').querySelectorAll('.query-item');
        
        const queryIndex = queryItems.length + 1;
        
        // Create main container for this query item
        const queryItem = document.createElement('div');
        queryItem.className = 'query-item';
        
        // Create container for query field and buttons
        const queryContainer = document.createElement('div');
        queryContainer.className = 'query-container';
        
        // Input field
        const queryField = document.createElement('input');
        queryField.type = 'text';
        queryField.className = 'query-field';
        queryField.value = queryText;
        queryField.placeholder = `Search Query ${queryIndex}`;
        
        // Delete button
        const deleteButton = document.createElement('button');
        deleteButton.type = 'button';
        deleteButton.className = 'action-button delete-button';
        deleteButton.textContent = 'Delete';
        deleteButton.onclick = function() {
            queryItem.parentNode.removeChild(queryItem);
            
            // Update the placeholder numbers for remaining queries within this container
            const parent = container || document.getElementById('queriesContainer');
            const items = parent.querySelectorAll('.query-item');
            items.forEach((item, idx) => {
                const field = item.querySelector('.query-field');
                if (field) field.placeholder = `Search Query ${idx + 1}`;
            });
        };
        
        // Search button
        const searchButton = document.createElement('button');
        searchButton.type = 'button';
        searchButton.className = 'action-button search-button';
        searchButton.textContent = 'Search';
        searchButton.onclick = function() {
            performSearch(queryField.value, queryItem);
        };
        
        // Add elements to container
        queryContainer.appendChild(queryField);
        queryContainer.appendChild(searchButton);
        queryContainer.appendChild(deleteButton);
        
        // Create loading indicator for this search
        const searchLoading = document.createElement('div');
        searchLoading.className = 'search-loading';
        searchLoading.textContent = 'Searching... Please wait.';
        
        // Create table for results
        const resultsTable = document.createElement('table');
        resultsTable.className = 'results-table';
        
        // Add table header
        const tableHeader = document.createElement('thead');
        const headerRow = document.createElement('tr');
    
        const typeHeader = document.createElement('th');
        typeHeader.textContent = 'Type';
    
        const titleHeader = document.createElement('th');
        titleHeader.textContent = 'Title';
    
        const bodyHeader = document.createElement('th');
        bodyHeader.textContent = 'Description';
    
        const urlHeader = document.createElement('th');
        urlHeader.textContent = 'URL';
    
        const scoreHeader = document.createElement('th');
        scoreHeader.textContent = 'Score';
    
        const justificationHeader = document.createElement('th');
        justificationHeader.textContent = 'Justification';
    
        headerRow.appendChild(typeHeader);
        headerRow.appendChild(titleHeader);
        headerRow.appendChild(bodyHeader);
        headerRow.appendChild(urlHeader);
        headerRow.appendChild(scoreHeader);
        headerRow.appendChild(justificationHeader);
        tableHeader.appendChild(headerRow);
        
        // Add table body
        const tableBody = document.createElement('tbody');
        
        resultsTable.appendChild(tableHeader);
        resultsTable.appendChild(tableBody);
        
        // Add all elements to the query item
        queryItem.appendChild(queryContainer);
        queryItem.appendChild(searchLoading);
        queryItem.appendChild(resultsTable);
        
        // Add container to the queries list
        queriesContainer.appendChild(queryItem);
    }
    
    function createAccordionSection(timestamp) {
        const accordionSection = document.createElement('div');
        accordionSection.className = 'accordion-section';
        
        const accordionHeader = document.createElement('div');
        accordionHeader.className = 'accordion-header';
        accordionHeader.innerHTML = `
            <span>Search Results <span class="query-timestamp">${timestamp}</span></span>
            <span class="toggle-icon">▼</span>
        `;
        accordionHeader.onclick = function() {
            this.classList.toggle('collapsed');
            const body = this.nextElementSibling;
            body.classList.toggle('collapsed');
            
            // Update the toggle icon
            const toggleIcon = this.querySelector('.toggle-icon');
            if (body.classList.contains('collapsed')) {
                toggleIcon.textContent = '▶';
            } else {
                toggleIcon.textContent = '▼';
            }
        };
        
        const accordionBody = document.createElement('div');
        accordionBody.className = 'accordion-body';
        
        const accordionContent = document.createElement('div');
        accordionContent.className = 'accordion-content';
        accordionBody.appendChild(accordionContent);
        
        accordionSection.appendChild(accordionHeader);
        accordionSection.appendChild(accordionBody);
        
        return accordionSection;
    }

    const userInput = document.getElementById('userProblemDescription').value.trim();
    if (!userInput) {
        alert('Please enter a technical problem description');
        return;
    }
    
    // Show loading indicator
    document.getElementById('loadingIndicator').style.display = 'block';
    
    // Collapse all existing query sections
    const existingAccordions = document.querySelectorAll('.accordion-section');
    existingAccordions.forEach(accordion => {
        const header = accordion.querySelector('.accordion-header');
        const body = accordion.querySelector('.accordion-body');
        if (header && body && !header.classList.contains('collapsed')) {
            header.classList.add('collapsed');
            body.classList.add('collapsed');
        }
    });
    
    // Send message to Flask backend
    fetch('/chat', {
        method: 'POST',
        body: new URLSearchParams({ 'message': userInput }),
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    .then(response => response.json())
    .then(data => {
        // Hide loading indicator
        document.getElementById('loadingIndicator').style.display = 'none';
        
        try {
            // Parse the JSON string from the LLM response
            let jsonData;
            // First check if data.reply is already an object
            if (typeof data.reply === 'object') {
                jsonData = data.reply;
            } else {
                // Try to extract JSON if it's a string possibly with markdown code blocks
                const jsonString = data.reply.replace(/```json|```/g, '').trim();
                jsonData = JSON.parse(jsonString);
            }
            
            // Create a new accordion section for these search results
            const timestamp = new Date().toLocaleString();
            const accordionSection = createAccordionSection(timestamp);
            
            // Add each query from the response to this accordion
            Object.keys(jsonData).forEach(key => {
                addQueryField(jsonData[key], accordionSection.querySelector('.accordion-content'));
            });
            
            // Add the accordion to the container
            const queriesContainer = document.getElementById('queriesContainer');
            queriesContainer.insertBefore(accordionSection, queriesContainer.firstChild);
            
            // Show results container
            document.getElementById('resultsContainer').style.display = 'block';
        } catch (error) {
            console.error('Error parsing JSON:', error);
            alert('There was an error processing the response. Please try again.');
        }
    })
    .catch(error => {
        document.getElementById('loadingIndicator').style.display = 'none';
        console.error('Error:', error);
        alert('There was an error communicating with the server. Please try again.');
    });
}

function displayKeyIssues(keyIssues) {
    // Get or create the key issues container
    let keyIssuesContainer = document.getElementById('keyIssuesContainer');
    if (!keyIssuesContainer) {
        keyIssuesContainer = document.createElement('div');
        keyIssuesContainer.id = 'keyIssuesContainer';
        keyIssuesContainer.className = 'key-issues-container';
        document.getElementById('resultsContainer').appendChild(keyIssuesContainer);
    }
    
    // Clear previous content
    keyIssuesContainer.innerHTML = '';
    
    // Create header
    const header = document.createElement('h3');
    header.textContent = 'Key Issues';
    keyIssuesContainer.appendChild(header);
    
    // Create issues list
    const issuesList = document.createElement('div');
    issuesList.className = 'key-issues-list';

    const KIsubmitButton = document.createElement('button');
    KIsubmitButton.className = "btn btn-primary";
    KIsubmitButton.id = "key-issues-submit-btn";
    KIsubmitButton.textContent = "Generate problem descriptions";
    KIsubmitButton.style.marginTop = "10px";
    KIsubmitButton.onclick = generateProblemDescriptions;

    const centerButton = document.createElement("center");
    centerButton.appendChild(KIsubmitButton);

    
    // Add each key issue
    keyIssues.forEach(issue => {
        const issueCard = document.createElement('div');
        issueCard.className = 'key-issue-card';
        issueCard.dataset.id = issue.id;
        
        const issueTitle = document.createElement('div');
        issueTitle.className = 'key-issue-title';
        issueTitle.textContent = issue.title;
        
        const issueDescription = document.createElement('div');
        issueDescription.className = 'key-issue-description';
        issueDescription.textContent = issue.description;
        
        const challengesTitle = document.createElement('div');
        challengesTitle.style.fontWeight = 'bold';
        challengesTitle.style.marginTop = '10px';
        challengesTitle.textContent = 'Challenges:';
        
        const challengesList = document.createElement('ul');
        challengesList.className = 'key-issue-challenges';
        
        issue.challenges.forEach(challenge => {
            const challengeItem = document.createElement('li');
            challengeItem.textContent = challenge;
            challengesList.appendChild(challengeItem);
        });
        
        const impactTitle = document.createElement('div');
        impactTitle.style.fontWeight = 'bold';
        impactTitle.style.marginTop = '10px';
        impactTitle.textContent = 'Potential Impact:';
        
        const issueImpact = document.createElement('div');
        issueImpact.className = 'key-issue-impact';
        issueImpact.textContent = issue.potential_impact;
        
        // Add click handler to toggle selection
        issueCard.addEventListener('click', function() {
            this.classList.toggle('selected');
        });
        
        // Append all elements
        issueCard.appendChild(issueTitle);
        issueCard.appendChild(issueDescription);
        issueCard.appendChild(challengesTitle);
        issueCard.appendChild(challengesList);
        issueCard.appendChild(impactTitle);
        issueCard.appendChild(issueImpact);
        
        issuesList.appendChild(issueCard);
    });
    
    keyIssuesContainer.appendChild(issuesList);
    keyIssuesContainer.appendChild(centerButton);
    keyIssuesContainer.style.display = "block";
}

function generateProblemDescriptions(){
    let result = {
        descriptions: {},
        challenges: {}
    };

    const selectedCards = document.querySelectorAll(".key-issue-card.selected");

    selectedCards.forEach(card => {
        const userInput = document.getElementById('userInput').value.trim();
        const id = card.getAttribute("data-id");
        const description = card.querySelector('.key-issue-description').textContent.trim();
        const challenges = Array.from(card.querySelectorAll(".key-issue-challenges li")).map(challenge => challenge.textContent.trim());

        result.descriptions[id] = description;
        result.challenges[id] = challenges;
        result["technical_topic"] = userInput;
    })

    document.querySelector('.progress-text').innerHTML = "Generating problem descriptions ... This may take a while."
    document.getElementById('globalLoadingOverlay').style.display = 'flex';
    
    // Send message to Flask backend
    fetch('/create-several-probdesc', {
        method: 'POST',
        body: JSON.stringify(result),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        // Hide loading indicator
        document.getElementById('globalLoadingOverlay').style.display = 'none';
        
        // Check if we have key issues in the response
        if (data.problem_descriptions && data.problem_descriptions.length > 0) {
            // Display the key issues
            displayProblemDescriptions(data.problem_descriptions);
        } else if (data.error) {
            alert('Error: ' + data.error);
        } else {
            alert('No problem descriptions found/generated. Please try again with another or the same query.');
        }
    })
    .catch(error => {
        document.getElementById('globalLoadingOverlay').style.display = 'none';
        console.error('Error:', error);
        alert('There was an error communicating with the server. Please try again.');
    });
}

function displayProblemDescriptions(probDescs) {
    // Get or create the key issues container
    let probDescCards = document.getElementById("probDescCards");
    let probDescContainer = document.getElementById('probDescContainer');
    // Clear previous content
    probDescContainer.innerHTML = '';
    
    // Create header
    const header = document.createElement('h3');
    header.textContent = 'Problem Descriptions';
    probDescContainer.appendChild(header);
    
    // Create issues list
    const descriptionList = document.createElement('div');
    descriptionList.className = 'prob-desc-list';
    
    // Add each key issue
    probDescs.forEach((desc, index) => {
        const descCard = document.createElement('div');
        descCard.className = 'prob-desc-card';
        descCard.dataset.id = index+1;
        
        const descTitle = document.createElement('div');
        descTitle.className = 'prob-desc-title';
        descTitle.textContent = `Problem Description n°${index+1}`;
        
        const descDescription = document.createElement('div');
        descDescription.className = 'prob-desc-description';
        descDescription.textContent = desc;
        
        // Add click handler to toggle selection
        descCard.addEventListener('click', function() {
            document.getElementById("userProblemDescription").textContent = desc;
            document.getElementsByClassName("tablinks")[1].click();
        });
        
        // Append all elements
        descCard.appendChild(descTitle);
        descCard.appendChild(descDescription);
        
        descriptionList.appendChild(descCard);
    });
    
    probDescContainer.appendChild(descriptionList);
    probDescCards.style.display = "block";
}

function initRibbonAccordion() {
    const ribbon = document.querySelector('.ribbon-accordion');
    const ribbonHeader = ribbon.querySelector('.ribbon-header');
    
    ribbonHeader.addEventListener('click', function() {
        ribbon.classList.toggle('collapsed');
    });
}

function setupRibbonButtons() {
    // Generate Queries
    document.getElementById('ribbonGenerateQueriesButton').addEventListener('click', function() {
        generateSearchQueries();
    });
    
    // Analyze All
    document.getElementById('ribbonAnalyzeAllButton').addEventListener('click', function() {
        if(hasSearchResults()) {
            analyzeAllPapers();
        }
    });
    
    // Remove Failed
    document.getElementById('ribbonRemoveFailedButton').addEventListener('click', function() {
        if(hasSearchResults()) {
            removeFailedAnalyses();
        }
    });
    
    // Extract All Insights
    document.getElementById('ribbonExtractAllInsightsButton').addEventListener('click', function() {
        extractAllInsights();
    });
    
    // Group Insights
    document.getElementById('ribbonGroupInsightsButton').addEventListener('click', function() {
        groupInsightsByScore();
    });
    
    // Enhance Problem
    document.getElementById('ribbonEnhanceProblemButton').addEventListener('click', function() {
        enhanceProblem();
    });
    
    // Export to Excel
    document.getElementById('ribbonExportExcelButton').addEventListener('click', function() {
        if(hasSearchResults()) {
            exportToExcel();
        }
    });
}

initRibbonAccordion();
setupRibbonButtons();