File size: 80,420 Bytes
496298c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// R&D DocMap Catalog - Enhanced JavaScript Functionality

// Initialize Mermaid
mermaid.initialize({ 
    startOnLoad: false, 
    theme: 'base', 
    securityLevel: 'loose',
    themeVariables: {
        primaryColor: '#eff6ff',
        primaryTextColor: '#1e3a8a',
        primaryBorderColor: '#60a5fa',
        lineColor: '#6b7280',
        secondaryColor: '#f1f5f9',
        tertiaryColor: '#e0f2fe'
    }
});

// --- Global Variables ---
let documentsData = [];        // Main document catalog data
let lineageData = [];          // Section level lineage data
let templateData = [];         // Document template data if available
let sectionMappingData = [];   // Document section mapping data for lineage

// Flow definitions for document process visualization
const flowDefinitions = {
    "p1_sad": `graph TD; 
    subgraph Preclinical & Setup; 
    IB(IB v1):::input --> CLI-PROT-P1(Phase 1 Protocol):::core; 
    PRE-REP-TOX(Tox Report):::input --> IB; 
    PRE-REP-PK(PK Report):::input --> IB; 
    PRE-REP-CMC-STAB(Stability Report):::input --> IB; 
    CLI-PROT-P1 --> REG-SUB-IND(IND / CTA):::output; 
    CLI-PROT-P1 --> ICF(Informed Consent Form):::output; 
    CLI-PROT-P1 --> CRF(eCRF Spec):::output; 
    CLI-PROT-P1 --> CLI-PLAN-SAP(Stat Analysis Plan):::output; 
    CLI-PROT-P1 --> CLI-PLAN-DMP(Data Mgt Plan):::output; 
    CLI-PROT-P1 --> CLI-MAN-IMPHANDLE(IMP Handling Manual):::output; 
    CLI-PROT-P1 --> CMC-LABEL-IMP(IMP Label Spec):::output; 
    end; 
    
    subgraph Execution & Reporting; 
    ICF --> SiteOps[Site Operations / Enrollment]; 
    CRF --> SiteOps; 
    CLI-MAN-IMPHANDLE --> SiteOps; 
    CMC-LABEL-IMP --> SiteOps; 
    CLI-PLAN-DMP --> SiteOps; 
    SiteOps --> ClinicalData[(Clinical Database)]; 
    CLI-PLAN-SAP --> Analysis[Statistical Analysis]; 
    ClinicalData --> Analysis; 
    Analysis --> CLI-REP-CSR(Phase 1 CSR):::core; 
    ClinicalData --> CLI-REP-CSR; 
    IB --> CLI-REP-CSR; 
    end; 
    
    subgraph Updates & Follow-on; 
    CLI-REP-CSR --> IB_v2(IB Update v2):::output; 
    CLI-REP-CSR --> REG-AR(IND Annual Report / DSUR):::output; 
    CLI-REP-CSR --> CLI-PLAN-CDP(Clinical Dev Plan Update):::output; 
    end; 
    
    classDef input fill:#f3e8ff,stroke:#a855f7,color:#581c87; 
    classDef core fill:#e0f2fe,stroke:#38bdf8,color:#075985; 
    classDef output fill:#f0fdf4,stroke:#4ade80,color:#15803d; 
    
    click IB call displayDetailsAndGraphFromGraph("IB") "View Details"; 
    click PRE-REP-TOX call displayDetailsAndGraphFromGraph("PRE-REP-TOX") "View Details"; 
    click PRE-REP-PK call displayDetailsAndGraphFromGraph("PRE-REP-PK") "View Details"; 
    click PRE-REP-CMC-STAB call displayDetailsAndGraphFromGraph("PRE-REP-CMC-STAB") "View Details"; 
    click CLI-PROT-P1 call displayDetailsAndGraphFromGraph("CLI-PROT-P1") "View Details"; 
    click REG-SUB-IND call displayDetailsAndGraphFromGraph("REG-SUB-IND") "View Details"; 
    click ICF call displayDetailsAndGraphFromGraph("ICF") "View Details"; 
    click CRF call displayDetailsAndGraphFromGraph("CRF") "View Details"; 
    click CLI-PLAN-SAP call displayDetailsAndGraphFromGraph("CLI-PLAN-SAP") "View Details"; 
    click CLI-PLAN-DMP call displayDetailsAndGraphFromGraph("CLI-PLAN-DMP") "View Details"; 
    click CLI-MAN-IMPHANDLE call displayDetailsAndGraphFromGraph("CLI-MAN-IMPHANDLE") "View Details"; 
    click CMC-LABEL-IMP call displayDetailsAndGraphFromGraph("CMC-LABEL-IMP") "View Details"; 
    click CLI-REP-CSR call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details"; 
    click IB_v2 call displayDetailsAndGraphFromGraph("IB") "View Details (Latest IB)"; 
    click REG-AR call displayDetailsAndGraphFromGraph("REG-AR") "View Details"; 
    click CLI-PLAN-CDP call displayDetailsAndGraphFromGraph("CLI-PLAN-CDP") "View Details";`,
    
    "nda_submission": `graph TD; 
    subgraph Inputs; 
    CSRs(All Phase 1-3 CSRs):::input --> REG-ISS(ISS):::core; 
    CSRs --> REG-ISE(ISE):::core; 
    NonClinReps(All Nonclinical Reports):::input --> REG-CTD-M2(CTD Module 2 Summaries):::core; 
    CMCDataPkg(Full CMC Data Package):::input --> REG-CTD-M3(CTD Module 3 Quality):::core; 
    ProposedLabel(Proposed Label / SmPC):::input --> REG-CTD-M1(CTD Module 1 Admin & Label):::core; 
    end; 
    
    subgraph CTD_Assembly; 
    REG-ISS --> REG-CTD-M5(CTD Module 5 Clinical):::output; 
    REG-ISE --> REG-CTD-M5; 
    CSRs --> REG-CTD-M5; 
    NonClinReps --> REG-CTD-M4(CTD Module 4 Nonclinical):::output; 
    REG-CTD-M1 --> FullSubmission[eCTD Submission Package]; 
    REG-CTD-M2 --> FullSubmission; 
    REG-CTD-M3 --> FullSubmission; 
    REG-CTD-M4 --> FullSubmission; 
    REG-CTD-M5 --> FullSubmission; 
    end; 
    
    subgraph Submission_Output; 
    FullSubmission --> REG-SUB-NDA(NDA / MAA Submission):::final; 
    REG-SUB-NDA --> AgencyReview{Agency Review}; 
    AgencyReview --> REG-RTQ(Responses to Questions):::input; 
    REG-RTQ --> AgencyReview; 
    AgencyReview --> ApprovalDecision[Approval / Rejection]; 
    end; 
    
    classDef input fill:#fef9c3,stroke:#eab308,color:#854d0e; 
    classDef core fill:#e0f2fe,stroke:#38bdf8,color:#075985; 
    classDef output fill:#f0fdf4,stroke:#4ade80,color:#15803d; 
    classDef final fill:#fee2e2,stroke:#f87171,color:#991b1b; 
    
    click CSRs call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View CSR Details (Example)"; 
    click NonClinReps call displayDetailsAndGraphFromGraph("PRE-REP-TOX") "View Tox Report (Example)"; 
    click CMCDataPkg call displayDetailsAndGraphFromGraph("PRE-REP-CMC-PROCDEV") "View CMC Report (Example)"; 
    click ProposedLabel call displayDetailsAndGraphFromGraph("REG-LABEL-US") "View Label Details (Example)"; 
    click REG-ISS call displayDetailsAndGraphFromGraph("REG-ISS") "View Details"; 
    click REG-ISE call displayDetailsAndGraphFromGraph("REG-ISE") "View Details"; 
    click REG-CTD-M1 call displayDetailsAndGraphFromGraph("REG-CTD-M1") "View Details"; 
    click REG-CTD-M2 call displayDetailsAndGraphFromGraph("REG-CTD-M2") "View Details"; 
    click REG-CTD-M3 call displayDetailsAndGraphFromGraph("REG-CTD-M3") "View Details"; 
    click REG-CTD-M4 call displayDetailsAndGraphFromGraph("REG-CTD-M4") "View Details"; 
    click REG-CTD-M5 call displayDetailsAndGraphFromGraph("REG-CTD-M5") "View Details"; 
    click REG-SUB-NDA call displayDetailsAndGraphFromGraph("REG-SUB-NDA") "View Details"; 
    click REG-RTQ call displayDetailsAndGraphFromGraph("REG-RTQ") "View Details";`,
    
    "ind_pathway": `graph TD;
    DIS-REP-TVAL(Target Validation Report):::discovery --> DIS-REP-LO(Lead Optimization Report):::discovery;
    DIS-REP-LO --> DIS-REP-CANDSEL(Candidate Selection Report):::discovery;
    DIS-REP-CANDSEL --> PRE-PLAN-DEV(Preclinical Development Plan):::preclinical;
    PRE-PLAN-DEV --> PRE-PROT-TOX(Toxicology Study Protocol):::preclinical;
    PRE-PLAN-DEV --> PRE-PROT-PK(PK Study Protocol):::preclinical;
    PRE-PLAN-DEV --> PRE-REP-CMC-PROCDEV(CMC Process Development):::preclinical;
    PRE-PROT-TOX --> PRE-REP-TOX(Toxicology Study Report):::preclinical;
    PRE-PROT-PK --> PRE-REP-PK(PK Study Report):::preclinical;
    PRE-REP-CMC-PROCDEV --> PRE-REP-CMC-STAB(Stability Report):::preclinical;
    PRE-REP-TOX --> IB(Investigator's Brochure):::clinical;
    PRE-REP-PK --> IB;
    PRE-REP-CMC-STAB --> IB;
    IB --> REG-SUB-IND(IND Submission):::regulatory;
    IB --> CLI-PROT-P1(Phase 1 Protocol):::clinical;
    CLI-PROT-P1 --> REG-SUB-IND;
    REG-SUB-IND --> CLI-REP-CSR(Clinical Study Reports):::clinical;
    
    classDef discovery fill:#dbeafe,stroke:#3b82f6,color:#1e40af;
    classDef preclinical fill:#dcfce7,stroke:#22c55e,color:#166534;
    classDef clinical fill:#ede9fe,stroke:#8b5cf6,color:#5b21b6;
    classDef regulatory fill:#fef3c7,stroke:#f59e0b,color:#92400e;
    
    click DIS-REP-TVAL call displayDetailsAndGraphFromGraph("DIS-REP-TVAL") "View Details";
    click DIS-REP-LO call displayDetailsAndGraphFromGraph("DIS-REP-LO") "View Details";
    click DIS-REP-CANDSEL call displayDetailsAndGraphFromGraph("DIS-REP-CANDSEL") "View Details";
    click PRE-PLAN-DEV call displayDetailsAndGraphFromGraph("PRE-PLAN-DEV") "View Details";
    click PRE-PROT-TOX call displayDetailsAndGraphFromGraph("PRE-PROT-TOX") "View Details";
    click PRE-PROT-PK call displayDetailsAndGraphFromGraph("PRE-PROT-PK") "View Details";
    click PRE-REP-CMC-PROCDEV call displayDetailsAndGraphFromGraph("PRE-REP-CMC-PROCDEV") "View Details";
    click PRE-REP-TOX call displayDetailsAndGraphFromGraph("PRE-REP-TOX") "View Details";
    click PRE-REP-PK call displayDetailsAndGraphFromGraph("PRE-REP-PK") "View Details";
    click PRE-REP-CMC-STAB call displayDetailsAndGraphFromGraph("PRE-REP-CMC-STAB") "View Details";
    click IB call displayDetailsAndGraphFromGraph("IB") "View Details";
    click CLI-PROT-P1 call displayDetailsAndGraphFromGraph("CLI-PROT-P1") "View Details";
    click REG-SUB-IND call displayDetailsAndGraphFromGraph("REG-SUB-IND") "View Details";
    click CLI-REP-CSR call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details";`,
    
    "clinical_program": `graph TD;
    CLI-PLAN-TPP(Target Product Profile):::planning --> CLI-PLAN-CDP(Clinical Development Plan):::planning;
    CLI-PLAN-CDP --> CLI-PROT-P1(Phase 1 Protocol):::phase1;
    CLI-PLAN-CDP --> CLI-PROT-P2(Phase 2 Protocol):::phase2;
    CLI-PLAN-CDP --> CLI-PROT-P3(Phase 3 Protocol):::phase3;
    CLI-PROT-P1 --> ICF1(Phase 1 ICF):::phase1;
    CLI-PROT-P1 --> CRF1(Phase 1 CRF):::phase1;
    CLI-PROT-P1 --> CLI-PLAN-SAP1(Phase 1 SAP):::phase1;
    CLI-PROT-P2 --> ICF2(Phase 2 ICF):::phase2;
    CLI-PROT-P2 --> CRF2(Phase 2 CRF):::phase2;
    CLI-PROT-P2 --> CLI-PLAN-SAP2(Phase 2 SAP):::phase2;
    CLI-PROT-P3 --> ICF3(Phase 3 ICF):::phase3;
    CLI-PROT-P3 --> CRF3(Phase 3 CRF):::phase3;
    CLI-PROT-P3 --> CLI-PLAN-SAP3(Phase 3 SAP):::phase3;
    CLI-PROT-P3 --> CLI-CHARTER-DMC(DMC Charter):::phase3;
    CLI-PLAN-SAP1 --> CLI-REP-CSR1(Phase 1 CSR):::phase1;
    CLI-PLAN-SAP2 --> CLI-REP-CSR2(Phase 2 CSR):::phase2;
    CLI-PLAN-SAP3 --> CLI-REP-CSR3(Phase 3 CSR):::phase3;
    CLI-REP-CSR1 & CLI-REP-CSR2 & CLI-REP-CSR3 --> REG-ISS(Integrated Summary of Safety):::submission;
    CLI-REP-CSR2 & CLI-REP-CSR3 --> REG-ISE(Integrated Summary of Efficacy):::submission;
    REG-ISS & REG-ISE --> REG-SUB-NDA(NDA Submission):::submission;
    
    classDef planning fill:#dbeafe,stroke:#3b82f6,color:#1e40af;
    classDef phase1 fill:#ede9fe,stroke:#8b5cf6,color:#5b21b6;
    classDef phase2 fill:#fae8ff,stroke:#d946ef,color:#86198f;
    classDef phase3 fill:#fce7f3,stroke:#ec4899,color:#9d174d;
    classDef submission fill:#fee2e2,stroke:#f87171,color:#991b1b;
    
    click CLI-PLAN-TPP call displayDetailsAndGraphFromGraph("CLI-PLAN-TPP") "View Details";
    click CLI-PLAN-CDP call displayDetailsAndGraphFromGraph("CLI-PLAN-CDP") "View Details";
    click CLI-PROT-P1 call displayDetailsAndGraphFromGraph("CLI-PROT-P1") "View Details";
    click CLI-PROT-P2 call displayDetailsAndGraphFromGraph("CLI-PROT-P2") "View Details";
    click CLI-PROT-P3 call displayDetailsAndGraphFromGraph("CLI-PROT-P3") "View Details";
    click ICF1 call displayDetailsAndGraphFromGraph("ICF") "View Details";
    click CRF1 call displayDetailsAndGraphFromGraph("CRF") "View Details";
    click CLI-PLAN-SAP1 call displayDetailsAndGraphFromGraph("CLI-PLAN-SAP") "View Details";
    click ICF2 call displayDetailsAndGraphFromGraph("ICF") "View Details";
    click CRF2 call displayDetailsAndGraphFromGraph("CRF") "View Details";
    click CLI-PLAN-SAP2 call displayDetailsAndGraphFromGraph("CLI-PLAN-SAP") "View Details";
    click ICF3 call displayDetailsAndGraphFromGraph("ICF") "View Details";
    click CRF3 call displayDetailsAndGraphFromGraph("CRF") "View Details";
    click CLI-PLAN-SAP3 call displayDetailsAndGraphFromGraph("CLI-PLAN-SAP") "View Details";
    click CLI-CHARTER-DMC call displayDetailsAndGraphFromGraph("CLI-CHARTER-DMC") "View Details";
    click CLI-REP-CSR1 call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details";
    click CLI-REP-CSR2 call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details";
    click CLI-REP-CSR3 call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details";
    click REG-ISS call displayDetailsAndGraphFromGraph("REG-ISS") "View Details";
    click REG-ISE call displayDetailsAndGraphFromGraph("REG-ISE") "View Details";
    click REG-SUB-NDA call displayDetailsAndGraphFromGraph("REG-SUB-NDA") "View Details";`
};

