File size: 60,065 Bytes
57a4fb6
9a0be3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57a4fb6
9a0be3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57a4fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef2f773
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
// DocMap Agent - Enhanced Script with Improved Navigation and Document Catalog
// Override renderDocumentViewTabs
const originalRenderDocumentViewTabs = window.renderDocumentViewTabs;
window.renderDocumentViewTabs = function() {
  console.log("RENDERING TABS START");
  console.log("documentsData length:", documentsData.length);
  console.log("mainTabsDocViewContainer exists:", !!mainTabsDocViewContainer);
  
  try {
    // Simple fallback tab rendering
    const tabNames = ['All', 'Discovery', 'Preclinical', 'Clinical Development', 'Regulatory Submission'];
    let tabsHtml = '';
    tabNames.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
    mainTabsDocViewContainer.querySelectorAll('.doc-view-tab').forEach(tab => {
      tab.addEventListener('click', () => {
        currentDocViewTab = tab.dataset.tabName;
        renderDocumentViewTabs();
        renderDocumentList();
        updateBreadcrumb();
        clearSelection();
      });
    });
    
    console.log("RENDERING TABS COMPLETE");
  } catch (error) {
    console.error("Error rendering tabs:", error);
  }
};

// Override renderDocumentList
const originalRenderDocumentList = window.renderDocumentList;
window.renderDocumentList = function() {
  console.log("RENDERING LIST START");
  console.log("Current view:", currentVisibleView);
  console.log("Current tab:", currentDocViewTab);
  
  try {
    if (currentVisibleView !== 'documentViewWrapper') return;
    
    // Simple implementation of document list
    const searchTerm = searchInputDocView.value.toLowerCase();
    let filteredDocs = documentsData;
    
    if (currentDocViewTab !== 'All') {
      filteredDocs = filteredDocs.filter(doc => {
        // Simplified phase mapping
        const docPhase = doc.Phase || '';
        return docPhase.includes(currentDocViewTab) || 
               (currentDocViewTab === 'Clinical Development' && docPhase.includes('Clinical'));
      });
    }
    
    if (searchTerm) {
      filteredDocs = filteredDocs.filter(doc =>
        doc.Document_Name.toLowerCase().includes(searchTerm) ||
        doc.Doc_ID_Type.toLowerCase().includes(searchTerm)
      );
    }
    
    if (filteredDocs.length === 0) {
      documentListDocViewContainer.innerHTML = `<p class="text-gray-500 text-center py-4">No documents found.</p>`;
    } else {
      let listHtml = '<ul class="divide-y divide-gray-200">';
      filteredDocs.slice(0, 20).forEach(doc => { // Limit to first 20 for performance
        listHtml += `
          <li data-doc-id="${doc.Doc_ID_Type}" class="doc-list-item px-3 py-2 hover:bg-blue-50 cursor-pointer">
            <div class="flex items-center">
              <i class="lucide lucide-file-text text-gray-400 mr-2"></i>
              <span>${doc.Document_Name} <span class="text-xs text-gray-500">(${doc.Doc_ID_Type})</span></span>
            </div>
          </li>
        `;
      });
      listHtml += '</ul>';
      documentListDocViewContainer.innerHTML = listHtml;
      
      // Add event listeners
      document.querySelectorAll('.doc-list-item').forEach(item => {
        item.addEventListener('click', () => {
          alert(`Document details for: ${item.dataset.docId}`);
          // Uncomment to use modal when fixed
          // currentSelectedDocId = item.dataset.docId;
          // displayDetailsInModal(currentSelectedDocId);
        });
      });
    }
    
    console.log("RENDERING LIST COMPLETE");
  } catch (error) {
    console.error("Error rendering document list:", error);
  }
};