// --- DOM Elements Cache ---
const mainContentArea = document.getElementById('mainContentArea');
const homeSection = document.getElementById('home');
const documentViewWrapper = document.getElementById('documentViewWrapper');
const flowsViewWrapper = document.getElementById('flowsViewWrapper');
const dataLineageViewWrapper = document.getElementById('dataLineageViewWrapper');
const uberDepViewWrapper = document.getElementById('uberDepViewWrapper');

const searchInputDocView = document.getElementById('searchInputDocView');
const headerSearchInput = document.getElementById('headerSearchInput');
const mainTabsDocViewContainer = document.getElementById('mainTabsDocView');
const documentListDocViewContainer = document.getElementById('documentListDocView');

const flowsListContainer = document.getElementById('flowsList');
const mermaidFlowGraphContainer = document.getElementById('mermaidFlowGraph');
const flowPlaceholder = document.getElementById('flowPlaceholder');
const showExampleFlowBtnFlowView = document.getElementById('showExampleFlowBtnFlowView');

// Data Lineage Elements
const lineageDocumentSelect = document.getElementById('lineageDocumentSelect');
const lineageSectionSelect = document.getElementById('lineageSectionSelect');
const mermaidLineageGraph = document.getElementById('mermaidLineageGraph');
const lineagePlaceholder = document.getElementById('lineagePlaceholder');

// Uber Dependency Elements
const uberDepDocTypeSelect = document.getElementById('uberDepDocTypeSelect');
const uberDepPhaseSelect = document.getElementById('uberDepPhaseSelect');
const mermaidUberDepGraph = document.getElementById('mermaidUberDepGraph');
const uberDepPlaceholder = document.getElementById('uberDepPlaceholder');

const homeButton = document.getElementById('homeButton');
const breadcrumbNav = document.getElementById('breadcrumbNav');

// Modals
const showExampleFlowBtnHeader = document.getElementById('showExampleFlowBtn');
const exampleFlowModal = document.getElementById('exampleFlowModal');
const exampleMermaidGraphContainer = document.getElementById('exampleMermaidGraph');
const closeExampleModalBtn = document.getElementById('closeExampleModalBtn');
const detailsModal = document.getElementById('detailsModal');
const detailsModalTitle = document.getElementById('detailsModalTitle');
const detailsContentInModal = document.getElementById('detailsContentInModal');
const closeDetailsModalBtn = document.getElementById('closeDetailsModalBtn');
const prevDocBtn = document.getElementById('prevDocBtn');
const nextDocBtn = document.getElementById('nextDocBtn');
const loadingSpinner = document.getElementById('loadingSpinner');

// --- State Variables ---
let currentVisibleView = 'home';
let currentDocViewTab = 'All';
let currentSelectedDocId = null;
let currentSelectedFlowId = null;
let currentDocListIndices = { prev: null, next: null };
let currentLineageDocId = null;
let currentLineageSectionId = null;

// --- Utility Functions ---
function getDocNameById(docId) {
    const doc = documentsData.find(d => d.Doc_ID_Type === docId);
    return doc ? (doc.Document_Name.split('(')[0].trim() || doc.Document_Name) : docId;
}