// Override flowsList rendering
const originalRenderFlowsList = window.renderFlowsList;
window.renderFlowsList = function() {
  console.log("RENDERING FLOWS START");
  
  try {
    const flowIds = Object.keys(flowDefinitions);
    console.log("Flow IDs:", flowIds);
    
    if (flowIds.length === 0) {
      flowsListContainer.innerHTML = '<p class="text-gray-500">No flows available</p>';
      return;
    }
    
    let flowsHtml = '';
    flowIds.forEach(id => {
      const title = id.replace(/_/g, ' ').toUpperCase();
      flowsHtml += `
        <div class="flow-card" data-flow-id="${id}">
          <div class="flex items-center justify-between">
            <span class="font-medium">${title}</span>
            <i class="lucide lucide-chevron-right text-gray-400"></i>
          </div>
        </div>
      `;
    });
    
    flowsListContainer.innerHTML = flowsHtml;
    
    // Add event listeners
    flowsListContainer.querySelectorAll('.flow-card').forEach(card => {
      card.addEventListener('click', () => {
        const flowId = card.dataset.flowId;
        currentSelectedFlowId = flowId;
        alert(`Selected flow: ${flowId}`);
        // Uncomment when fixed
        // displayFlowGraph(flowId);
        // renderFlowsList();
      });
    });
    
    console.log("RENDERING FLOWS COMPLETE");
  } catch (error) {
    console.error("Error rendering flows list:", error);
  }
};

// Force load sequence after a delay
setTimeout(() => {
  console.log("FORCE LOADING SEQUENCE");
  
  if (currentVisibleView === 'documentViewWrapper') {
    renderDocumentViewTabs();
    renderDocumentList();
  } else if (currentVisibleView === 'flowsViewWrapper') {
    renderFlowsList();
  }
}, 3000);
// Initialize Mermaid
mermaid.initialize({ 
    startOnLoad: false, 
    theme: 'base', 
    securityLevel: 'loose', /* Allow clicks */ 
    themeVariables: {
        primaryColor: '#eff6ff', // blue-50
        primaryTextColor: '#1e3a8a', // blue-900
        primaryBorderColor: '#60a5fa', // blue-400
        lineColor: '#6b7280', // gray-500
        secondaryColor: '#f1f5f9', // slate-100
        tertiaryColor: '#e0f2fe' // sky-100
    }
});

// --- Global Variables ---
let documentsData = [];
let templateData = [];
const flowDefinitions = { // Keep example flows from v2
    "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 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');

const homeButton = document.getElementById('homeButton'); // Home Button
const breadcrumbNav = document.getElementById('breadcrumbNav'); // Breadcrumb container

// Modals
const showExampleFlowBtnHeader = document.getElementById('showExampleFlowBtn'); // Button in header
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 graphContentInModal = document.getElementById('graphContentInModal');
const mermaidGraphContainerInModal = document.getElementById('mermaidGraphInModal');
const closeDetailsModalBtn = document.getElementById('closeDetailsModalBtn');
const prevDocBtn = document.getElementById('prevDocBtn');
const nextDocBtn = document.getElementById('nextDocBtn');

// --- State Variables ---
let currentVisibleView = 'home'; // Tracks which main section is visible ('home', 'documentViewWrapper', 'flowsViewWrapper')
let currentDocViewTab = 'All'; // Track the active tab within the document view ('All', 'Discovery', ...)
let currentSelectedDocId = null;
let currentSelectedFlowId = null;
let currentDocListIndices = { prev: null, next: 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) || []; // Use word boundary \b
    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 to switch between major views (Home, Documents, Flows)
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');

    // 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'; // Set the tab for document view
            renderDocumentViewTabs(); // Render the tabs within this view
            renderDocumentList();     // Render the list based on the tab
        } else if (viewId === 'flowsViewWrapper') {
            renderFlowsList();
            // Optionally display a default flow or keep placeholder
            mermaidFlowGraphContainer.innerHTML = '';
            flowPlaceholder.style.display = 'block';
            currentSelectedFlowId = null;
        } else { // Home view
            currentDocViewTab = 'All'; // Reset doc view tab when going home
        }
    } else {
        console.error(`Target view section not found: ${viewId}. Defaulting to home.`);
        homeSection.classList.remove('hidden-container');
        currentVisibleView = 'home';
    }
    updateBreadcrumb(); // Update breadcrumb based on the current view
    clearSelection(); // Clear specific doc selection when switching main views
}