function extractDocIDs(text) {
    if (!text || documentsData.length === 0) return [];
    const knownIDs = new Set(documentsData.map(doc => doc.Doc_ID_Type));
    const potentialIDs = text.match(/[A-Z0-9]+(?:-[A-Z0-9]+)*\b/g) || [];
    return potentialIDs.filter(id => knownIDs.has(id));
}

function getComplexityIcon(complexity) {
    switch (complexity?.toLowerCase()) {
        case 'low': return '<i class="lucide lucide-bar-chart text-green-500" title="Low Complexity"></i>';
        case 'low-medium': return '<i class="lucide lucide-bar-chart-2 text-lime-500" title="Low-Medium Complexity"></i>';
        case 'medium': return '<i class="lucide lucide-bar-chart-3 text-yellow-500" title="Medium Complexity"></i>';
        case 'medium-high': return '<i class="lucide lucide-bar-chart-4 text-orange-500" title="Medium-High Complexity"></i>';
        case 'high': return '<i class="lucide lucide-bar-chart-big text-red-500" title="High Complexity"></i>';
        default: return '';
    }
}

function getRegulatoryIcon(significance) {
    if (!significance) return '';
    const lowerSig = significance.toLowerCase();
    if (lowerSig.includes('submission critical')) return '<i class="lucide lucide-shield-check text-red-600" title="Submission Critical"></i>';
    if (lowerSig.includes('gcp')) return '<i class="lucide lucide-clipboard-check text-blue-600" title="GCP Relevant"></i>';
    if (lowerSig.includes('glp')) return '<i class="lucide lucide-flask-conical text-purple-600" title="GLP Relevant"></i>';
    if (lowerSig.includes('gmp')) return '<i class="lucide lucide-factory text-indigo-600" title="GMP Relevant"></i>';
    if (lowerSig.includes('gvp')) return '<i class="lucide lucide-activity text-teal-600" title="GVP Relevant"></i>';
    if (lowerSig.includes('regulatory requirement')) return '<i class="lucide lucide-shield-alert text-orange-600" title="Regulatory Requirement"></i>';
    if (lowerSig.includes('internal')) return '<i class="lucide lucide-home text-gray-500" title="Internal Governance/Strategy"></i>';
    return '<i class="lucide lucide-shield text-gray-400" title="Regulatory Significance"></i>';
}

function getMainTabIcon(tabName) {
     if (!tabName) return '<i class="lucide lucide-file-question"></i>';
     const lowerTab = tabName.toLowerCase();
     if (lowerTab.includes('discovery')) return '<i class="lucide lucide-search"></i>';
     if (lowerTab.includes('preclinical')) return '<i class="lucide lucide-flask-conical"></i>';
     if (lowerTab === 'clinical development') return '<i class="lucide lucide-users"></i>';
     if (lowerTab === 'regulatory submission') return '<i class="lucide lucide-file-check-2"></i>';
     if (lowerTab === 'post-marketing & quality') return '<i class="lucide lucide-recycle"></i>';
     if (lowerTab.includes('flows')) return '<i class="lucide lucide-git-fork"></i>';
     if (lowerTab.includes('all')) return '<i class="lucide lucide-layers"></i>';
     return '<i class="lucide lucide-folder-open"></i>';
}

function linkDocumentIDsForDetails(text) {
    if (!text || documentsData.length === 0) return 'N/A';
    const knownIDs = new Set(documentsData.map(doc => doc.Doc_ID_Type));
    let linkedText = text.replace(/(\b[A-Z0-9]+(?:-[A-Z0-9]+)*\b)/g, (match) => {
        if (knownIDs.has(match)) {
            return `<span class="doc-link" data-doc-id="${match}">${match}</span>`;
        }
        return match;
    });
    return linkedText;
}

// --- Core Rendering & View Switching ---
function switchToView(viewId, initialTab = null) {
    console.log(`Switching view to: ${viewId}, Initial Tab: ${initialTab}`);
    currentVisibleView = viewId;

    // Hide all main sections
    homeSection.classList.add('hidden-container');
    documentViewWrapper.classList.add('hidden-container');
    flowsViewWrapper.classList.add('hidden-container');
    dataLineageViewWrapper.classList.add('hidden-container');
    uberDepViewWrapper.classList.add('hidden-container');

    // Show the target section
    const targetSection = document.getElementById(viewId);
    if (targetSection) {
        targetSection.classList.remove('hidden-container');

        // Handle specific view initializations
        if (viewId === 'documentViewWrapper') {
            currentDocViewTab = initialTab || 'All';
            renderDocumentViewTabs();
            renderDocumentList();
        } else if (viewId === 'flowsViewWrapper') {
            renderFlowsList();
            mermaidFlowGraphContainer.innerHTML = '';
            flowPlaceholder.style.display = 'block';
            currentSelectedFlowId = null;
        } else if (viewId === 'dataLineageViewWrapper') {
            renderDataLineageSelectors();
            mermaidLineageGraph.innerHTML = '';
            lineagePlaceholder.style.display = 'block';
        } else if (viewId === 'uberDepViewWrapper') {
            renderUberDepFilters();
            renderUberDependencyGraph();
        } else {
            // Home view
            currentDocViewTab = 'All';
        }
    } else {
        console.error(`Target view section not found: ${viewId}. Defaulting to home.`);
        homeSection.classList.remove('hidden-container');
        currentVisibleView = 'home';
    }
    updateBreadcrumb();
    clearSelection();
}

function updateBreadcrumb() {
    breadcrumbNav.innerHTML = '';
    const homeLink = `<a href="#" data-view-target="home" class="text-blue-600 hover:underline">Home</a>`;

    if (currentVisibleView === 'home') {
        breadcrumbNav.innerHTML = `<span class="text-gray-500">Home</span>`;
    } else if (currentVisibleView === 'documentViewWrapper') {
        breadcrumbNav.innerHTML = `${homeLink} <span class="mx-2 text-gray-400">/</span> <span class="text-gray-500">Document Catalog (${currentDocViewTab})</span>`;
    } else if (currentVisibleView === 'flowsViewWrapper') {
        breadcrumbNav.innerHTML = `${homeLink} <span class="mx-2 text-gray-400">/</span> <span class="text-gray-500">Process Visualization</span>`;
    } else if (currentVisibleView === 'dataLineageViewWrapper') {
        breadcrumbNav.innerHTML = `${homeLink} <span class="mx-2 text-gray-400">/</span> <span class="text-gray-500">Section-Level Lineage</span>`;
    } else if (currentVisibleView === 'uberDepViewWrapper') {
        breadcrumbNav.innerHTML = `${homeLink} <span class="mx-2 text-gray-400">/</span> <span class="text-gray-500">DocGen Dependencies</span>`;
    }
}

// --- Document View Functions ---
function renderDocumentViewTabs() {
    const phaseMap = {
        'Discovery': 'Discovery', 'Preclinical': 'Preclinical',
        'Clinical Phase 1': 'Clinical Development', 'Clinical Phase 2': 'Clinical Development', 'Clinical Phase 3': 'Clinical Development', 'Clinical (All Phases)': 'Clinical Development',
        'Regulatory Submission': 'Regulatory Submission', 'Regulatory Submission Review Phase': 'Regulatory Submission',
        'Post-Marketing': 'Post-Marketing & Quality', 'All Phases': 'Post-Marketing & Quality',
        'Discovery, Preclinical': 'Discovery', 'Preclinical, Clinical': 'Preclinical',
        'Preclinical (End), Clinical Phase 1': 'Preclinical', 'Discovery (late), Preclinical, Clinical': 'Discovery',
        'Pre/Post-Approval':'Regulatory Submission', 'Clinical (Annual)': 'Clinical Development',
        'Preclinical / Clinical':'Preclinical', 'Clinical (Early Phase 2/End of Phase 2)': 'Clinical Development'
    };
    const uniquePhases = [...new Set(documentsData.map(doc => phaseMap[doc.Phase] || 'Other'))];
    const tabOrder = ['All', 'Discovery', 'Preclinical', 'Clinical Development', 'Regulatory Submission', 'Post-Marketing & Quality', 'Other'];
    const sortedTabs = tabOrder.filter(tab => uniquePhases.includes(tab) || tab === 'All');
    uniquePhases.forEach(phase => { if (!sortedTabs.includes(phase)) sortedTabs.push(phase); });

    let tabsHtml = '';
    sortedTabs.forEach(tabName => {
        const isActive = tabName === currentDocViewTab;
        tabsHtml += `
            <button
                data-tab-name="${tabName}"
                class="main-tab doc-view-tab px-4 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 focus:outline-none whitespace-nowrap ${isActive ? 'active' : ''}"
            >
               ${getMainTabIcon(tabName)} ${tabName}
            </button>
        `;
    });
    mainTabsDocViewContainer.innerHTML = tabsHtml;

    // Add event listeners to THESE tabs
    mainTabsDocViewContainer.querySelectorAll('.doc-view-tab').forEach(tab => {
        tab.addEventListener('click', () => {
            currentDocViewTab = tab.dataset.tabName;
            renderDocumentViewTabs();
            renderDocumentList();
            updateBreadcrumb();
            clearSelection();
        });
    });
}

function renderDocumentList() {
    if (currentVisibleView !== 'documentViewWrapper') return;

    const phaseMap = {
        'Discovery': 'Discovery', 'Preclinical': 'Preclinical',
        'Clinical Phase 1': 'Clinical Development', 'Clinical Phase 2': 'Clinical Development', 'Clinical Phase 3': 'Clinical Development', 'Clinical (All Phases)': 'Clinical Development',
        'Regulatory Submission': 'Regulatory Submission', 'Regulatory Submission Review Phase': 'Regulatory Submission',
        'Post-Marketing': 'Post-Marketing & Quality', 'All Phases': 'Post-Marketing & Quality',
        'Discovery, Preclinical': 'Discovery', 'Preclinical, Clinical': 'Preclinical',
        'Preclinical (End), Clinical Phase 1': 'Preclinical', 'Discovery (late), Preclinical, Clinical': 'Discovery',
        'Pre/Post-Approval':'Regulatory Submission', 'Clinical (Annual)': 'Clinical Development',
         'Preclinical / Clinical':'Preclinical', 'Clinical (Early Phase 2/End of Phase 2)': 'Clinical Development'
     };

    const searchTerm = searchInputDocView.value.toLowerCase();
    let filteredDocs = documentsData;

    // Apply phase filter based on currentDocViewTab
    if (currentDocViewTab !== 'All') {
        filteredDocs = filteredDocs.filter(doc => {
            const primaryPhase = phaseMap[doc.Phase] || 'Other';
            return primaryPhase === currentDocViewTab;
        });
    }

    // Apply search filter
    if (searchTerm) {
        filteredDocs = filteredDocs.filter(doc =>
            doc.Document_Name.toLowerCase().includes(searchTerm) ||
            doc.Doc_ID_Type.toLowerCase().includes(searchTerm) ||
            (doc.Sub_Phase_Discipline && doc.Sub_Phase_Discipline.toLowerCase().includes(searchTerm)) ||
            (doc.Purpose_Key_Content && doc.Purpose_Key_Content.toLowerCase().includes(searchTerm)) ||
            (doc["Authoring_Department(s)"] && doc["Authoring_Department(s)"].toLowerCase().includes(searchTerm)) ||
            (doc.Key_Metadata && doc.Key_Metadata.toLowerCase().includes(searchTerm))
        );
    }

    // Render logic with enhanced styling
    let listHtml = '';
    if (filteredDocs.length === 0) {
        listHtml = `<p class="text-gray-500 text-center py-4">No documents found ${searchTerm ? 'matching search in' : 'for'} ${currentDocViewTab === 'All' ? 'any phase' : currentDocViewTab}.</p>`;
    } else {
        const sortedDocs = filteredDocs.sort((a, b) => a.Document_Name.localeCompare(b.Document_Name));
        listHtml = '<ul class="divide-y divide-gray-200">';
        sortedDocs.forEach(doc => {
            const isSelected = doc.Doc_ID_Type === currentSelectedDocId;
            listHtml += `
                <li data-doc-id="${doc.Doc_ID_Type}" data-phase="${doc.Phase}" class="document-item doc-list-item px-3 py-3 hover:bg-blue-50 cursor-pointer text-sm flex justify-between items-start ${isSelected ? 'bg-blue-100 font-semibold' : ''}">
                    <div class="flex flex-col min-w-0 pr-2">
                        <div class="flex items-center">
                            <i class="lucide lucide-file-text text-blue-500 mr-2 flex-shrink-0"></i>
                            <span class="font-medium truncate" title="${doc.Document_Name}">${doc.Document_Name}</span>
                        </div>
                        <div class="text-xs text-gray-500 mt-1 ml-6">
                            <span class="mr-2">${doc.Doc_ID_Type}</span> • 
                            <span class="mx-2">${doc.Phase || 'N/A'}</span> • 
                            <span class="mx-2">${doc.Sub_Phase_Discipline || 'N/A'}</span>
                        </div>
                        <div class="text-xs text-gray-600 mt-1 ml-6 line-clamp-2" title="${doc.Purpose_Key_Content || 'No description available'}">
                            ${doc.Purpose_Key_Content || 'No description available'}
                        </div>
                    </div>
                    <div class="flex items-center space-x-1 flex-shrink-0">
                        ${getComplexityIcon(doc.Complexity_Authoring)}
                        ${getRegulatoryIcon(doc.Regulatory_Significance)}
                    </div>
                </li>`;
        });
        listHtml += '</ul>';
    }

    if(documentListDocViewContainer) {
        documentListDocViewContainer.innerHTML = listHtml;
    } else {
        console.error("documentListDocViewContainer element not found!");
        return;
    }

    // Add event listeners for items in THIS list
    document.querySelectorAll('#documentListDocView li.doc-list-item').forEach(item => {
        item.addEventListener('click', () => {
            currentSelectedDocId = item.dataset.docId;
            displayDetailsInModal(currentSelectedDocId);
            renderDocumentList();
        });
    });
}

function findNextPrevDocs(currentId) {
     const listItems = documentListDocViewContainer.querySelectorAll('li[data-doc-id]');
     const docIds = Array.from(listItems).map(li => li.dataset.docId);
     const currentIndex = docIds.indexOf(currentId);

     if (currentIndex === -1 || docIds.length <= 1) {
         return { prev: null, next: null };
     }
      const prevIndex = currentIndex > 0 ? currentIndex - 1 : docIds.length - 1;
      const nextIndex = currentIndex < docIds.length - 1 ? currentIndex + 1 : 0;

     return {
         prev: docIds[prevIndex],
         next: docIds[nextIndex]
     };
}

// Enhanced document details display with modern, clean card design
async function displayDetailsInModal(docId) {
     const doc = documentsData.find(d => d.Doc_ID_Type === docId);
     if (!doc) return;

     currentSelectedDocId = docId;
     detailsModalTitle.textContent = `${doc.Document_Name} (${doc.Doc_ID_Type})`;

     // Create tabs for different views
     const tabsHtml = `
        <div class="details-tabs mb-4">
            <div class="details-tab active" data-tab="info">Information</div>
            <div class="details-tab" data-tab="dependencies">Dependencies</div>
            <div class="details-tab" data-tab="sections">Sections</div>
        </div>
     `;

     // Create content sections with enhanced styling
     const infoHtml = `
        <div class="details-content active" id="tab-content-info">
            <div class="detail-card">
                <div class="detail-card-header">
                    <h3 class="detail-card-title">Document Overview</h3>
                    <span class="detail-card-badge">${doc.Phase || 'N/A'}</span>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                    <div class="space-y-4">
                        <div class="detail-card-section">
                            <span class="detail-card-label">Discipline:</span>
                            <div class="detail-card-value">${doc.Sub_Phase_Discipline || 'N/A'}</div>
                        </div>
                        
                        <div class="detail-card-section">
                            <span class="detail-card-label">Authoring Department(s):</span>
                            <div class="detail-card-value">${doc['Authoring_Department(s)'] || 'N/A'}</div>
                        </div>
                        
                        <div class="detail-card-section">
                            <span class="detail-card-label">Review/Approval Dept(s):</span>
                            <div class="detail-card-value">${doc['Review_Approval_Dept(s)'] || 'N/A'}</div>
                        </div>
                    </div>
                    
                    <div class="space-y-4">
                        <div class="detail-card-section flex items-center">
                            <span class="detail-card-label">Complexity:</span>
                            <div class="ml-2 flex items-center">${getComplexityIcon(doc.Complexity_Authoring)} ${doc.Complexity_Authoring || 'N/A'}</div>
                        </div>
                        
                        <div class="detail-card-section flex items-center">
                            <span class="detail-card-label">Regulatory Significance:</span>
                            <div class="ml-2 flex items-center">${getRegulatoryIcon(doc.Regulatory_Significance)} ${doc.Regulatory_Significance || 'N/A'}</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="detail-card mt-4">
                <div class="detail-card-header">
                    <h3 class="detail-card-title">Content & Metadata</h3>
                </div>
                
                <div class="space-y-4 mt-4">
                    <div class="detail-card-section">
                        <span class="detail-card-label">Purpose / Key Content:</span>
                        <div class="detail-card-value">${doc.Purpose_Key_Content || 'N/A'}</div>
                    </div>
                    
                    <div class="detail-card-section">
                        <span class="detail-card-label">Key Metadata:</span>
                        <div class="detail-card-value">${doc.Key_Metadata || 'N/A'}</div>
                    </div>
                </div>
            </div>
            
            <div class="detail-card mt-4">
                <div class="detail-card-header">
                    <h3 class="detail-card-title">Dependencies</h3>
                </div>
                
                <div class="space-y-4 mt-4">
                    <div class="detail-card-section">
                        <span class="detail-card-label">Input Docs/Data:</span>
                        <div class="detail-card-value">${linkDocumentIDsForDetails(doc.Input_Documents_Data_Sources) || 'N/A'}</div>
                    </div>
                    
                    <div class="detail-card-section">
                        <span class="detail-card-label">Output/Informs Docs:</span>
                        <div class="detail-card-value">${linkDocumentIDsForDetails(doc.Output_Informs_Documents) || 'N/A'}</div>
                    </div>
                </div>
            </div>
        </div>
     `;

     const dependenciesHtml = `
        <div class="details-content" id="tab-content-dependencies">
            <div id="document-graph-container" class="dependency-graph mt-3"></div>
        </div>
     `;

     // Section listing tab - for documents with section lineage data
     const relatedSections = sectionMappingData.filter(section => 
        section.Document_Name === doc.Document_Name || 
        section['Input Document (s)']?.includes(doc.Document_Name)
     );

     let sectionsHtml = `
        <div class="details-content" id="tab-content-sections">
     `;

     if (relatedSections.length > 0) {
         sectionsHtml += `
            <div class="detail-card">
                <div class="detail-card-header">
                    <h3 class="detail-card-title">Document Sections</h3>
                </div>
                <div class="mt-4 space-y-2">
         `;
         
         relatedSections.forEach(section => {
             sectionsHtml += `
                <div class="p-3 border border-gray-200 rounded-md hover:bg-blue-50 cursor-pointer" 
                     data-doc-name="${section.Document_Name}" 
                     data-section-name="${section['Output Section Name']}"
                     onclick="selectSectionForLineage('${section.Document_Name}', '${section['Output Section Name']}')">
                    <div class="font-medium text-blue-700">${section['Output Section Name']}</div>
                    <div class="text-sm text-gray-600">${section['Output Sub-section Name'] || ''}</div>
                    <div class="text-xs text-gray-500 mt-1">
                        <span class="font-medium">Input: </span>${section['Input Document (s)'] || 'N/A'}
                    </div>
                </div>
             `;
         });
         
         sectionsHtml += `
                </div>
            </div>
         `;
     } else {
         sectionsHtml += `
            <div class="text-center py-8 text-gray-500">
                <i class="lucide lucide-file-question text-4xl mb-2"></i>
                <p>No section-level mapping data available for this document.</p>
            </div>
         `;
     }
     
     sectionsHtml += `</div>`;

     // Combine all content
     detailsContentInModal.innerHTML = tabsHtml + infoHtml + dependenciesHtml + sectionsHtml;

     // Add tab switching functionality
     detailsContentInModal.querySelectorAll('.details-tab').forEach(tab => {
         tab.addEventListener('click', () => {
             // Update active tab
             detailsContentInModal.querySelectorAll('.details-tab').forEach(t => t.classList.remove('active'));
             tab.classList.add('active');
             
             // Show corresponding content
             const tabId = tab.dataset.tab;
             detailsContentInModal.querySelectorAll('.details-content').forEach(c => c.classList.remove('active'));
             document.getElementById(`tab-content-${tabId}`).classList.add('active');
             
             // If dependencies tab, render the graph
             if (tabId === 'dependencies') {
                 renderDependencyGraph(docId);
             }
         });
     });

     // Add event listeners to document links within the modal
     detailsContentInModal.querySelectorAll('.doc-link').forEach(link => {
         link.addEventListener('click', (e) => {
             displayDetailsInModal(e.target.dataset.docId);
             // Optionally update the main list highlight if visible
             if (currentVisibleView === 'documentViewWrapper') {
                 renderDocumentList();
             }
         });
     });

     // Setup Next/Prev Buttons
     currentDocListIndices = findNextPrevDocs(docId);
     prevDocBtn.disabled = !currentDocListIndices.prev;
     nextDocBtn.disabled = !currentDocListIndices.next;

     // Show Modal
     detailsModal.style.display = 'flex';
     
     // Only re-render list if doc view is active
     if (currentVisibleView === 'documentViewWrapper') {
        renderDocumentList();
     }
}