// Function to update breadcrumbs
function updateBreadcrumb() {
    breadcrumbNav.innerHTML = ''; // Clear existing
    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>`;
    }
}


// Function to render tabs ONLY within the Document View section
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']; // No 'Flows' here
    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; // Use currentDocViewTab state
        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; // Update the doc view tab state
            renderDocumentViewTabs(); // Re-render tabs for active style
            renderDocumentList();     // Re-render list for the new tab
            updateBreadcrumb();       // Update breadcrumb text
            clearSelection();         // Clear specific doc selection
        });
    });
}


// Function to render the document list based on the ACTIVE DOC VIEW TAB and search
function renderDocumentList() {
    // This function should only render if documentViewWrapper is the current view
    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(); // Use the correct search input
    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(); // Re-render list for selection highlight
        });
    });
}

// findNextPrevDocs uses the correct container based on current view
function findNextPrevDocs(currentId) {
     const listItems = documentListDocViewContainer.querySelectorAll('li[data-doc-id]'); // Always use DocView list
     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 displayDetailsInModal with tabs for different views
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="templates">Templates</div>
        </div>
     `;

     // Create content sections
     const infoHtml = `
        <div class="details-content active" id="tab-content-info">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <div class="mb-3">
                        <span class="text-sm font-medium text-gray-600">Phase:</span>
                        <span class="ml-2 text-sm px-2 py-1 bg-blue-100 text-blue-800 rounded-full">${doc.Phase || 'N/A'}</span>
                    </div>
                    <div class="mb-3">
                        <span class="text-sm font-medium text-gray-600">Discipline:</span>
                        <span class="ml-2">${doc.Sub_Phase_Discipline || 'N/A'}</span>
                    </div>
                    <div class="mb-3">
                        <span class="text-sm font-medium text-gray-600">Authoring Department(s):</span>
                        <span class="ml-2">${doc['Authoring_Department(s)'] || 'N/A'}</span>
                    </div>
                    <div class="mb-3">
                        <span class="text-sm font-medium text-gray-600">Review/Approval Dept(s):</span>
                        <span class="ml-2">${doc['Review_Approval_Dept(s)'] || 'N/A'}</span>
                    </div>
                    <div class="mb-3 flex items-center">
                        <span class="text-sm font-medium text-gray-600">Complexity:</span>
                        <span class="ml-2 flex items-center">${getComplexityIcon(doc.Complexity_Authoring)} ${doc.Complexity_Authoring || 'N/A'}</span>
                    </div>
                    <div class="mb-3 flex items-center">
                        <span class="text-sm font-medium text-gray-600">Regulatory Significance:</span>
                        <span class="ml-2 flex items-center">${getRegulatoryIcon(doc.Regulatory_Significance)} ${doc.Regulatory_Significance || 'N/A'}</span>
                    </div>
                </div>
                <div>
                    <div class="mb-3">
                        <div class="text-sm font-medium text-gray-600 mb-1">Purpose / Key Content:</div>
                        <div class="bg-gray-50 p-3 rounded text-sm max-h-28 overflow-y-auto custom-scroll">${doc.Purpose_Key_Content || 'N/A'}</div>
                    </div>
                    <div class="mb-3">
                        <div class="text-sm font-medium text-gray-600 mb-1">Key Metadata:</div>
                        <div class="bg-gray-50 p-3 rounded text-sm">${doc.Key_Metadata || 'N/A'}</div>
                    </div>
                </div>
            </div>
            <div class="mt-4">
                <div class="text-sm font-medium text-gray-600 mb-1">Input Docs/Data:</div>
                <div class="bg-gray-50 p-3 rounded text-sm">${linkDocumentIDsForDetails(doc.Input_Documents_Data_Sources) || 'N/A'}</div>
            </div>
            <div class="mt-4">
                <div class="text-sm font-medium text-gray-600 mb-1">Output/Informs Docs:</div>
                <div class="bg-gray-50 p-3 rounded text-sm">${linkDocumentIDsForDetails(doc.Output_Informs_Documents) || 'N/A'}</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>
     `;

     // Get templates related to this document type
     const relatedTemplates = templateData.filter(tpl => tpl.document_type === doc.Doc_ID_Type);
     let templatesHtml = `
        <div class="details-content" id="tab-content-templates">
     `;

     if (relatedTemplates.length > 0) {
         templatesHtml += `
            <div class="grid grid-cols-1 gap-4">
         `;
         
         relatedTemplates.forEach(tpl => {
             templatesHtml += `
                <div class="template-card">
                    <div class="template-header">
                        <h3>${tpl.name}</h3>
                        <span class="template-badge">${tpl.document_type}</span>
                    </div>
                    <p class="template-description">${tpl.description}</p>
                    <div class="template-sections">
                        <h4 class="text-sm font-medium mb-2">Sections:</h4>
                        ${tpl.sections.slice(0, 4).map(section => `
                            <div class="template-section">
                                <div class="template-section-title">${section.title}</div>
                                <div class="template-section-description">${section.description}</div>
                            </div>
                        `).join('')}
                        ${tpl.sections.length > 4 ? `<div class="text-xs text-center text-blue-500 mt-2">+ ${tpl.sections.length - 4} more sections</div>` : ''}
                    </div>
                    <div class="template-metadata">
                        ${tpl.metadata.phase ? `<div class="template-metadata-item"><i class="lucide lucide-layers"></i>${tpl.metadata.phase}</div>` : ''}
                        ${tpl.metadata.complexity ? `<div class="template-metadata-item"><i class="lucide lucide-bar-chart"></i>${tpl.metadata.complexity}</div>` : ''}
                        ${tpl.metadata.estimated_completion_time ? `<div class="template-metadata-item"><i class="lucide lucide-clock"></i>${tpl.metadata.estimated_completion_time}</div>` : ''}
                    </div>
                </div>
             `;
         });
         
         templatesHtml += `</div>`;
     } else {
         templatesHtml += `<p class="text-center text-gray-500 py-10">No templates available for this document type.</p>`;
     }
     
     templatesHtml += `</div>`;

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

     // 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();
     }
}