// Function to render dependency graph using Mermaid
async function renderDependencyGraph(docId) {
    const doc = documentsData.find(d => d.Doc_ID_Type === docId);
    if (!doc) return;
    
    const container = document.getElementById('document-graph-container');
    if (!container) return;
    
    // Show loading spinner
    container.innerHTML = '<div class="loading-spinner"></div>';
    
    const inputIDs = extractDocIDs(doc.Input_Documents_Data_Sources);
    const outputIDs = extractDocIDs(doc.Output_Informs_Documents);
    
    let mermaidDefinition = 'graph TD;\n';
    const centerNodeName = getDocNameById(doc.Doc_ID_Type);
    
    // Define center node with improved styling
    mermaidDefinition += `    ${doc.Doc_ID_Type}("${centerNodeName}\\n(${doc.Doc_ID_Type})"):::focus;\n`;
    
    // Define input nodes and connections
    inputIDs.forEach(inputId => {
        const inputNodeName = getDocNameById(inputId);
        mermaidDefinition += `    ${inputId}("${inputNodeName}\\n(${inputId})"):::input --> ${doc.Doc_ID_Type};\n`;
    });
    
    // Define output nodes and connections
    outputIDs.forEach(outputId => {
        const outputNodeName = getDocNameById(outputId);
        mermaidDefinition += `    ${doc.Doc_ID_Type} --> ${outputId}("${outputNodeName}\\n(${outputId})"):::output;\n`;
    });
    
    // Add class definitions for better styling
    mermaidDefinition += `    classDef focus fill:#e0f2fe,stroke:#38bdf8,stroke-width:2px,color:#075985;\n`;
    mermaidDefinition += `    classDef input fill:#f1f5f9,stroke:#94a3b8,color:#334155;\n`;
    mermaidDefinition += `    classDef output fill:#f1f5f9,stroke:#94a3b8,color:#334155;\n`;
    
    // Add click handlers for all nodes
    [doc.Doc_ID_Type, ...inputIDs, ...outputIDs].forEach(id => {
        mermaidDefinition += `    click ${id} call displayDetailsAndGraphFromModal("${id}") "View Details";\n`;
    });
    
    try {
        const graphId = `mermaid-modal-graph-${docId}-${Date.now()}`;
        const { svg } = await mermaid.render(graphId, mermaidDefinition);
        container.innerHTML = svg;
        
        // Make the SVG responsive
        const svgElement = container.querySelector('svg');
        if (svgElement) {
            svgElement.setAttribute('width', '100%');
            svgElement.setAttribute('height', '100%');
            svgElement.style.maxHeight = '400px';
        }
    } catch (error) {
        console.error("Mermaid rendering error:", error);
        container.innerHTML = `
            <div class="text-center text-red-500 py-4">
                <i class="lucide lucide-alert-triangle text-2xl mb-2"></i>
                <p>Failed to render dependency graph.</p>
            </div>
        `;
    }
}

// --- Flow Visualization Functions ---
function renderFlowsList() {
    const flowDisplayTitles = {
        "p1_sad": "Phase 1 SAD Study Documents", 
        "nda_submission": "NDA/MAA Submission Process",
        "ind_pathway": "IND Pathway Documents",
        "clinical_program": "Clinical Program Development"
    };
    
    let flowsHtml = `
        <div class="mb-4">
            <h3 class="text-lg font-semibold text-gray-700 mb-2">Document Workflows</h3>
            <p class="text-sm text-gray-500 mb-4">Select a flow to visualize document relationships and dependencies in typical R&D processes.</p>
        </div>
    `;
    
    Object.keys(flowDefinitions).forEach(id => {
        const title = flowDisplayTitles[id] || `Flow ${id}`;
        const isSelected = id === currentSelectedFlowId;
        
        flowsHtml += `
            <div class="flow-card ${isSelected ? 'active' : ''}" data-flow-id="${id}">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="lucide lucide-git-branch text-purple-500 mr-2"></i>
                        <span class="font-medium">${title}</span>
                    </div>
                    <i class="lucide lucide-chevron-right text-gray-400"></i>
                </div>
                <p class="text-xs text-gray-500 mt-1 ml-6">
                    ${id === 'p1_sad' ? 'Documents required for First-in-Human studies' : 
                      id === 'nda_submission' ? 'Regulatory submission package assembly' : 
                      id === 'ind_pathway' ? 'Discovery to IND enabling documents' :
                      id === 'clinical_program' ? 'Clinical phase documentation flow' :
                      'Document workflow visualization'}
                </p>
            </div>
        `;
    });
    
    flowsListContainer.innerHTML = flowsHtml;
    
    // Add event listeners
    flowsListContainer.querySelectorAll('.flow-card').forEach(card => {
        card.addEventListener('click', () => {
            const flowId = card.dataset.flowId;
            currentSelectedFlowId = flowId;
            displayFlowGraph(flowId);
            renderFlowsList(); // Update active state
        });
    });
}

async function displayFlowGraph(flowId) {
    const definition = flowDefinitions[flowId];
    if (!definition) {
        mermaidFlowGraphContainer.innerHTML = `
            <div class="flex flex-col items-center justify-center p-10 text-gray-500">
                <i class="lucide lucide-alert-circle text-3xl mb-3"></i>
                <p>Flow definition not found.</p>
            </div>
        `;
        flowPlaceholder.style.display = 'none';
        return;
    }
    
    // Show loading indicator
    mermaidFlowGraphContainer.innerHTML = `
        <div class="flex flex-col items-center justify-center p-10">
            <div class="loading-spinner"></div>
            <p class="text-gray-500 mt-4">Rendering flow graph...</p>
        </div>
    `;
    flowPlaceholder.style.display = 'none';
    
    try {
        if (flowsViewWrapper.classList.contains('hidden-container')) return;
        
        const clickableDefinition = definition.replace(/click ([A-Z0-9_\-]+) call displayDetailsAndGraphFromGraph/g,'click $1 call displayDetailsAndGraphFromGraph');
        const graphId = `mermaid-flow-${flowId}-${Date.now()}`;
        
        const { svg } = await mermaid.render(graphId, clickableDefinition);
        mermaidFlowGraphContainer.innerHTML = svg;
        
        // Make the SVG responsive
        const svgElement = mermaidFlowGraphContainer.querySelector('svg');
        if (svgElement) {
            svgElement.setAttribute('width', '100%');
            svgElement.setAttribute('height', '100%');
            svgElement.style.maxHeight = '700px'; // Taller to accommodate complex flows
        }
        
        // Add title and description based on flow ID
        const flowDisplayTitles = {
            "p1_sad": "Phase 1 SAD Study Documents", 
            "nda_submission": "NDA/MAA Submission Process",
            "ind_pathway": "IND Pathway Documents",
            "clinical_program": "Clinical Program Development"
        };
        
        const flowDescriptions = {
            "p1_sad": "This diagram shows the key documents needed for a Phase 1 Single Ascending Dose study, from preclinical inputs through to clinical execution and reporting.",
            "nda_submission": "The NDA/MAA submission process flow showing how various documents and data packages are assembled into a regulatory submission.",
            "ind_pathway": "Documents required from Discovery through Preclinical development to enable an IND/CTA submission.",
            "clinical_program": "The integrated flow of clinical documentation across Phases 1-3 leading to regulatory submission."
        };
        
        const title = flowDisplayTitles[flowId] || `Flow ${flowId}`;
        const description = flowDescriptions[flowId] || "Document workflow visualization";
        
        // Add title and description above the graph
        const titleContainer = document.createElement('div');
        titleContainer.className = 'mb-4';
        titleContainer.innerHTML = `
            <h3 class="text-xl font-semibold text-gray-800 mb-2">${title}</h3>
            <p class="text-sm text-gray-600">${description}</p>
        `;
        
        mermaidFlowGraphContainer.insertBefore(titleContainer, mermaidFlowGraphContainer.firstChild);
        
    } catch (error) {
        console.error(`Mermaid rendering error for flow ${flowId}:`, error);
        mermaidFlowGraphContainer.innerHTML = `
            <div class="text-center p-10">
                <i class="lucide lucide-alert-triangle text-red-500 text-3xl mb-3"></i>
                <p class="text-red-500 mb-4">Error rendering flow graph.</p>
                <div class="bg-gray-100 p-4 rounded text-xs overflow-auto max-h-60">
                    ${error.message}
                </div>
            </div>
        `;
    }
}

async function showExampleFlow() {
    const exampleDefinition = flowDefinitions['p1_sad'];
    
     try {
         // Show loading indicator
         exampleMermaidGraphContainer.innerHTML = `
            <div class="flex flex-col items-center justify-center p-10">
                <div class="loading-spinner"></div>
                <p class="text-gray-500 mt-4">Rendering example flow...</p>
            </div>
         `;
         
         const clickableDefinition = exampleDefinition.replace(/click ([A-Z0-9_\-]+) call displayDetailsAndGraphFromGraph/g, 'click $1 call displayDetailsAndGraphFromModal');
         const graphId = `example-mermaid-graph-render-${Date.now()}`;
         const { svg } = await mermaid.render(graphId, clickableDefinition);
         exampleMermaidGraphContainer.innerHTML = svg;
         
         // Add title and description
         const titleContainer = document.createElement('div');
         titleContainer.className = 'mb-4';
         titleContainer.innerHTML = `
            <h3 class="text-lg font-semibold text-gray-800 mb-2">Phase 1 SAD Study Documents</h3>
            <p class="text-sm text-gray-600">This diagram shows the key documents needed for a Phase 1 Single Ascending Dose study, from preclinical inputs through to clinical execution and reporting.</p>
         `;
         exampleMermaidGraphContainer.insertBefore(titleContainer, exampleMermaidGraphContainer.firstChild);
         
         // Make the SVG responsive
         const svgElement = exampleMermaidGraphContainer.querySelector('svg');
         if (svgElement) {
             svgElement.setAttribute('width', '100%');
             svgElement.setAttribute('height', '100%');
         }
         
         exampleFlowModal.style.display = "flex";
     } catch (error) {
         console.error("Mermaid rendering error for example:", error);
         exampleMermaidGraphContainer.innerHTML = `
            <div class="text-center p-10">
                <i class="lucide lucide-alert-triangle text-red-500 text-3xl mb-3"></i>
                <p class="text-red-500">Error rendering example flow graph.</p>
            </div>
         `;
         exampleFlowModal.style.display = "flex";
     }
}

// --- NEW: Data Lineage Functions ---
function renderDataLineageSelectors() {
    if (!lineageDocumentSelect) return;
    
    // Clear previous options
    lineageDocumentSelect.innerHTML = '<option value="">Select a document...</option>';
    lineageSectionSelect.innerHTML = '<option value="">Select a section...</option>';
    lineageSectionSelect.disabled = true;
    
    // Get unique document names from section mapping data
    const uniqueDocNames = [...new Set(sectionMappingData.map(section => section.Document_Name))];
    
    // Add options to document select
    uniqueDocNames.sort().forEach(docName => {
        lineageDocumentSelect.innerHTML += `<option value="${docName}">${docName}</option>`;
    });
    
    // Add event listener to document select
    lineageDocumentSelect.addEventListener('change', function() {
        const selectedDoc = this.value;
        
        if (selectedDoc) {
            currentLineageDocId = selectedDoc;
            lineageSectionSelect.disabled = false;
            
            // Filter sections for the selected document
            const docSections = sectionMappingData.filter(section => section.Document_Name === selectedDoc);
            
            // Clear and populate section select
            lineageSectionSelect.innerHTML = '<option value="">Select a section...</option>';
            
            // Get unique section names (avoiding duplicates)
            const uniqueSections = [...new Set(docSections.map(section => section['Output Section Name']))];
            
            uniqueSections.forEach(sectionName => {
                lineageSectionSelect.innerHTML += `<option value="${sectionName}">${sectionName}</option>`;
            });
        } else {
            lineageSectionSelect.disabled = true;
            lineageSectionSelect.innerHTML = '<option value="">Select a section...</option>';
            currentLineageDocId = null;
            lineagePlaceholder.style.display = 'block';
            mermaidLineageGraph.innerHTML = '';
        }
    });
    
    // Add event listener to section select
    lineageSectionSelect.addEventListener('change', function() {
        const selectedSection = this.value;
        
        if (selectedSection && currentLineageDocId) {
            currentLineageSectionId = selectedSection;
            renderSectionLineageGraph(currentLineageDocId, selectedSection);
        } else {
            currentLineageSectionId = null;
            lineagePlaceholder.style.display = 'block';
            mermaidLineageGraph.innerHTML = '';
        }
    });
}

// Function to select a section for lineage visualization (from document details modal)
function selectSectionForLineage(docName, sectionName) {
    // Switch to lineage view
    switchToView('dataLineageViewWrapper');
    
    // Set the selectors
    if (lineageDocumentSelect) {
        lineageDocumentSelect.value = docName;
        
        // Trigger change event to populate section select
        const event = new Event('change');
        lineageDocumentSelect.dispatchEvent(event);
        
        // Set the section selector after a small delay (to ensure it's populated)
        setTimeout(() => {
            if (lineageSectionSelect) {
                lineageSectionSelect.value = sectionName;
                
                // Trigger change event to render the graph
                lineageSectionSelect.dispatchEvent(event);
            }
        }, 100);
    }
}

// Render section lineage graph
async function renderSectionLineageGraph(documentName, sectionName) {
    if (!documentName || !sectionName) {
        lineagePlaceholder.style.display = 'block';
        mermaidLineageGraph.innerHTML = '';
        return;
    }
    
    lineagePlaceholder.style.display = 'none';
    mermaidLineageGraph.innerHTML = `
        <div class="flex flex-col items-center justify-center p-10">
            <div class="loading-spinner"></div>
            <p class="text-gray-500 mt-4">Rendering section lineage...</p>
        </div>
    `;
    
    // Filter section data to find the target section and related sections
    const targetSection = sectionMappingData.find(section => 
        section.Document_Name === documentName && 
        section['Output Section Name'] === sectionName
    );
    
    if (!targetSection) {
        mermaidLineageGraph.innerHTML = `
            <div class="text-center p-10">
                <i class="lucide lucide-alert-circle text-gray-400 text-3xl mb-3"></i>
                <p class="text-gray-500">No lineage data found for this section.</p>
            </div>
        `;
        return;
    }
    
    // Create Mermaid definition for section lineage
    let mermaidDefinition = 'graph TD;\n';
    
    // Create unique node IDs
    const targetNodeId = `${sanitizeForMermaid(documentName)}_${sanitizeForMermaid(sectionName)}`;
    
    // Create the target section node
    mermaidDefinition += `    ${targetNodeId}["${documentName}\\n${sectionName}"]:::target;\n`;
    
    // Add input documents/sections if available
    if (targetSection['Input Document (s)']) {
        const inputSources = targetSection['Input Document (s)'].split(',').map(s => s.trim());
        
        inputSources.forEach((source, idx) => {
            // Try to find if it's a specific section
            const sourceSection = source.includes(':') ? source.split(':')[1].trim() : '';
            const sourceDoc = source.includes(':') ? source.split(':')[0].trim() : source;
            
            const sourceNodeId = `input_${sanitizeForMermaid(sourceDoc)}_${idx}`;
            
            if (sourceSection) {
                mermaidDefinition += `    ${sourceNodeId}["${sourceDoc}\\n${sourceSection}"]:::input --> ${targetNodeId};\n`;
            } else {
                mermaidDefinition += `    ${sourceNodeId}["${sourceDoc}"]:::input --> ${targetNodeId};\n`;
            }
        });
    }
    
    // Find sections that use this section as input
    const outputSections = sectionMappingData.filter(section => {
        if (!section['Input Document (s)']) return false;
        
        // Check if any input source references this document and section
        const inputSources = section['Input Document (s)'].split(',').map(s => s.trim());
        return inputSources.some(source => {
            // Check for exact section reference
            if (source.includes(':')) {
                const [sourceDoc, sourceSection] = source.split(':').map(s => s.trim());
                return sourceDoc === documentName && sourceSection === sectionName;
            }
            // Check for document reference
            return source === documentName;
        });
    });
    
    // Add output sections to graph
    outputSections.forEach((outputSection, idx) => {
        const outputNodeId = `output_${sanitizeForMermaid(outputSection.Document_Name)}_${idx}`;
        
        mermaidDefinition += `    ${targetNodeId} --> ${outputNodeId}["${outputSection.Document_Name}\\n${outputSection['Output Section Name']}"]:::output;\n`;
    });
    
    // Add styling
    mermaidDefinition += `
    classDef target fill:#e0f2fe,stroke:#38bdf8,stroke-width:2px,color:#075985;
    classDef input fill:#f1f5f9,stroke:#94a3b8,color:#334155;
    classDef output fill:#f0fdf4,stroke:#4ade80,color:#15803d;
    `;
    
    try {
        const graphId = `mermaid-lineage-${Date.now()}`;
        const { svg } = await mermaid.render(graphId, mermaidDefinition);
        
        // Create title container
        const titleContainer = document.createElement('div');
        titleContainer.className = 'mb-4';
        titleContainer.innerHTML = `
            <h3 class="text-xl font-semibold text-gray-800 mb-2">Section Lineage: ${sectionName}</h3>
            <p class="text-sm text-gray-600">Document: ${documentName}</p>
            ${targetSection['Output Sub-section Name'] ? 
                `<p class="text-xs text-gray-500">Subsection: ${targetSection['Output Sub-section Name']}</p>` : ''}
        `;
        
        // Clear container and add title + SVG
        mermaidLineageGraph.innerHTML = '';
        mermaidLineageGraph.appendChild(titleContainer);
        mermaidLineageGraph.innerHTML += svg;
        
        // Make SVG responsive
        const svgElement = mermaidLineageGraph.querySelector('svg');
        if (svgElement) {
            svgElement.setAttribute('width', '100%');
            svgElement.setAttribute('height', '100%');
            svgElement.style.maxHeight = '600px';
        }
    } catch (error) {
        console.error("Mermaid rendering error for section lineage:", error);
        mermaidLineageGraph.innerHTML = `
            <div class="text-center p-10">
                <i class="lucide lucide-alert-triangle text-red-500 text-3xl mb-3"></i>
                <p class="text-red-500 mb-4">Error rendering section lineage graph.</p>
                <div class="bg-gray-100 p-4 rounded text-xs overflow-auto max-h-60">
                    ${error.message}
                </div>
            </div>
        `;
    }
}