// New 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>
        `;
    }
}

// Callbacks from Mermaid graphs
window.displayDetailsAndGraphFromGraph = async (docId) => {
    console.log("Graph node clicked (main flow or example):", docId);
    await displayDetailsInModal(docId); // Always show in modal
    setTimeout(() => {
        // If the doc list view is active, scroll the item into view
        if (currentVisibleView === 'documentViewWrapper') {
            const listItem = document.querySelector(`#documentListDocView li[data-doc-id="${docId}"]`);
            listItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }, 100);
};

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

function clearSelection() {
    currentSelectedDocId = null;
     if (currentVisibleView === 'documentViewWrapper') {
         renderDocumentList(); // Update list highlight
     }
}

// Enhance flow list rendering with better UI
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
        });
    });
}

// Enhanced flow graph display
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";
     }
}

// --- Global Search Functionality ---

// Add 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 ---

// 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); });

// --- Initialization ---
document.addEventListener('DOMContentLoaded', async () => {
    console.log("DOM Loaded. Fetching data...");
    mainContentArea.innerHTML += '<div id="loadingSpinner" class="text-center p-10"><i class="lucide lucide-loader-2 animate-spin text-4xl text-blue-500"></i><p>Loading Data...</p></div>'; // Add loading spinner

    try {
        // Load document data
        const docsResponse = await fetch('documents.json');
        if (!docsResponse.ok) {
            throw new Error(`HTTP error! status: ${docsResponse.status}`);
        }
        documentsData = await docsResponse.json();
        console.log(`Successfully loaded ${documentsData.length} documents from documents.json`);
        
        // Load template data
        try {
            const templatesResponse = await fetch('document_templates.json');
            if (templatesResponse.ok) {
                templateData = await templatesResponse.json();
                console.log(`Successfully loaded ${templateData.length} templates from document_templates.json`);
            } else {
                console.warn("Templates file not found. Document templates will not be available.");
                templateData = [];
            }
        } catch (templateError) {
            console.warn("Error loading templates:", templateError);
            templateData = [];
        }

        // Remove spinner and initialize UI
        document.getElementById('loadingSpinner')?.remove();
        switchToView('home'); // Start on the 'Home' view

    } catch (error) {
        console.error("Failed to load documents.json:", error);
        document.getElementById('loadingSpinner')?.remove();
        // Display error message more prominently
        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 document database (documents.json). Please ensure the file exists in the same folder and is valid JSON.</span>
            <p class="text-xs mt-1">(${error.message})</p>
          </div>`;
    }
});