// Helper function to sanitize text for Mermaid node IDs
function sanitizeForMermaid(text) {
    return text.replace(/[^a-zA-Z0-9]/g, '_');
}

// --- NEW: Uber Dependency View Functions ---
function renderUberDepFilters() {
    if (!uberDepDocTypeSelect || !uberDepPhaseSelect) return;
    
    // Clear previous options
    uberDepDocTypeSelect.innerHTML = '<option value="all">All Document Types</option>';
    uberDepPhaseSelect.innerHTML = '<option value="all">All Phases</option>';
    
    // Get unique document types
    const uniqueDocTypes = [...new Set(documentsData.map(doc => doc.Doc_ID_Type.split('-')[0]))];
    
    // Add options to document type select
    uniqueDocTypes.sort().forEach(docType => {
        uberDepDocTypeSelect.innerHTML += `<option value="${docType}">${docType}</option>`;
    });
    
    // Get unique phases
    const uniquePhases = [...new Set(documentsData.map(doc => doc.Phase))].filter(phase => phase);
    
    // Add options to phase select
    uniquePhases.sort().forEach(phase => {
        uberDepPhaseSelect.innerHTML += `<option value="${phase}">${phase}</option>`;
    });
    
    // Add event listeners to filters
    uberDepDocTypeSelect.addEventListener('change', renderUberDependencyGraph);
    uberDepPhaseSelect.addEventListener('change', renderUberDependencyGraph);
}

// Function to render uber dependency graph based on selected filters
async function renderUberDependencyGraph() {
    uberDepPlaceholder.style.display = 'none';
    mermaidUberDepGraph.innerHTML = `
        <div class="flex flex-col items-center justify-center p-10">
            <div class="loading-spinner"></div>
            <p class="text-gray-500 mt-4">Rendering document generation dependencies...</p>
        </div>
    `;
    
    // Get filter values
    const selectedDocType = uberDepDocTypeSelect ? uberDepDocTypeSelect.value : 'all';
    const selectedPhase = uberDepPhaseSelect ? uberDepPhaseSelect.value : 'all';
    
    // Filter documents based on selected filters
    let filteredDocs = documentsData;
    
    if (selectedDocType !== 'all') {
        filteredDocs = filteredDocs.filter(doc => doc.Doc_ID_Type.startsWith(selectedDocType));
    }
    
    if (selectedPhase !== 'all') {
        filteredDocs = filteredDocs.filter(doc => doc.Phase === selectedPhase);
    }
    
    // Limit to a reasonable number of documents for the graph
    if (filteredDocs.length > 30) {
        filteredDocs = filteredDocs.slice(0, 30);
    }
    
    // Create Mermaid definition for uber dependency graph
    let mermaidDefinition = 'graph TD;\n';
    
    // Track all dependencies to avoid duplicates
    const processedDeps = new Set();
    
    // Track all doc IDs in the graph
    const docIdsInGraph = new Set();
    
    // Process each document
    filteredDocs.forEach(doc => {
        const docId = doc.Doc_ID_Type;
        docIdsInGraph.add(docId);
        
        // Add the document node with phase-based styling
        const phaseClass = getPhaseClassForNode(doc.Phase);
        mermaidDefinition += `    ${docId}["${doc.Document_Name}\\n(${docId})"]:::${phaseClass};\n`;
        
        // Process input documents
        if (doc.Input_Documents_Data_Sources) {
            const inputIds = extractDocIDs(doc.Input_Documents_Data_Sources);
            
            inputIds.forEach(inputId => {
                if (!processedDeps.has(`${inputId}->${docId}`)) {
                    mermaidDefinition += `    ${inputId} --> ${docId};\n`;
                    processedDeps.add(`${inputId}->${docId}`);
                    docIdsInGraph.add(inputId);
                }
            });
        }
        
        // Process output documents
        if (doc.Output_Informs_Documents) {
            const outputIds = extractDocIDs(doc.Output_Informs_Documents);
            
            outputIds.forEach(outputId => {
                if (!processedDeps.has(`${docId}->${outputId}`)) {
                    mermaidDefinition += `    ${docId} --> ${outputId};\n`;
                    processedDeps.add(`${docId}->${outputId}`);
                    docIdsInGraph.add(outputId);
                }
            });
        }
    });
    
    // Add styling for different document phases
    mermaidDefinition += `
    classDef discovery fill:#dbeafe,stroke:#3b82f6,color:#1e40af;
    classDef preclinical fill:#dcfce7,stroke:#22c55e,color:#166534;
    classDef clinical fill:#ede9fe,stroke:#8b5cf6,color:#5b21b6;
    classDef regulatory fill:#fef3c7,stroke:#f59e0b,color:#92400e;
    classDef postmarketing fill:#fee2e2,stroke:#f87171,color:#991b1b;
    classDef default fill:#f1f5f9,stroke:#94a3b8,color:#334155;
    `;
    
    // Add click handlers for all nodes
    docIdsInGraph.forEach(id => {
        mermaidDefinition += `    click ${id} call displayDetailsFromUberGraph("${id}") "View Details";\n`;
    });
    
    try {
        const graphId = `mermaid-uber-dep-${Date.now()}`;
        const { svg } = await mermaid.render(graphId, mermaidDefinition);
        
        // Create title container
        const titleContainer = document.createElement('div');
        titleContainer.className = 'mb-4';
        titleContainer.innerHTML = `
            <h3 class="text-xl font-semibold text-gray-800 mb-2">Document Generation Dependencies</h3>
            <p class="text-sm text-gray-600">
                ${selectedDocType !== 'all' ? `Document Type: ${selectedDocType}` : 'All Document Types'} | 
                ${selectedPhase !== 'all' ? `Phase: ${selectedPhase}` : 'All Phases'}
            </p>
            <p class="text-xs text-gray-500 mt-1">
                Showing ${docIdsInGraph.size} documents and ${processedDeps.size} dependencies
                ${filteredDocs.length >= 30 ? ' (limited to 30 documents for readability)' : ''}
            </p>
        `;
        
        // Clear container and add title + SVG
        mermaidUberDepGraph.innerHTML = '';
        mermaidUberDepGraph.appendChild(titleContainer);
        mermaidUberDepGraph.innerHTML += svg;
        
        // Make SVG responsive
        const svgElement = mermaidUberDepGraph.querySelector('svg');
        if (svgElement) {
            svgElement.setAttribute('width', '100%');
            svgElement.setAttribute('height', '100%');
            svgElement.style.maxHeight = '800px';
        }
    } catch (error) {
        console.error("Mermaid rendering error for uber dependency graph:", error);
        mermaidUberDepGraph.innerHTML = `
            <div class="text-center p-10">
                <i class="lucide lucide-alert-triangle text-red-500 text-3xl mb-3"></i>
                <p class="text-red-500 mb-4">Error rendering dependency graph.</p>
                <div class="bg-gray-100 p-4 rounded text-xs overflow-auto max-h-60">
                    ${error.message}
                </div>
            </div>
        `;
    }
}

// Helper function to get Mermaid class for document phase
function getPhaseClassForNode(phase) {
    if (!phase) return 'default';
    
    const lowerPhase = phase.toLowerCase();
    if (lowerPhase.includes('discovery')) return 'discovery';
    if (lowerPhase.includes('preclinical')) return 'preclinical';
    if (lowerPhase.includes('clinical')) return 'clinical';
    if (lowerPhase.includes('regulatory') || lowerPhase.includes('submission')) return 'regulatory';
    if (lowerPhase.includes('post-marketing') || lowerPhase.includes('post-approval')) return 'postmarketing';
    
    return 'default';
}

// --- Callback Functions for Mermaid Graph Interactions ---
window.displayDetailsAndGraphFromGraph = async (docId) => {
    await displayDetailsInModal(docId);
    setTimeout(() => {
        if (currentVisibleView === 'documentViewWrapper') {
            const listItem = document.querySelector(`#documentListDocView li[data-doc-id="${docId}"]`);
            listItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }, 100);
};

window.displayDetailsAndGraphFromModal = async (docId) => {
    await displayDetailsInModal(docId);
    setTimeout(() => {
        if (currentVisibleView === 'documentViewWrapper') {
            const listItem = document.querySelector(`#documentListDocView li[data-doc-id="${docId}"]`);
            listItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }, 100);
};

window.displayDetailsFromUberGraph = async (docId) => {
    await displayDetailsInModal(docId);
};

function clearSelection() {
    currentSelectedDocId = null;
    if (currentVisibleView === 'documentViewWrapper') {
        renderDocumentList();
    }
}

// --- Global Search Functionality ---
function performGlobalSearch(searchTerm) {
    if (!searchTerm) return;
    
    searchTerm = searchTerm.toLowerCase();
    let results = documentsData.filter(doc => 
        doc.Document_Name.toLowerCase().includes(searchTerm) ||
        doc.Doc_ID_Type.toLowerCase().includes(searchTerm) ||
        (doc.Purpose_Key_Content && doc.Purpose_Key_Content.toLowerCase().includes(searchTerm))
    );
    
    // Switch to document view with search results
    switchToView('documentViewWrapper', 'All');
    
    // Set the search input in document view to match the global search
    searchInputDocView.value = searchTerm;
    
    // Render the filtered list
    renderDocumentList();
}

// --- Event Listeners ---
document.addEventListener('DOMContentLoaded', function() {
    // Search input specific to document view
    searchInputDocView?.addEventListener('input', renderDocumentList);

    // Global header search
    headerSearchInput?.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            performGlobalSearch(e.target.value);
        }
    });

    // Home button listener
    homeButton?.addEventListener('click', () => switchToView('home'));

    // Breadcrumb listener (delegated)
    breadcrumbNav?.addEventListener('click', (e) => {
        if (e.target.tagName === 'A' && e.target.dataset.viewTarget) {
            e.preventDefault();
            switchToView(e.target.dataset.viewTarget);
        }
    });

    // Dashboard card listeners (delegated to main content area)
    mainContentArea?.addEventListener('click', (e) => {
        const card = e.target.closest('.dashboard-card[data-target-view]');
        if (card) {
            const targetView = card.dataset.targetView;
            const initialTab = card.dataset.initialTab; // Get initial tab if specified
            if (targetView) {
                switchToView(targetView, initialTab);
            }
        }
    });

    // Example Flow Buttons (Header and Flow View)
    showExampleFlowBtnHeader?.addEventListener('click', showExampleFlow);
    showExampleFlowBtnFlowView?.addEventListener('click', showExampleFlow);

    // Modal Close Listeners
    closeExampleModalBtn?.addEventListener('click', () => exampleFlowModal.style.display = "none");
    window.addEventListener('click', (event) => { if (event.target == exampleFlowModal) exampleFlowModal.style.display = "none"; });
    closeDetailsModalBtn?.addEventListener('click', () => { detailsModal.style.display = "none"; clearSelection(); });
    window.addEventListener('click', (event) => { if (event.target == detailsModal) { detailsModal.style.display = "none"; clearSelection(); } });

    // Modal Next/Prev Button Listeners
    prevDocBtn?.addEventListener('click', () => { if (currentDocListIndices.prev) displayDetailsInModal(currentDocListIndices.prev); });
    nextDocBtn?.addEventListener('click', () => { if (currentDocListIndices.next) displayDetailsInModal(currentDocListIndices.next); });

    // Load data and initialize application
    initializeApp();
});

// --- Initialize Application and Load Data ---
async function initializeApp() {
    try {
        await Promise.all([
            loadDocumentsData(),
            loadSectionMappingData()
        ]);
        
        // Hide loading spinner
        loadingSpinner.style.display = 'none';
        
        // Initialize the home view
        switchToView('home');
        
    } catch (error) {
        console.error("Failed to initialize application:", error);
        
        // Hide spinner and show error message
        loadingSpinner.style.display = 'none';
        
        // Display error message
        mainContentArea.innerHTML = `
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative m-4" role="alert">
                <strong class="font-bold">Error!</strong>
                <span class="block sm:inline">Could not load application data. Please check your network connection and try again.</span>
                <p class="text-xs mt-1">(${error.message})</p>
            </div>
        `;
    }
}

// Function to load document data
async function loadDocumentsData() {
    const response = await fetch('documents.json');
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    documentsData = await response.json();
    console.log(`Successfully loaded ${documentsData.length} documents from documents.json`);
    
    // Process document links
    processDocumentLinks();
}

// Function to process document links to establish connections
function processDocumentLinks() {
    // Create a map to track missing Input/Output fields
    documentsData.forEach(doc => {
        if (!doc.Input_Documents_Data_Sources) {
            doc.Input_Documents_Data_Sources = '';
        }
        if (!doc.Output_Informs_Documents) {
            doc.Output_Informs_Documents = '';
        }
    });
    
    // Ensure bidirectional links
    documentsData.forEach(doc => {
        const docId = doc.Doc_ID_Type;
        
        // Process document output links
        const outputIds = extractDocIDs(doc.Output_Informs_Documents);
        outputIds.forEach(outputId => {
            const outputDoc = documentsData.find(d => d.Doc_ID_Type === outputId);
            if (outputDoc && !outputDoc.Input_Documents_Data_Sources.includes(docId)) {
                // Add this doc as input to the output doc
                outputDoc.Input_Documents_Data_Sources += outputDoc.Input_Documents_Data_Sources ? `, ${docId}` : docId;
            }
        });
        
        // Process document input links
        const inputIds = extractDocIDs(doc.Input_Documents_Data_Sources);
        inputIds.forEach(inputId => {
            const inputDoc = documentsData.find(d => d.Doc_ID_Type === inputId);
            if (inputDoc && !inputDoc.Output_Informs_Documents.includes(docId)) {
                // Add this doc as output to the input doc
                inputDoc.Output_Informs_Documents += inputDoc.Output_Informs_Documents ? `, ${docId}` : docId;
            }
        });
    });
}

// Function to load section mapping data for lineage view
async function loadSectionMappingData() {
    try {
        const response = await fetch('section_mapping.json');
        if (!response.ok) {
            console.warn(`Section mapping data not available (status: ${response.status})`);
            // Create mock data from the pasted CSV-like content for demonstration
            sectionMappingData = createMockSectionMappingData();
        } else {
            sectionMappingData = await response.json();
        }
        console.log(`Loaded ${sectionMappingData.length} section mappings`);
    } catch (error) {
        console.warn("Could not load section mapping data:", error);
        // Create mock data for demonstration
        sectionMappingData = createMockSectionMappingData();
    }
}

// Function to create mock section mapping data from the pasted content for demonstration
function createMockSectionMappingData() {
    // This would normally come from section_mapping.json
    // For now, create some sample data
    return [
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "Title Page",
            "Output Sub-section Name": "Protocol Number",
            "Input Document (s)": "Manual input",
            "Input Section(s)": "",
            "Format": ""
        },
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "Title Page",
            "Output Sub-section Name": "Date",
            "Input Document (s)": "Manual input",
            "Input Section(s)": "",
            "Format": ""
        },
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "Title Page",
            "Output Sub-section Name": "Compound name",
            "Input Document (s)": "Concept event PPT",
            "Input Section(s)": "Title page",
            "Format": ""
        },
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "Title Page",
            "Output Sub-section Name": "1 Protocol Title",
            "Input Document (s)": "Concept event PPT",
            "Input Section(s)": "Title page",
            "Format": ""
        },
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "Title Page",
            "Output Sub-section Name": "1 Brief Title",
            "Input Document (s)": "Concept event PPT",
            "Input Section(s)": "Title page",
            "Format": ""
        },
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "All Pages",
            "Output Sub-section Name": "Header : Drug Name",
            "Input Document (s)": "Concept event PPT",
            "Input Section(s)": "",
            "Format": "Client-XXXXXXX"
        },
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "Section 1: PROTOCOL SUMMARY",
            "Output Sub-section Name": "1 Protocol Title",
            "Input Document (s)": "Concept event PPT",
            "Input Section(s)": "Title page",
            "Format": ""
        },
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "Section 1: PROTOCOL SUMMARY",
            "Output Sub-section Name": "1 Brief Title",
            "Input Document (s)": "Concept event PPT",
            "Input Section(s)": "Title page",
            "Format": ""
        },
        {
            "Document_Name": "Protocol Early Phase",
            "Output Section Name": "Section 1: PROTOCOL SUMMARY",
            "Output Sub-section Name": "1 Rationale",
            "Input Document (s)": "1. Design concept ppt, 2. Investigator Brochure",
            "Input Section(s)": "Title page, study background, Introduction",
            "Format": "summary"
        },
        {
            "Document_Name": "Clinical Study Report",
            "Output Section Name": "Title of Study",
            "Output Sub-section Name": "Title Page - full protocol title",
            "Input Document (s)": "Protocol",
            "Input Section(s)": "",
            "Format": ""
        },
        {
            "Document_Name": "Clinical Study Report",
            "Output Section Name": "Investigators/Study Centers",
            "Output Sub-section Name": "",
            "Input Document (s)": "CTMS",
            "Input Section(s)": "",
            "Format": ""
        },
        {
            "Document_Name": "Clinical Study Report",
            "Output Section Name": "Study Period",
            "Output Sub-section Name": "",
            "Input Document (s)": "CTMS",
            "Input Section(s)": "",
            "Format": ""
        },
        {
            "Document_Name": "Clinical Study Report",
            "Output Section Name": "Clinical Phase",
            "Output Sub-section Name": "",
            "Input Document (s)": "Protocol",
            "Input Section(s)": "Title or Protocol Study Design Section",
            "Format": ""
        },
        {
            "Document_Name": "Clinical Study Report",
            "Output Section Name": "Introduction",
            "Output Sub-section Name": "",
            "Input Document (s)": "Protocol",
            "Input Section(s)": "Introduction,Overall Design",
            "Format": ""
        },
        {
            "Document_Name": "Clinical Study Report",
            "Output Section Name": "Objectives",
            "Output Sub-section Name": "",
            "Input Document (s)": "Protocol",
            "Input Section(s)": "Objectives and Endpoints",
            "Format": ""
        },
        {
            "Document_Name": "Pharmacy Manual",
            "Output Section Name": "Section 0: Title Page",
            "Output Sub-section Name": "PROTOCOL NUMBER",
            "Input Document (s)": "Protocol",
            "Input Section(s)": "",
            "Format": ""
        },
        {
            "Document_Name": "Pharmacy Manual",
            "Output Section Name": "Section 0: Title Page",
            "Output Sub-section Name": "Protocol Title",
            "Input Document (s)": "Protocol",
            "Input Section(s)": "",
            "Format": ""
        },
        {
            "Document_Name": "Pharmacy Manual",
            "Output Section Name": "Section 0: Title Page",
            "Output Sub-section Name": "Version",
            "Input Document (s)": "Manual input",
            "Input Section(s)": "",
            "Format": ""
        },
        {
            "Document_Name": "Pharmacy Manual",
            "Output Section Name": "Section 0: Title Page",
            "Output Sub-section Name": "Protocol Amendment",
            "Input Document (s)": "Protocol",
            "Input Section(s)": "",
            "Format": ""
        }
    ];
}