File size: 143,839 Bytes
8e313ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698508d
 
 
 
8e313ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>NGS Analysis Platform — Groq</title>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&family=Syne:wght@400;600;700;800&display=swap" rel="stylesheet"/>
<style>
:root{
  --bg:#04080a;--bg2:#080f12;--bg3:#0c161a;--bg4:#101d22;
  --border:#142028;--border2:#1c2f3a;
  --text:#c8e6f0;--text2:#5a9ab5;--text3:#244455;--text4:#162c38;
  --cyan:#00c8f0;--cdim:#0098bc;--cbg:#001a22;--cbright:#44e8ff;
  --red:#ff4e6a;--gold:#f0b429;--purple:#a78bfa;--green:#00d084;--teal:#2dd4bf;
  --font-mono:'JetBrains Mono',monospace;
  --font-sans:'Syne',sans-serif;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{min-height:100vh;background:var(--bg);color:var(--text);font-family:var(--font-mono)}
::-webkit-scrollbar{width:4px;height:4px}
::-webkit-scrollbar-track{background:var(--bg2)}
::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px}
#app{min-height:100vh;display:flex;flex-direction:column}

/* NAV */
.nav{background:rgba(4,8,10,.97);backdrop-filter:blur(14px);border-bottom:1px solid var(--border);padding:0 22px;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:200;height:56px}
.nav-logo{display:flex;align-items:center;gap:10px;cursor:pointer;text-decoration:none}
.logo-hex{width:36px;height:36px;background:linear-gradient(135deg,var(--cdim),var(--cyan));clip-path:polygon(50% 0%,100% 25%,100% 75%,50% 100%,0% 75%,0% 25%);display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:800;color:#000;font-family:var(--font-sans);box-shadow:0 0 24px rgba(0,200,240,.3)}
.nav-brand{font-family:var(--font-sans);font-size:15px;font-weight:700;letter-spacing:-.3px;color:var(--text)}
.nav-brand span{color:var(--cyan)}
.nav-steps{display:flex;align-items:center;gap:2px}
.nav-step{padding:5px 12px;font-size:9.5px;font-family:var(--font-mono);letter-spacing:.8px;border:1px solid transparent;border-radius:5px;cursor:pointer;transition:all .15s;color:var(--text3);text-transform:uppercase;background:none}
.nav-step.active{border-color:var(--cyan);color:var(--cyan);background:var(--cbg)}
.nav-step.done{color:var(--cdim)}
.nav-step:disabled{opacity:.2;cursor:default;pointer-events:none}
.nav-right{display:flex;align-items:center;gap:8px}

/* PAGE */
.page{max-width:1180px;margin:0 auto;padding:28px 20px 100px;width:100%}

/* HERO */
.hero{margin-bottom:32px}
.hero-title{font-family:var(--font-sans);font-size:32px;font-weight:800;letter-spacing:-1.5px;margin-bottom:10px;line-height:1.1;background:linear-gradient(135deg,var(--text),var(--cyan));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.hero-sub{font-size:12px;color:var(--text2);line-height:1.8;max-width:640px}

/* CARDS */
.card{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:20px 22px;margin-bottom:14px}
.card-title{font-size:9.5px;font-weight:700;color:var(--text2);margin-bottom:14px;letter-spacing:2px;text-transform:uppercase}

/* GRIDS */
.g2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.g3{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
.g4{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}

/* INPUTS */
.inp{width:100%;padding:9px 13px;border:1px solid var(--border);border-radius:8px;background:var(--bg3);color:var(--text);font-size:12px;font-family:var(--font-mono);outline:none;transition:border .15s}
.inp:focus{border-color:var(--cyan)}
.inp::placeholder{color:var(--text3)}
select.inp{cursor:pointer}

/* BUTTONS */
.btn{padding:9px 22px;background:var(--cyan);color:#000;border:none;border-radius:8px;cursor:pointer;font-size:12px;font-family:var(--font-mono);font-weight:700;transition:all .15s;letter-spacing:.3px;white-space:nowrap}
.btn:hover:not(:disabled){background:var(--cbright);box-shadow:0 0 20px rgba(0,200,240,.4)}
.btn:disabled{opacity:.35;cursor:not-allowed}
.btn-ghost{padding:7px 14px;background:transparent;color:var(--text2);border:1px solid var(--border);border-radius:8px;cursor:pointer;font-size:11px;font-family:var(--font-mono);transition:all .15s}
.btn-ghost:hover{border-color:var(--cyan);color:var(--cyan)}
.btn-dl{padding:6px 14px;background:var(--bg3);color:var(--cyan);border:1px solid var(--border2);border-radius:6px;cursor:pointer;font-size:10px;font-family:var(--font-mono);transition:all .15s;letter-spacing:.5px}
.btn-dl:hover{background:var(--cbg);border-color:var(--cyan)}
.btn-sm{padding:4px 10px;border:1px solid var(--border);border-radius:5px;background:transparent;color:var(--text2);font-size:9.5px;font-family:var(--font-mono);cursor:pointer;transition:all .12s}
.btn-sm:hover{border-color:var(--cyan);color:var(--cyan)}
.btn-sm.active{border-color:var(--cyan);color:var(--cyan);background:var(--cbg)}

/* TAGS */
.tag{display:inline-block;padding:2px 9px;border-radius:4px;font-size:9px;font-weight:700;letter-spacing:1px;text-transform:uppercase}

/* METRICS */
.met{background:var(--bg3);border-radius:10px;padding:13px 16px;border-left:3px solid}
.met-label{font-size:9px;color:var(--text2);margin-bottom:6px;letter-spacing:1.5px;text-transform:uppercase}
.met-val{font-size:24px;font-weight:700;font-family:var(--font-sans)}
.met-sub{font-size:9px;color:var(--text3);margin-top:4px}

/* STATUS DOTS */
.dot{width:7px;height:7px;border-radius:50%;flex-shrink:0}
.dot-cyan{background:var(--cyan);box-shadow:0 0 6px var(--cyan)}
.dot-red{background:var(--red)}
.dot-gold{background:var(--gold)}
.dot-dim{background:var(--border2)}

/* LOG */
.log-wrap{background:#020a0e;border-radius:12px;padding:16px 18px;border:1px solid #081820;height:100%}
.log-head{font-size:9px;color:#0a2a38;margin-bottom:10px;letter-spacing:2.5px;display:flex;align-items:center;gap:8px}
.log-body{max-height:320px;overflow-y:auto;font-size:11px;line-height:2}
.ls{color:#00c8f0}.li{color:#2a7a98}.ld{color:#142838}.lw{color:#f0b429}.le{color:#ff4e6a}.lp{color:#5ab8d0}.lt{color:#082030;margin-right:6px}

/* TABS */
.tab-row{display:flex;border-bottom:1px solid var(--border);margin-bottom:20px;gap:0;flex-wrap:wrap;overflow-x:auto}
.tab-btn{padding:9px 16px;font-size:9.5px;font-family:var(--font-mono);letter-spacing:.8px;border:none;border-bottom:2px solid transparent;background:transparent;color:var(--text3);cursor:pointer;margin-bottom:-1px;transition:all .15s;text-transform:uppercase;white-space:nowrap}
.tab-btn.active{border-bottom-color:var(--cyan);color:var(--cyan)}

/* CHAT */
.chat-u{background:var(--cbg);color:var(--cyan);border:1px solid #0a3040;border-radius:10px 10px 2px 10px;padding:9px 13px;font-size:11px;max-width:78%}
.chat-a{background:var(--bg3);color:var(--text);border:1px solid var(--border);border-radius:10px 10px 10px 2px;padding:9px 13px;font-size:11px;max-width:86%;line-height:1.85;white-space:pre-wrap}

/* ANIMATIONS */
@keyframes spin{to{transform:rotate(360deg)}}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}
@keyframes fadeUp{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
@keyframes scanDown{0%{top:0}100%{top:100%}}
@keyframes glow{0%,100%{box-shadow:0 0 6px var(--cyan)}50%{box-shadow:0 0 18px var(--cyan),0 0 36px rgba(0,200,240,.3)}}
.spin{display:inline-block;animation:spin 1s linear infinite}
.pulse{animation:pulse 1.4s ease infinite}
.fade-up{animation:fadeUp .35s ease forwards}

/* DROP ZONE */
.drop-zone{border:1.5px dashed var(--border2);border-radius:12px;padding:38px 22px;text-align:center;cursor:pointer;transition:all .2s;background:var(--bg3)}
.drop-zone:hover,.drop-zone.drag{border-color:var(--cyan);background:var(--cbg);box-shadow:0 0 24px rgba(0,200,240,.1)}

/* QC BADGES */
.fqc-badge{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:4px;font-size:9px;font-weight:700;letter-spacing:.5px}
.fqc-badge.pass{background:#001822;color:var(--cyan);border:1px solid #003040}
.fqc-badge.warn{background:#1a1000;color:var(--gold);border:1px solid #3a2800}
.fqc-badge.fail{background:#1a0008;color:var(--red);border:1px solid #3a001a}

/* MODE SELECTOR */
.mode-btn{flex:1;padding:15px 14px;border-radius:12px;cursor:pointer;font-family:var(--font-mono);text-align:left;border:1px solid var(--border);background:var(--bg2);transition:all .15s}
.mode-btn.active{border-color:var(--cyan);background:var(--cbg);box-shadow:0 0 18px rgba(0,200,240,.1)}

/* API BAR */
.api-bar{background:#020e14;border:1px solid #0a2030;border-radius:10px;padding:11px 16px;margin-bottom:18px;display:flex;align-items:center;gap:10px;flex-wrap:wrap}

/* STICKY CTA */
.sticky-cta{position:sticky;bottom:22px;display:flex;justify-content:flex-end;padding-top:10px}

/* TABLES */
.qtable{width:100%;border-collapse:collapse;font-size:11px}
.qtable th{font-size:9px;color:var(--text2);letter-spacing:1.5px;text-transform:uppercase;padding:7px 9px;border-bottom:1px solid var(--border);text-align:left;font-weight:600}
.qtable td{padding:7px 9px;border-bottom:1px solid #0a1820;color:var(--text)}
.qtable tr:last-child td{border-bottom:none}
.qtable tr:hover td{background:var(--bg3)}

/* PROG BAR */
.prog-bar{height:5px;background:var(--border);border-radius:3px;overflow:hidden;margin-top:8px}
.prog-fill{height:100%;border-radius:3px;transition:width .6s ease;background:linear-gradient(90deg,var(--cyan),var(--cbright))}

/* GENOME SELECTOR */
.genome-org-tabs{display:flex;gap:4px;flex-wrap:wrap;margin-bottom:12px}
.genome-org-tab{padding:4px 12px;border:1px solid var(--border);border-radius:20px;cursor:pointer;font-size:9.5px;font-family:var(--font-mono);background:var(--bg3);color:var(--text2);transition:all .15s;white-space:nowrap}
.genome-org-tab.active{border-color:var(--cyan);color:var(--cyan);background:var(--cbg)}
.genome-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:8px}
.genome-card{padding:10px 14px;border:1px solid var(--border);border-radius:8px;cursor:pointer;background:var(--bg3);transition:all .15s}
.genome-card.active{border-color:var(--cyan);background:var(--cbg);box-shadow:0 0 12px rgba(0,200,240,.1)}
.genome-card:hover:not(.active){border-color:var(--border2)}
.genome-card-id{font-size:11px;font-weight:700;color:var(--cyan);margin-bottom:3px}
.genome-card-desc{font-size:9.5px;color:var(--text3)}

/* PIPELINE VIZ */
.pipe-track{position:relative;padding-left:36px}
.pipe-track::before{content:'';position:absolute;left:11px;top:12px;bottom:12px;width:2px;background:var(--border);border-radius:1px}
.pipe-stage{position:relative;padding:10px 14px;margin-bottom:4px;border:1px solid var(--border);border-radius:8px;background:var(--bg2);transition:all .3s}
.pipe-stage.done-stage{border-color:#0a3040;background:var(--bg3)}
.pipe-stage.active-stage{border-color:var(--gold);background:#100d00;box-shadow:0 0 12px rgba(240,180,41,.15)}
.pipe-node{position:absolute;left:-27px;top:12px;width:22px;height:22px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:8.5px;font-weight:700;border:2px solid;transition:all .4s;background:var(--bg)}
.pipe-node.done{background:var(--cyan);border-color:var(--cyan);color:#000}
.pipe-node.active{border-color:var(--gold);color:var(--gold);animation:glow 1.5s ease infinite}
.pipe-node.pending{border-color:var(--border2);color:var(--text3)}
.pipe-stage-name{font-size:11px;font-weight:600;color:var(--text)}
.pipe-stage-name.active-name{color:var(--gold)}
.pipe-stage-name.done-name{color:var(--text2)}
.pipe-stage-detail{font-size:10px;color:var(--text3);margin-top:3px}
.pipe-stage-out{font-size:9.5px;color:var(--text4);margin-top:2px}
.pipe-stage-out.done-out{color:var(--cyan)}

/* NOTIF */
.notif{position:fixed;bottom:26px;right:26px;background:var(--bg3);border:1px solid var(--cyan);border-radius:12px;padding:12px 20px;font-size:12px;color:var(--cyan);z-index:9999;display:flex;align-items:center;gap:10px;box-shadow:0 4px 28px rgba(0,200,240,.2);transform:translateX(130%);transition:transform .3s ease}
.notif.show{transform:translateX(0)}

/* ERR */
.err-box{padding:10px 16px;background:#150508;border:1px solid #3a0010;border-radius:8px;font-size:11px;color:#ff6080;margin-top:12px}

/* OVERVIEW cards */
.ov-metric{background:var(--bg3);border:1px solid var(--border);border-radius:10px;padding:14px 16px;text-align:center}
.ov-metric-val{font-size:28px;font-weight:800;font-family:var(--font-sans);margin-bottom:4px}
.ov-metric-label{font-size:9px;color:var(--text2);letter-spacing:1.5px;text-transform:uppercase}

/* STEP EXPLAIN POPUP */
.step-explain{background:var(--bg4);border:1px solid var(--border2);border-radius:8px;padding:12px 14px;margin-top:8px;font-size:10.5px;color:var(--text2);line-height:1.75}

@media(max-width:768px){.g2,.g3,.g4{grid-template-columns:1fr}.nav-steps{display:none}}
</style>
</head>
<body>
<div id="app"></div>
<div id="notif" class="notif"><span class="dot dot-cyan"></span><span id="notif-msg"></span></div>

<script>
// ═══════════════════════════════════════
//  CONSTANTS
// ═══════════════════════════════════════
const SEQ_C={'RNA-seq':'#00c8f0','WGS/WGRS':'#00d084','ChIP-seq':'#a78bfa','Bisulfite-seq':'#f0b429'};
const SEQ_B={'RNA-seq':'#001a22','WGS/WGRS':'#001a0e','ChIP-seq':'#0e0a2a','Bisulfite-seq':'#1a1000'};

// Groq models — free tier
const GROQ_MODELS=[
  {id:'llama-3.3-70b-versatile',label:'Llama 3.3 70B Versatile',badge:'BEST QUALITY',desc:'Best for complex bio analysis'},
  {id:'llama-3.1-8b-instant',label:'Llama 3.1 8B Instant',badge:'FASTEST',desc:'Blazing speed, lighter tasks'},
  {id:'llama3-70b-8192',label:'Llama 3 70B (8K ctx)',badge:'STABLE',desc:'Proven stable model'},
  {id:'gemma2-9b-it',label:'Gemma 2 9B IT',badge:'GOOGLE',desc:'Google research model'},
];

const GROQ_API='https://api.groq.com/openai/v1/chat/completions';

const UPLOAD_CATEGORIES={
  'RNA-seq':{
    icon:'🧬',
    desc:'Transcriptome sequencing — differential gene expression analysis',
    required:['Raw FASTQ files (.fastq / .fastq.gz) — R1 and R2 for paired-end','One file pair per sample (e.g. sample1_R1.fastq.gz, sample1_R2.fastq.gz)','Minimum 2 samples per condition recommended','File naming: include condition/group in filename (e.g. tumor_rep1_R1.fastq.gz)'],
    optional:['Count matrix (.txt/.csv) if pre-quantified','GTF annotation file if using custom genome','Sample metadata sheet (CSV with sample IDs, condition, batch)'],
    notes:'Typical file size: 1–5 GB per sample. Paired-end 150 bp reads recommended for isoform analysis.',
    accept:'.fastq,.fq,.gz,.txt,.csv'
  },
  'WGS/WGRS':{
    icon:'🔬',
    desc:'Whole genome sequencing — SNV, InDel, and structural variant calling',
    required:['Raw FASTQ files (.fastq.gz) — R1 and R2 for paired-end','Minimum 30× coverage recommended (files typically 30–80 GB per sample)','BAM/SAM files accepted if pre-aligned (.bam + .bai index)'],
    optional:['VCF files (.vcf / .vcf.gz) if pre-called','BED file for targeted regions','Known sites VCF for BQSR (dbSNP, 1000G)'],
    notes:'WGS files are large (30–100 GB/sample). Ensure sufficient coverage depth. WES/panel sequencing also supported.',
    accept:'.fastq,.fq,.gz,.bam,.sam,.vcf,.bed'
  },
  'ChIP-seq':{
    icon:'🧲',
    desc:'Chromatin immunoprecipitation sequencing — peak calling and motif analysis',
    required:['IP FASTQ files (.fastq.gz) — immunoprecipitated samples','Input/control FASTQ files — matched genomic input controls (required for peak calling)','Label files clearly: e.g. H3K27ac_IP_rep1.fastq.gz, Input_rep1.fastq.gz'],
    optional:['Pre-aligned BAM files (.bam + .bai)','BED files of known peaks (.bed)','Blacklist regions BED for filtering'],
    notes:'Single-end reads common for ChIP-seq. Pair each IP sample with an input control. Histone ChIP typically needs 20–50M reads; TF ChIP 10–20M.',
    accept:'.fastq,.fq,.gz,.bam,.sam,.bed'
  },
  'Bisulfite-seq':{
    icon:'🔵',
    desc:'WGBS / RRBS — DNA methylation profiling at CpG resolution',
    required:['Bisulfite-converted FASTQ files (.fastq.gz) — R1 and R2 for paired-end','Label files with condition: e.g. tumor_WGBS_R1.fastq.gz','Minimum 10× CpG coverage recommended (WGBS files: 40–100 GB/sample; RRBS: 5–15 GB/sample)'],
    optional:['Pre-aligned BAM from Bismark (.bam)','CpG coverage/methylation call files (.cov, .bismark.gz)','RRBS-specific: MspI digestion site BED file'],
    notes:'Bisulfite conversion reduces sequence complexity — expect lower alignment rates (50–85%) vs standard NGS. Non-CpG methylation (CHG/CHH) also reported.',
    accept:'.fastq,.fq,.gz,.bam,.cov'
  },
  'ATAC-seq':{
    icon:'🌀',
    desc:'Chromatin accessibility profiling — open chromatin and TF footprinting',
    required:['Raw FASTQ files (.fastq.gz) — paired-end required','Nucleosome-free region expected: ~200 bp insert size','Label files: e.g. condition_ATAC_rep1_R1.fastq.gz'],
    optional:['Pre-aligned BAM (.bam + .bai)','Peak BED files (.bed / narrowPeak)','TSS annotation for enrichment scoring'],
    notes:'ATAC-seq libraries require paired-end sequencing. Mitochondrial contamination is common — expect 30–50% reads mapping to chrM.',
    accept:'.fastq,.fq,.gz,.bam,.sam,.bed'
  },
  'scRNA-seq':{
    icon:'🔮',
    desc:'Single-cell RNA sequencing — cell type deconvolution and trajectory analysis',
    required:['R1 FASTQ (cell barcodes + UMI) and R2 FASTQ (cDNA reads)','For 10x Genomics: standard R1/R2/I1 file structure','Barcode whitelist for your chemistry (10x v2/v3, etc.)'],
    optional:['Pre-processed count matrix (h5, h5ad, MEX format)','CellRanger output directory (barcodes.tsv, features.tsv, matrix.mtx)','Cell annotation CSV'],
    notes:'Specify 10x Genomics chemistry version. Typical yield: 5,000–10,000 cells per library. Multiple samples can be demultiplexed if hashtag antibodies used.',
    accept:'.fastq,.fq,.gz,.h5,.csv,.tsv,.mtx'
  },
};

const REFERENCE_GENOMES={
  'Human':[
    {id:'hg38',label:'GRCh38 / hg38',desc:'Current human reference (Dec 2013)'},
    {id:'hg19',label:'GRCh37 / hg19',desc:'Legacy human reference (Feb 2009)'},
    {id:'T2T-CHM13',label:'T2T-CHM13v2.0',desc:'Telomere-to-telomere (2022)'},
  ],
  'Mouse':[
    {id:'mm39',label:'GRCm39 / mm39',desc:'Current mouse reference (2020)'},
    {id:'mm10',label:'GRCm38 / mm10',desc:'Legacy mouse reference (2012)'},
  ],
  'Rat':[
    {id:'rn7',label:'mRatBN7.2 / rn7',desc:'Rattus norvegicus (2020)'},
    {id:'rn6',label:'Rnor_6.0 / rn6',desc:'Rat legacy assembly'},
  ],
  'Zebrafish':[
    {id:'danRer11',label:'GRCz11 / danRer11',desc:'Danio rerio (2017)'},
    {id:'danRer10',label:'GRCz10 / danRer10',desc:'Danio rerio legacy'},
  ],
  'Fruitfly':[
    {id:'dm6',label:'BDGP6.46 / dm6',desc:'D. melanogaster (2014)'},
    {id:'dm3',label:'BDGP5 / dm3',desc:'D. melanogaster legacy'},
  ],
  'C. elegans':[
    {id:'ce11',label:'WBcel235 / ce11',desc:'C. elegans (2013)'},
  ],
  'Yeast':[
    {id:'sacCer3',label:'SacCer3 (R64-1-1)',desc:'S. cerevisiae (2011)'},
    {id:'pombe_ASM',label:'ASM294v2 / S. pombe',desc:'S. pombe (2007)'},
  ],
  'Arabidopsis':[
    {id:'TAIR10',label:'TAIR10',desc:'A. thaliana (2010)'},
    {id:'TAIR9',label:'TAIR9',desc:'A. thaliana legacy'},
  ],
  'Chicken':[
    {id:'galGal6',label:'GRCg6a / galGal6',desc:'Gallus gallus (2018)'},
  ],
  'Pig':[
    {id:'susScr11',label:'Sscrofa11.1',desc:'Sus scrofa (2017)'},
  ],
  'Cow':[
    {id:'bosTau9',label:'ARS-UCD1.2 / bosTau9',desc:'Bos taurus (2018)'},
  ],
  'Macaque':[
    {id:'rheMac10',label:'Mmul_10 / rheMac10',desc:'Macaca mulatta (2019)'},
  ],
  'Rice':[
  {id:'IRGSP-1.0', label:'IRGSP-1.0', desc:'Oryza sativa japonica (2011)'},
  {id:'MSU7', label:'MSU Rice Genome Annotation Release 7', desc:'Oryza sativa (legacy)'},
],
};

// Pipeline steps with explanations
const PIPE_STEPS={
  'RNA-seq':[
    {name:'FastQC — raw read quality',tool:'FastQC v0.12',out:'Per-sample HTML/ZIP QC report',explain:'FastQC analyses raw FASTQ files and assesses per-base quality scores, GC content, adapter contamination, sequence duplication levels and overrepresented sequences. This step flags potential issues before proceeding.'},
    {name:'Trimmomatic — adapter & quality trimming',tool:'Trimmomatic v0.39',out:'Cleaned FASTQ files',explain:'Trimmomatic removes Illumina adapter sequences and low-quality bases from read ends. Uses sliding window approach: clips when 4-base window quality drops below Phred 20, and removes reads shorter than 36 bp.'},
    {name:'FastQC — post-trim quality check',tool:'FastQC v0.12',out:'Post-trim QC report',explain:'Re-runs FastQC on trimmed reads to verify adapter removal was successful and read quality has improved. Ensures the trimming parameters were appropriate before expensive alignment step.'},
    {name:'STAR — splice-aware genome alignment',tool:'STAR v2.7.10',out:'Aligned BAM files (sorted)',explain:'STAR (Spliced Transcripts Alignment to a Reference) performs ultra-fast splice-aware alignment. It uses a genome index built from the selected reference + GTF annotation. Outputs coordinate-sorted BAM files for each sample.'},
    {name:'Samtools — sort, index & flagstat',tool:'Samtools v1.18',out:'Indexed BAM + alignment stats',explain:'Samtools sorts and indexes the BAM file for fast random access. Flagstat reports total reads, mapped reads, properly paired reads, and singletons — a quick sanity check on alignment quality.'},
    {name:'featureCounts — read quantification',tool:'Subread/featureCounts v2.0',out:'Raw gene count matrix',explain:'featureCounts assigns aligned reads to genomic features (genes/exons) defined in the GTF annotation. Outputs a count matrix (genes × samples) used as input for differential expression analysis.'},
    {name:'DESeq2 — normalisation & DEG analysis',tool:'DESeq2 v1.42 (R/Bioconductor)',out:'DEG table + normalised counts',explain:'DESeq2 normalises counts using the median-of-ratios method to account for library size differences. It fits a negative binomial model per gene and performs Wald test for differential expression between conditions. Applies Benjamini-Hochberg correction (padj).'},
    {name:'GSEA — pathway enrichment analysis',tool:'fgsea v1.28 (R)',out:'Enriched pathway gene sets',explain:'Gene Set Enrichment Analysis (GSEA) tests whether predefined gene sets (KEGG, Reactome, GO) are enriched at the top or bottom of the ranked DEG list. Pre-ranked GSEA uses the signed log2FC × -log10(padj) score.'},
    {name:'PCA · Volcano · Heatmap generation',tool:'ggplot2 + pheatmap (R)',out:'Publication-quality plots',explain:'PCA reveals sample clustering and batch effects using top-variance genes. Volcano plot shows fold-change vs significance for all genes simultaneously. Heatmap with hierarchical clustering visualises the top DEGs with z-score normalisation.'},
    {name:'MultiQC — aggregated QC report',tool:'MultiQC v1.20',out:'multiqc_report.html',explain:'MultiQC scans all output directories and aggregates FastQC, STAR, featureCounts, and Trimmomatic logs into a single interactive HTML report. Essential for comparing QC across all samples at a glance.'},
  ],
  'WGS/WGRS':[
    {name:'FastQC — raw read quality',tool:'FastQC v0.12',out:'Per-sample QC report',explain:'Assesses raw FASTQ quality including per-base scores, GC content, and adapter contamination. Critical for WGS data to detect library prep issues early.'},
    {name:'Cutadapt — adapter trimming',tool:'Cutadapt v4.6',out:'Trimmed FASTQ files',explain:'Cutadapt removes adapter sequences and low-quality bases from WGS reads. Supports paired-end trimming and outputs trimming statistics for MultiQC integration.'},
    {name:'FastQC — post-trim quality',tool:'FastQC v0.12',out:'Post-trim QC report',explain:'Verifies adapter removal and quality improvement after Cutadapt trimming.'},
    {name:'BWA-MEM2 — genome alignment',tool:'BWA-MEM2 v2.2',out:'Aligned SAM → BAM',explain:'BWA-MEM2 aligns paired-end WGS reads to the reference genome. Uses a seed-and-extend approach optimised for reads >70 bp. Outputs SAM format which is piped to samtools for BAM conversion and sorting.'},
    {name:'Samtools — sort, index & stats',tool:'Samtools v1.18',out:'Sorted BAM + coverage stats',explain:'Converts SAM to BAM, sorts by coordinate, and creates index. Samtools stats and coverage commands provide depth-of-coverage metrics per chromosome, duplicate rates, and insert size distribution.'},
    {name:'GATK MarkDuplicates & BQSR',tool:'GATK v4.4',out:'Deduped, recalibrated BAM',explain:'MarkDuplicates flags PCR/optical duplicates introduced during library amplification. Base Quality Score Recalibration (BQSR) corrects systematic errors in base quality scores using known variant sites (dbSNP), improving variant calling accuracy.'},
    {name:'GATK HaplotypeCaller — variant calling',tool:'GATK v4.4 (gVCF mode)',out:'Raw VCF per sample',explain:'HaplotypeCaller performs local de novo assembly of haplotypes around active regions to detect SNVs and InDels. Runs in GVCF mode for joint genotyping, producing one gVCF per sample with all sites.'},
    {name:'GATK GenotypeGVCFs & VQSR',tool:'GATK v4.4',out:'Filtered & genotyped VCF',explain:'GenotypeGVCFs performs joint genotyping across all samples. VQSR (Variant Quality Score Recalibration) trains a Gaussian mixture model on known variant resources to assign calibrated quality scores, then applies tranches-based filtering.'},
    {name:'SnpEff — variant annotation',tool:'SnpEff v5.2',out:'Annotated VCF + HTML summary',explain:'SnpEff annotates each variant with predicted functional consequences (synonymous, missense, nonsense, splice site, etc.) based on the gene model. Also reports variant impact (HIGH/MODERATE/LOW) and affected genes/transcripts.'},
    {name:'MultiQC — aggregated QC report',tool:'MultiQC v1.20',out:'multiqc_report.html',explain:'Aggregates FastQC, BWA, GATK, and Samtools logs into a single interactive HTML QC report.'},
  ],
  'ChIP-seq':[
    {name:'FastQC — raw read quality',tool:'FastQC v0.12',out:'QC report per sample',explain:'Assesses ChIP-seq input and immunoprecipitated samples. ChIP-seq often shows GC bias and enrichment at certain k-mers; FastQC helps identify these.'},
    {name:'Trimmomatic — adapter trimming',tool:'Trimmomatic v0.39',out:'Trimmed FASTQ files',explain:'Removes Illumina adapters common in ChIP-seq libraries. Short fragments (transcription factor ChIP) may require aggressive trimming.'},
    {name:'FastQC — post-trim quality',tool:'FastQC v0.12',out:'Post-trim QC report',explain:'Confirms adapter removal and quality improvement.'},
    {name:'Bowtie2 — ultra-fast alignment',tool:'Bowtie2 v2.5',out:'Aligned SAM → sorted BAM',explain:'Bowtie2 aligns ChIP-seq reads to the reference genome. Uses short-read aligner optimised for single-end or paired-end ChIP reads. Outputs sorted BAM files.'},
    {name:'Samtools — deduplication & filtering',tool:'Samtools + Picard v3.1',out:'Filtered, indexed BAM',explain:'Removes PCR duplicates with Picard MarkDuplicates (essential in ChIP-seq). Samtools view filters for uniquely mapped reads (MAPQ≥20) and properly paired reads to reduce noise in peak calling.'},
    {name:'MACS2 — peak calling',tool:'MACS2 v2.2.9',out:'narrowPeak / broadPeak BED',explain:'MACS2 (Model-based Analysis of ChIP-seq) models the shift size of ChIP fragments and calls enriched regions (peaks) by comparing IP vs Input. Uses Poisson distribution to assess peak significance. Produces narrowPeak for TF ChIP, broadPeak for histone marks.'},
    {name:'DeepTools — BigWig signal tracks',tool:'deepTools v3.5',out:'Normalised BigWig files',explain:'deepTools bamCoverage generates normalised read coverage tracks (RPKM or CPM) in BigWig format for visualisation in IGV or UCSC Genome Browser. bamCompare creates log2 IP/Input ratio tracks.'},
    {name:'Homer — motif enrichment analysis',tool:'HOMER v4.11',out:'HTML motif report',explain:'HOMER findMotifsGenome identifies enriched DNA sequence motifs in peak summit regions (+/-100 bp). Reports known TF binding motifs from JASPAR/TRANSFAC database ranked by p-value.'},
    {name:'IDR — reproducibility analysis',tool:'IDR v2.0.4',out:'Reproducible peak set',explain:'IDR (Irreproducibility Discovery Rate) framework compares peak ranks between replicates and identifies a high-confidence reproducible peak set. Essential for ENCODE-compliant ChIP-seq analyses.'},
    {name:'MultiQC — aggregated QC report',tool:'MultiQC v1.20',out:'multiqc_report.html',explain:'Aggregates FastQC, Bowtie2, MACS2, and deepTools logs into a comprehensive QC report.'},
  ],
  'Bisulfite-seq':[
    {name:'FastQC — raw read quality',tool:'FastQC v0.12',out:'QC report per sample',explain:'Bisulfite-treated DNA has unusual GC content due to cytosine conversion. FastQC will show GC distribution deviating from normal — this is expected and not a QC failure.'},
    {name:'Trimmomatic — adapter trimming',tool:'Trimmomatic v0.39',out:'Trimmed FASTQ files',explain:'Removes sequencing adapters and low-quality bases. Bisulfite libraries benefit from removing the first few bases at 5\' end which often show M-bias (methylation bias).'},
    {name:'FastQC — post-trim quality',tool:'FastQC v0.12',out:'Post-trim QC report',explain:'Verifies trimming quality.'},
    {name:'Bismark — bisulfite alignment',tool:'Bismark v0.24 + Bowtie2',out:'Aligned BAM files',explain:'Bismark converts both genome strands (C→T) and reads (C→T), aligns simultaneously, and outputs a BAM file with methylation calls. Handles both directional and non-directional libraries. Reports bisulfite conversion rate.'},
    {name:'Bismark deduplication',tool:'bismark_dedup',out:'Deduplicated BAM',explain:'Removes PCR duplicates from bisulfite-converted libraries. Different from standard deduplication — uses unique alignment positions rather than read sequences since all C→T conversions look similar.'},
    {name:'Bismark methylation extractor',tool:'bismark_methylation_extractor',out:'CpG/CHG/CHH context files',explain:'Extracts per-CpG methylation calls from the BAM file. Outputs CpG, CHG, and CHH methylation in separate files. Also generates M-bias plots to assess position-specific methylation biases along reads.'},
    {name:'DSS — differential methylation (DMR)',tool:'DSS v2.50 (R/Bioconductor)',out:'DMR BED + statistics table',explain:'DSS uses a Bayesian hierarchical model to test for differential methylation at CpG sites between conditions. Smoothing is applied to borrow information from neighbouring CpGs. DMR calling groups significant DMS into regions.'},
    {name:'CpG island & context annotation',tool:'annotatr v1.28 (R)',out:'Annotated DMR BED file',explain:'annotatr overlaps DMRs with CpG island annotations (islands, shores, shelves, open sea) and genic contexts (promoter, exon, intron, intergenic) to understand the regulatory significance of differential methylation.'},
    {name:'Visualisation & DMR report',tool:'ggplot2 + methylKit (R)',out:'DMR plots + HTML report',explain:'Generates coverage plots, methylation violin plots, PCA of samples by methylation profiles, and lollipop plots of top DMRs. All visualisations are compiled into a final HTML report.'},
    {name:'MultiQC — aggregated QC report',tool:'MultiQC v1.20',out:'multiqc_report.html',explain:'Aggregates FastQC, Bismark, and DSS statistics into one QC report.'},
  ],
};

const EXAMPLES=['cystic fibrosis','Alzheimer\'s disease','breast cancer WGBS','COPD transcriptome','colorectal cancer','leukemia ChIP-seq','Parkinson\'s methylation','type 2 diabetes WGS','lung adenocarcinoma','glioblastoma epigenomics','hepatocellular carcinoma','rheumatoid arthritis'];

// ═══════════════════════════════════════
//  STATE
// ═══════════════════════════════════════
let S={
  screen:'home',
  groqKey:'',selectedModel:'llama-3.3-70b-versatile',
  inputMode:'query',queryInput:'',dirInput:'',uploadedFiles:[],uploadCategory:'',
  searching:false,searchResults:[],searchErr:'',selectedDs:null,
  selectedGenomeOrg:'Human',selectedGenomeId:'hg38',
  cfg:{email:'',notifyEmail:'',outDir:''},
  pipeLog:[],pipeStep:-1,pipeStepTotal:0,pipeDone:false,pipeProgress:0,activeStepExplain:'',
  stats:null,bio:null,fastqc:null,multiqc:null,interpretation:'',
  chatHistory:[],chatInput:'',chatLoading:false,
  resTab:'overview',expandedStep:-1,searchPage:0,
  emailSent:false,mailtoLink:'',
};
let logBuf=[];
function set(p){Object.assign(S,typeof p==='function'?p(S):p);render();}

// ═══════════════════════════════════════
//  GROQ API CALL (with robust JSON handling)
// ═══════════════════════════════════════
async function callGroq(systemPrompt,userPrompt,maxTokens=1400,expectJson=false){
  if(!S.groqKey) throw new Error('Groq API key not set. Paste your key above.');
  const resp=await fetch(GROQ_API,{
    method:'POST',
    headers:{'Content-Type':'application/json','Authorization':'Bearer '+S.groqKey},
    body:JSON.stringify({
      model:S.selectedModel,
      max_tokens:maxTokens,
      temperature:expectJson?0.3:0.7,
      messages:[
        {role:'system',content:systemPrompt},
        {role:'user',content:userPrompt}
      ]
    })
  });
  const data=await resp.json();
  if(data.error) throw new Error(data.error.message||JSON.stringify(data.error));
  const text=data.choices?.[0]?.message?.content||'';
  if(expectJson){
    try {
      // Try to extract JSON
      const clean=text.replace(/^```(?:json)?\s*/,'').replace(/\s*```$/,'').trim();
      return JSON.parse(clean);
    } catch(e) {
      // If JSON parsing fails, create a fallback object with a warning
      console.warn('Failed to parse JSON from Groq response:', text);
      return { _error: 'JSON parse failed', _raw: text, _message: 'Model did not return valid JSON. Using fallback data.' };
    }
  }
  return text;
}

// ═══════════════════════════════════════
//  AI CALLS (with fallbacks)
// ═══════════════════════════════════════
async function searchDatasets(query){
  const data=await callGroq(
    'You are a bioinformatics database expert. Return ONLY a valid JSON object with key "datasets" containing exactly 6 realistic public NGS datasets for the given disease/condition. Each dataset MUST have all these fields: id (string "ds_1" to "ds_6"), title (string), source (one of: "GEO", "NCBI SRA", "ENA", "ArrayExpress"), seqType (one of: "RNA-seq", "WGS/WGRS", "ChIP-seq", "Bisulfite-seq"), organism (string), samples (integer), year (integer 2018-2024), condition (string), accession (realistic accession ID), description (2 sentences), sizeGB (string like "12.4"), pmid (integer or null). Mix seqTypes and sources. Return ONLY JSON, no explanation.',
    'Disease/query: "'+query+'"',1600,true
  );
  if(data._error) {
    // Return a fallback dataset array
    return [
      {id:'ds_f1', title:`${query} RNA-seq study`, source:'GEO', seqType:'RNA-seq', organism:'Homo sapiens', samples:12, year:2023, condition:query, accession:'GSE99999', description:'Fallback dataset due to API response error.', sizeGB:'5.2', pmid:null},
      {id:'ds_f2', title:`${query} WGS study`, source:'NCBI SRA', seqType:'WGS/WGRS', organism:'Homo sapiens', samples:8, year:2024, condition:query, accession:'SRP999999', description:'Fallback dataset due to API response error.', sizeGB:'78.3', pmid:null},
    ];
  }
  return Array.isArray(data)?data:(data.datasets||Object.values(data)[0]||[]);
}

async function fetchBioResults(ds){
  const ctx='Dataset: '+ds.title+'\nSeqType: '+ds.seqType+'\nCondition: '+ds.condition+'\nOrganism: '+ds.organism;
  try {
    if(ds.seqType==='RNA-seq'){
      return await callGroq(
        'You are a bioinformatics expert. Return ONLY valid JSON (no markdown, no explanation) with exactly these keys: topGenes (array of 10 real HGNC gene symbols relevant to the condition), directions (array of 10 strings each "UP" or "DOWN"), lfc (array of 10 numbers: UP genes 1.2 to 4.5, DOWN genes -1.2 to -4.0), padj (array of 10 strings like "2.1e-06"), baseMean (array of 10 integers 50-5000), pathways (array of 6 KEGG pathway names specific to this condition), geneDesc (array of 10 one-sentence gene descriptions).',
        ctx,1200,true
      );
    }
    if(ds.seqType==='WGS/WGRS'){
      return await callGroq(
        'You are a bioinformatics expert. Return ONLY valid JSON with: topGenes (array of 8 gene symbols with variants in this condition), variantType (array of 8 strings like "Missense p.Arg248Trp"), significance (array of 8 each one of: "Pathogenic","Likely pathogenic","VUS","Likely benign"), af (array of 8 allele frequency strings like "0.0012"), chr (array of 8 chromosome strings like "chr17"), pos (array of 8 integers), geneRole (array of 8 one-sentence roles), zygosity (array of 8 each "Heterozygous" or "Homozygous").',
        ctx,1100,true
      );
    }
    if(ds.seqType==='ChIP-seq'){
      return await callGroq(
        'You are a bioinformatics expert. Return ONLY valid JSON with: topMotifs (array of 8 TF motif names for this condition), motifPval (array of 8 p-value strings like "3.4e-38"), motifPct (array of 8 percentage strings like "41.2%"), targetGenes (array of 8 target genes near peaks), peakAnnotation (object with keys: promoter, intron, intergenic, exon, UTR each a percentage string), enrichScore (array of 8 numbers 2.5-18.5).',
        ctx,1000,true
      );
    }
    return await callGroq(
      'You are a bioinformatics expert. Return ONLY valid JSON with: topGenes (array of 9 gene symbols with differential methylation in this condition), directions (array of 9 each "Hyper" or "Hypo"), deltaBeta (array of 9 numbers: Hyper +0.15 to +0.55, Hypo -0.15 to -0.50), context (array of 9 CpG context strings like "CpG island promoter"), geneRole (array of 9 one-sentence roles), island (array of 9 each one of: "CpG island","Shore","Shelf","Open sea").',
      ctx,1000,true
    );
  } catch(e) {
    addLog('⚠️ Bio results fetch error: '+e.message,'w');
    return { _error: true, _message: e.message };
  }
}

async function fetchFastQC(ds,qc){
  try {
    const res = await callGroq(
      'You are a bioinformatics QC expert. Return ONLY valid JSON with FastQC results. Keys: perBaseQuality (array of 35 objects {pos:string, median:number 28-40, q25:number, q75:number, whisker_lo:number, whisker_hi:number}), perSeqQuality (array of 15 objects {score:number 15-40, count:number}), perBaseN (array of 35 objects {pos:string, n:number 0-5}), seqLengthDist (array of 5 objects {length:string, count:number}), duplicationLevels (array of 9 objects {level:string, pct:number}), overrepresentedSeqs (array of 3 objects {seq:string, count:number, pct:number, source:string}), adapterContent (array of 6 objects {pos:number, illumina:number, nextera:number, small_rna:number}), kmerContent (array of 5 objects {kmer:string, pct:number, ratio:number}), gcContent (array of 20 objects {gc:number, actual:number, theoretical:number}), modules (object with exactly 11 module names as keys each "pass","warn", or "fail"), summary (object: totalReads:string, poorQualReads:string, flaggedPct:string, totalBases:string).',
      'Dataset: '+ds.title+'\nSeqType: '+ds.seqType+'\nQC: '+JSON.stringify(qc),
      1800,true
    );
    if(res._error) {
      addLog('⚠️ FastQC JSON parse failed, using fallback QC data.','w');
      return createFallbackFastQC(qc);
    }
    return res;
  } catch(e) {
    addLog('⚠️ FastQC API error: '+e.message,'w');
    return createFallbackFastQC(qc);
  }
}

function createFallbackFastQC(qc) {
  // Generate a plausible fallback FastQC object from the QC stats
  return {
    modules: {
      'Per base sequence quality': 'pass',
      'Per sequence quality scores': 'pass',
      'Per base sequence content': 'warn',
      'Per sequence GC content': 'warn',
      'Per base N content': 'pass',
      'Sequence Length Distribution': 'pass',
      'Sequence Duplication Levels': 'warn',
      'Overrepresented sequences': 'pass',
      'Adapter Content': 'pass',
      'Kmer Content': 'warn',
      'Basic Statistics': 'pass'
    },
    summary: {
      totalReads: qc.totalReads || 'N/A',
      poorQualReads: '0.0%',
      flaggedPct: '0.0%',
      totalBases: 'N/A'
    },
    perBaseQuality: Array.from({length:35}, (_,i) => ({
      pos: (i+1).toString(),
      median: 32 + Math.sin(i/5)*2,
      q25: 28 + Math.sin(i/5)*1.5,
      q75: 36 + Math.sin(i/5)*1.8,
      whisker_lo: 20 + Math.sin(i/5)*2,
      whisker_hi: 40 + Math.sin(i/5)*1.5
    })),
    perSeqQuality: [20,25,28,30,32,34,35,36,37,38,39,40].map(score => ({ score, count: Math.floor(Math.random()*5000+1000) })),
    gcContent: Array.from({length:20}, (_,i) => ({ gc: i*5, actual: Math.random()*0.8+0.2, theoretical: 0.5 })),
    duplicationLevels: [
      {level:'Unique', pct: 55},
      {level:'2-5', pct: 18},
      {level:'5-10', pct: 10},
      {level:'10-50', pct: 9},
      {level:'>50', pct: 8}
    ],
    adapterContent: [
      {pos:1, illumina:0.1, nextera:0.05, small_rna:0.02},
      {pos:10, illumina:0.2, nextera:0.1, small_rna:0.05},
      {pos:20, illumina:0.3, nextera:0.2, small_rna:0.1},
      {pos:30, illumina:0.5, nextera:0.3, small_rna:0.2},
      {pos:40, illumina:0.8, nextera:0.5, small_rna:0.3},
      {pos:50, illumina:1.2, nextera:0.8, small_rna:0.5}
    ],
    overrepresentedSeqs: [],
    kmerContent: [
      {kmer:'AAAAAA', pct:2.1, ratio:1.1},
      {kmer:'CCCCCC', pct:1.8, ratio:0.9},
      {kmer:'GGGGGG', pct:1.9, ratio:1.0},
      {kmer:'TTTTTT', pct:2.0, ratio:1.1},
      {kmer:'GCGCGC', pct:3.2, ratio:1.4}
    ],
    seqLengthDist: [{length:'150', count:10000},{length:'151', count:12000},{length:'152', count:8000}],
    perBaseN: Array.from({length:35}, (_,i) => ({
      pos: (i+1).toString(),
      n: i < 3 ? Math.random()*0.5 : Math.random()*0.05
    }))
  };
}

async function fetchMultiQC(ds,qc){
  try {
    const res = await callGroq(
      'You are a bioinformatics QC expert. Return ONLY valid JSON for MultiQC: sampleStats (array of '+Math.min(ds.samples,8)+' objects {name:string, totalReads:string, mapped:string, mappingRate:string, duplicates:string, q30:string, gcContent:string, meanLen:string, status:"pass" or "warn" or "fail"}), alignmentStats (object {uniquelyMapped:string, multiMapped:string, unmapped:string, chimeric:string}), trimStats (object {readsPassFilter:string, readsWithAdapters:string, readsShortFiltered:string, basesQualityTrimmed:string}), insertSize (array of 12 objects {size:number, count:number}), coverage (array of 8 objects {chr:string, mean:number, median:number, pct20x:string}).',
      'Dataset: '+ds.title+'\nSeqType: '+ds.seqType+'\nSamples: '+ds.samples+'\nQC: '+JSON.stringify(qc),
      1400,true
    );
    if(res._error) {
      addLog('⚠️ MultiQC JSON parse failed, using fallback data.','w');
      return createFallbackMultiQC(ds,qc);
    }
    return res;
  } catch(e) {
    addLog('⚠️ MultiQC API error: '+e.message,'w');
    return createFallbackMultiQC(ds,qc);
  }
}

function createFallbackMultiQC(ds,qc) {
  const samples = Math.min(ds.samples,8);
  const sampleStats = Array.from({length:samples}, (_,i) => ({
    name: `Sample_${i+1}`,
    totalReads: qc.totalReads || '25M',
    mapped: (Math.random()*0.95+0.04).toFixed(2)+'M',
    mappingRate: (Math.random()*20+80).toFixed(1)+'%',
    duplicates: (Math.random()*30+5).toFixed(1)+'%',
    q30: (Math.random()*15+80).toFixed(1)+'%',
    gcContent: (Math.random()*20+40).toFixed(1)+'%',
    meanLen: '150',
    status: Math.random()>0.2?'pass':'warn'
  }));
  return {
    sampleStats,
    alignmentStats: {
      uniquelyMapped: '89.2%',
      multiMapped: '4.1%',
      unmapped: '6.7%',
      chimeric: '0.3%'
    },
    trimStats: {
      readsPassFilter: '92%',
      readsWithAdapters: '1.2%',
      readsShortFiltered: '0.8%',
      basesQualityTrimmed: '3.4%'
    },
    insertSize: Array.from({length:12}, (_,i) => ({ size: 150 + i*10, count: Math.floor(Math.random()*5000+500) })),
    coverage: ['chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8'].map(chr => ({ chr, mean: Math.random()*30+10, median: Math.random()*28+8, pct20x: (Math.random()*70+20).toFixed(0)+'%' }))
  };
}

async function fetchInterpretation(ds,stats,bio,fastqc){
  try {
    return await callGroq(
      'You are a senior computational biologist. Write a rigorous 4-paragraph biological interpretation with NO bullet points: (1) Data quality assessment from FastQC/QC metrics, (2) Key biological findings with specific gene/pathway names from the results, (3) Clinical and translational implications for '+ds.condition+', (4) Recommended follow-up experiments. Be specific. ~280 words total.',
      'Dataset: '+ds.title+' | Type: '+ds.seqType+' | Condition: '+ds.condition+' | Organism: '+ds.organism+'\nQC stats: '+JSON.stringify(stats)+'\nBio results: '+JSON.stringify(bio)+'\nFastQC modules: '+JSON.stringify(fastqc?.modules||{}),
      1000
    );
  } catch(e) {
    addLog('⚠️ Interpretation generation failed: '+e.message,'w');
    return 'Interpretation could not be generated due to an API error. Please check your Groq key and try again.';
  }
}

async function chatWithAI(history,message,ds,bio){
  const msgs=[];
  for(const h of history.slice(-8)){msgs.push({role:'user',content:h.user});msgs.push({role:'assistant',content:h.ai});}
  msgs.push({role:'user',content:message});
  const resp=await fetch(GROQ_API,{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+S.groqKey},body:JSON.stringify({
    model:S.selectedModel,max_tokens:700,temperature:0.7,
    messages:[{role:'system',content:'You are an expert NGS bioinformatics assistant. The user ran '+ds.seqType+' analysis on "'+ds.title+'" (condition: '+ds.condition+'). Results summary: '+JSON.stringify(bio||{})+'.'}, ...msgs]
  })});
  const data=await resp.json();
  if(data.error) throw new Error(data.error.message);
  return data.choices?.[0]?.message?.content||'';
}

// ═══════════════════════════════════════
//  UTILITIES
// ═══════════════════════════════════════
function rnd(lo,hi,d=1){return +(Math.random()*(hi-lo)+lo).toFixed(d);}
function sleep(ms){return new Promise(r=>setTimeout(r,ms));}
function h(s){if(s==null)return'';return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
function statusBadge(st){const cls={pass:'pass',warn:'warn',fail:'fail'}[st]||'warn';return '<span class="fqc-badge '+cls+'">'+{pass:'✓ PASS',warn:'⚠ WARN',fail:'✗ FAIL'}[st]+'</span>';}

function makeQC(seqType){
  if(seqType==='RNA-seq') return{totalReads:rnd(22,58,0)+'M',mappingRate:rnd(92,99.2)+'%',q30:rnd(84,97)+'%',genesDetected:Math.floor(Math.random()*4500+14000),degUp:Math.floor(Math.random()*380+80),degDown:Math.floor(Math.random()*280+60),medianInsert:Math.floor(rnd(180,280,0))+' bp',pctDup:rnd(8,32)+'%',gcContent:rnd(44,56)+'%'};
  if(seqType==='WGS/WGRS') return{coverage:rnd(30,55)+'x',mappingRate:rnd(97,99.5)+'%',q30:rnd(86,97)+'%',snvCount:Math.floor(Math.random()*1500+3500),indelCount:Math.floor(Math.random()*300+180),pathogenic:Math.floor(Math.random()*12+3),pctDup:rnd(5,22)+'%',gcContent:rnd(40,50)+'%'};
  if(seqType==='ChIP-seq') return{totalReads:rnd(32,85,0)+'M',mappingRate:rnd(88,97)+'%',frip:rnd(8,24)+'%',peaksFound:Math.floor(Math.random()*16000+7000),enrichmentScore:rnd(5,22),pctDup:rnd(12,40)+'%',q30:rnd(82,95)+'%'};
  return{totalReads:rnd(20,44,0)+'M',bisulfiteConv:rnd(97.5,99.8)+'%',mappingRate:rnd(72,87)+'%',cpgCoverage:rnd(10,28)+'x',dmrCount:Math.floor(Math.random()*750+350),hyperMeth:Math.floor(Math.random()*380+120),hypoMeth:Math.floor(Math.random()*320+90),q30:rnd(80,93)+'%'};
}

function addLog(msg,type='i'){
  logBuf.push({msg,type,t:new Date().toLocaleTimeString()});
  S.pipeLog=[...logBuf];render();
  const el=document.getElementById('pipelog');if(el)el.scrollTop=el.scrollHeight;
}

function showNotif(msg){
  const n=document.getElementById('notif'),m=document.getElementById('notif-msg');
  if(n&&m){m.textContent=msg;n.classList.add('show');setTimeout(()=>n.classList.remove('show'),3500);}
}

// ═══════════════════════════════════════
//  SEARCH / PIPELINE (unchanged but uses updated fetch functions)
// ═══════════════════════════════════════
async function doSearch(){
  const q=S.inputMode==='query'?S.queryInput.trim():S.inputMode==='path'?S.dirInput.trim():'files';
  if(!q&&!S.uploadedFiles.length)return;
  if(!S.groqKey){set({searchErr:'Please enter your Groq API key first.'});return;}
  set({searching:true,searchErr:'',searchResults:[],screen:'searching'});
  try{
    if(S.inputMode==='upload'){
      const names=S.uploadedFiles.map(f=>f.name?.toLowerCase()||'').join(' ');
      // Use explicitly selected category, fall back to auto-detection
      const st=S.uploadCategory||( names.includes('chip')?'ChIP-seq':names.includes('bisulf')||names.includes('wgbs')?'Bisulfite-seq':names.includes('wgs')?'WGS/WGRS':names.includes('atac')?'ATAC-seq':names.includes('scrna')||names.includes('sc_rna')?'scRNA-seq':'RNA-seq');
      set({searchResults:[{id:'up_1',title:'Uploaded: '+S.uploadedFiles.map(f=>f.name).join(', ').slice(0,60),source:'Local Upload',seqType:st,organism:'Homo sapiens',samples:S.uploadedFiles.length,year:2024,condition:'User-provided',accession:'LOCAL_UPLOAD',description:S.uploadedFiles.length+' file(s) uploaded. Category: '+st+'.',sizeGB:(S.uploadedFiles.reduce((a,f)=>a+f.size,0)/1e9).toFixed(2)||'?',pmid:null}],screen:'select',searching:false});
      return;
    }
    if(S.inputMode==='path'){
      const fname=S.dirInput.split('/').pop()||'data';
      const st=fname.includes('chip')?'ChIP-seq':fname.includes('bisulf')||fname.includes('wgbs')?'Bisulfite-seq':fname.includes('wgs')?'WGS/WGRS':'RNA-seq';
      set({searchResults:[
        {id:'lf_1',title:'Local: '+fname,source:'Local Filesystem',seqType:st,organism:'Homo sapiens',samples:4,year:2024,condition:'User-provided',accession:S.dirInput,description:'Files found at '+S.dirInput,sizeGB:'~2.4',pmid:null},
        {id:'lf_2',title:'Local control: '+fname+'_ctrl',source:'Local Filesystem',seqType:st,organism:'Homo sapiens',samples:4,year:2024,condition:'Control',accession:S.dirInput+'_ctrl',description:'Control group files',sizeGB:'~2.1',pmid:null}
      ],screen:'select',searching:false});
      return;
    }
    const results=await searchDatasets(q);
    set({searchResults:results,screen:'select',searching:false,searchPage:0});
  }catch(e){set({searchErr:'Error: '+e.message,screen:'home',searching:false});}
}

async function runPipeline(){
  if(!S.selectedDs||!S.groqKey)return;
  const ds=S.selectedDs;
  const qc=makeQC(ds.seqType);
  logBuf=[];
  const steps=PIPE_STEPS[ds.seqType];
  const genome=(REFERENCE_GENOMES[S.selectedGenomeOrg]||[]).find(g=>g.id===S.selectedGenomeId)||{label:S.selectedGenomeId};
  set({stats:qc,bio:null,fastqc:null,multiqc:null,pipeLog:[],pipeStep:-1,pipeStepTotal:steps.length,pipeProgress:0,pipeDone:false,interpretation:'',chatHistory:[],screen:'pipeline',emailSent:false});

  addLog('🔬 '+ds.seqType+' pipeline initialised','i');
  addLog('📦 '+ds.source+' | '+ds.accession+' | '+ds.samples+' samples','d');
  addLog('🧬 Reference: '+genome.label+' | Organism: '+ds.organism,'d');
  await sleep(300);

  if(!['Local Upload','Local Filesystem'].includes(ds.source)){
    addLog('📥 Fetching '+ds.samples+' samples from '+ds.source+'...','i');
    await sleep(700);
    addLog('   ✅ '+ds.sizeGB+' GB staged','s');
  }

  for(let i=0;i<steps.length;i++){
    S.pipeStep=i;
    S.pipeProgress=Math.round((i/steps.length)*100);
    S.activeStepExplain=steps[i].explain;
    render();
    addLog('⚙️  ['+( i+1)+'/'+steps.length+'] '+steps[i].name,'p');
    await sleep(450+Math.random()*400);

    // Step-specific logic
    if(i===0){
      addLog('   → Reads: '+(qc.totalReads||'?')+' | Q30: '+(qc.q30||'?')+' | GC: '+(qc.gcContent||'?'),'d');
      addLog('   → Fetching FastQC data via '+S.selectedModel+'...','i');
      try{
        const fqc=await fetchFastQC(ds,qc);S.fastqc=fqc;
        const mods=fqc.modules||{};
        const pass=Object.values(mods).filter(v=>v==='pass').length;
        const warn=Object.values(mods).filter(v=>v==='warn').length;
        const fail=Object.values(mods).filter(v=>v==='fail').length;
        addLog('   ✅ FastQC: '+pass+' PASS · '+warn+' WARN · '+fail+' FAIL','s');
      }catch(e){addLog('⚠️  FastQC: '+e.message,'w');}
    }
    if(i===1) addLog('   → Adapter trimming complete | Low-quality bases removed | Min length: 36bp','d');
    if(i===2) addLog('   → Post-trim Q30 improved | Adapter contamination: <0.1%','d');
    if(i===3){
      const aligner=ds.seqType==='WGS/WGRS'?'BWA-MEM2':ds.seqType==='ChIP-seq'?'Bowtie2':ds.seqType==='Bisulfite-seq'?'Bismark':'STAR';
      addLog('   → '+aligner+' aligned to '+genome.label,' | Rate: '+(qc.mappingRate||'?'),'d');
    }
    if(i===4) addLog('   → BAM sorted + indexed | Duplicates: '+(qc.pctDup||'?'),'d');
    if(i===5){
      addLog('   → Fetching biological results via '+S.selectedModel+'...','i');
      try{
        const bio=await fetchBioResults(ds);S.bio=bio;
        if(bio._error) {
          addLog('   ⚠️ Bio results: fallback used due to API error.','w');
        } else {
          const top=bio.topGenes||bio.topMotifs||[];
          addLog('   ✅ '+top.length+' key features identified: '+top.slice(0,4).join(', ')+'...','s');
          if(ds.seqType==='RNA-seq') addLog('   → DEGs: '+(qc.degUp||'?')+' UP / '+(qc.degDown||'?')+' DOWN (padj<0.05)','d');
          if(ds.seqType==='WGS/WGRS') addLog('   → SNVs: '+(qc.snvCount||'?')+' | InDels: '+(qc.indelCount||'?')+' | Pathogenic: '+(qc.pathogenic||'?'),'d');
          if(ds.seqType==='Bisulfite-seq') addLog('   → DMRs: '+(qc.dmrCount||'?')+' | Hyper: '+(qc.hyperMeth||'?')+' | Hypo: '+(qc.hypoMeth||'?'),'d');
          if(ds.seqType==='ChIP-seq') addLog('   → Peaks: '+(qc.peaksFound||'?')+' | FRiP: '+(qc.frip||'?'),'d');
        }
      }catch(e){addLog('⚠️  Bio results: '+e.message,'w');}
    }
    if(i===8){
      addLog('   → Generating MultiQC report via '+S.selectedModel+'...','i');
      try{
        const mqc=await fetchMultiQC(ds,qc);S.multiqc=mqc;
        addLog('   ✅ MultiQC: '+(mqc.sampleStats||[]).length+' samples processed','s');
      }catch(e){addLog('⚠️  MultiQC: '+e.message,'w');}
    }
    if(i===steps.length-1){
      addLog('📝 Generating AI interpretation...','i');
      try{
        S.interpretation=await fetchInterpretation(ds,qc,S.bio,S.fastqc);
        addLog('   ✅ Biological interpretation ready','s');
      }catch(e){S.interpretation='Generation failed: '+e.message;addLog('⚠️  '+e.message,'w');}
    }
    addLog('   ✅ Step '+(i+1)+' done → '+steps[i].out,'s');
    await sleep(80);
  }

  S.pipeProgress=100;
  const outDir=S.cfg.outDir||('~/NGS_Results/'+ds.accession+'_'+new Date().toISOString().slice(0,10));
  addLog('💾 Results saved to: '+outDir+'/','i');
  addLog('   → fastqc_report/ | multiqc_report.html | '+ds.accession+'_results.csv | report.html','d');

  if(S.cfg.email){
    addLog('📧 Preparing email notification...','i');
    await sleep(300);
    const body=generateEmailBody(ds,qc);
    const recipient=encodeURIComponent(S.cfg.notifyEmail||S.cfg.email);
    const subj=encodeURIComponent('NGS Pipeline Complete: '+ds.accession+' — '+ds.condition);
    S.mailtoLink='mailto:'+recipient+'?subject='+subj+'&body='+encodeURIComponent(body);
    S.emailSent=true;
    addLog('   ✅ Email prepared — click "Open in Mail" in Downloads tab','s');
    showNotif('Email ready for '+(S.cfg.notifyEmail||S.cfg.email));
  }

  S.pipeDone=true;
  S.activeStepExplain='';
  addLog('🎉 Pipeline complete! All results ready.','s');
  await sleep(250);

  const initQ='Summarise the key findings from this '+ds.seqType+' analysis.';
  S.chatHistory=[{user:initQ,ai:'Generating summary...'}];
  set({screen:'results',resTab:'overview'});
  try{const ans=await chatWithAI([],initQ,ds,S.bio);S.chatHistory=[{user:initQ,ai:ans}];render();}
  catch{S.chatHistory=[{user:initQ,ai:'AI chat ready. Ask me anything about your results.'}];render();}
}

function reset(){logBuf=[];set({screen:'home',searchResults:[],selectedDs:null,pipeLog:[],stats:null,bio:null,fastqc:null,multiqc:null,interpretation:'',chatHistory:[],pipeDone:false,searchErr:'',pipeStep:-1,pipeProgress:0,emailSent:false,mailtoLink:''});}

// ═══════════════════════════════════════
//  DOWNLOADS (unchanged)
// ═══════════════════════════════════════
function downloadFile(content,filename,mime='text/plain'){
  const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([content],{type:mime}));a.download=filename;document.body.appendChild(a);a.click();document.body.removeChild(a);
  showNotif('Downloaded: '+filename);
}
function generateEmailBody(ds,qc){
  return 'NGS ANALYSIS PIPELINE — COMPLETE\n'+'─'.repeat(50)+'\n\nDataset: '+ds.title+'\nAccession: '+ds.accession+'\nSeqType: '+ds.seqType+'\nCondition: '+ds.condition+'\nOrganism: '+ds.organism+'\nReference Genome: '+S.selectedGenomeId+'\nModel used: '+S.selectedModel+'\n\nQC SUMMARY\n'+'─'.repeat(30)+'\n'+Object.entries(qc).map(([k,v])=>k+': '+v).join('\n')+'\n\nOUTPUT DIRECTORY\n'+( S.cfg.outDir||'~/NGS_Results/'+ds.accession)+'\n\nGenerated: '+new Date().toLocaleString()+'\nPlatform: NGS Analysis Platform (Groq / '+S.selectedModel+')';
}
function generateResultsCSV(){
  const ds=S.selectedDs,bio=S.bio;if(!ds||!bio)return;
  let csv='';
  if(ds.seqType==='RNA-seq'){
    csv='Gene,Direction,Log2FoldChange,padj,BaseMean,Description\n';
    (bio.topGenes||[]).forEach((g,i)=>{csv+=g+','+(bio.directions?.[i]||'')+','+(bio.lfc?.[i]||'')+','+(bio.padj?.[i]||'')+','+(bio.baseMean?.[i]||'')+',"'+((bio.geneDesc?.[i]||'').replace(/"/g,"'"))+'"\n';});
  }else if(ds.seqType==='WGS/WGRS'){
    csv='Gene,Chr,Variant,Significance,AlleleFreq,Zygosity,Role\n';
    (bio.topGenes||[]).forEach((g,i)=>{csv+=g+','+(bio.chr?.[i]||'')+','+(bio.variantType?.[i]||'')+','+(bio.significance?.[i]||'')+','+(bio.af?.[i]||'')+','+(bio.zygosity?.[i]||'')+',"'+((bio.geneRole?.[i]||'').replace(/"/g,"'"))+'"\n';});
  }else if(ds.seqType==='ChIP-seq'){
    csv='Motif,PeakPct,Pval,EnrichScore,Target\n';
    (bio.topMotifs||[]).forEach((m,i)=>{csv+=m+','+(bio.motifPct?.[i]||'')+','+(bio.motifPval?.[i]||'')+','+(bio.enrichScore?.[i]||'')+','+(bio.targetGenes?.[i]||'')+'\n';});
  }else{
    csv='Gene,Direction,DeltaBeta,Context,Island,Role\n';
    (bio.topGenes||[]).forEach((g,i)=>{csv+=g+','+(bio.directions?.[i]||'')+','+(bio.deltaBeta?.[i]||'')+','+(bio.context?.[i]||'')+','+(bio.island?.[i]||'')+',"'+((bio.geneRole?.[i]||'').replace(/"/g,"'"))+'"\n';});
  }
  downloadFile(csv,ds.accession+'_results.csv','text/csv');
}
function generateFastQCTxt(){
  const ds=S.selectedDs,fqc=S.fastqc||createFallbackFastQC(S.stats||{}),st=S.stats;if(!ds)return;
  const mods=fqc?.modules||{};
  let txt='FastQC Report — '+ds.title+'\n'+'='.repeat(60)+'\nAccession: '+ds.accession+'\nSeqType: '+ds.seqType+'\nReference: '+S.selectedGenomeId+'\n\nModule Results\n'+'-'.repeat(40)+'\n';
  Object.entries(mods).forEach(([mod,status])=>{txt+='['+status.toUpperCase().padEnd(4)+'] '+mod+'\n';});
  txt+='\nQC Stats\n'+'-'.repeat(40)+'\n'+Object.entries(st||{}).map(([k,v])=>k+': '+v).join('\n');
  if(fqc?.overrepresentedSeqs?.length){txt+='\n\nOverrepresented Sequences\n'+'-'.repeat(40)+'\n';fqc.overrepresentedSeqs.forEach(s=>{txt+=s.seq.slice(0,30)+'... ('+s.pct+'%) — '+s.source+'\n';});}
  txt+='\n\nGenerated: '+new Date().toLocaleString()+'\nModel: '+S.selectedModel;
  downloadFile(txt,ds.accession+'_fastqc_report.txt');
}
function generateAlignmentTSV(){
  const ds=S.selectedDs,st=S.stats,mqc=S.multiqc;if(!ds)return;
  let tsv='Sample\tTotal_Reads\tMapped\tMapping_Rate\tDuplicates\tQ30\tGC\tMean_Insert\n';
  if(mqc?.sampleStats){mqc.sampleStats.forEach(s=>{tsv+=s.name+'\t'+s.totalReads+'\t'+s.mapped+'\t'+s.mappingRate+'\t'+s.duplicates+'\t'+s.q30+'\t'+s.gcContent+'\t'+s.meanLen+'\n';});}
  else{tsv+=(ds.accession)+'\t'+(st?.totalReads||'N/A')+'\tN/A\t'+(st?.mappingRate||'N/A')+'\t'+(st?.pctDup||'N/A')+'\t'+(st?.q30||'N/A')+'\t'+(st?.gcContent||'N/A')+'\tN/A\n';}
  downloadFile(tsv,ds.accession+'_alignment_stats.tsv');
}
function generateHTMLReport(){
  const ds=S.selectedDs,st=S.stats,bio=S.bio,interp=S.interpretation;if(!ds)return;
  const c=SEQ_C[ds.seqType]||'#00c8f0';
  const genes=(bio?.topGenes||bio?.topMotifs||[]).join(', ');
  const steps=PIPE_STEPS[ds.seqType]||[];
  let html='<!DOCTYPE html><html><head><meta charset="UTF-8"><title>NGS Report — '+ds.accession+'</title><style>body{font-family:Arial,sans-serif;max-width:980px;margin:0 auto;padding:32px;background:#f9fafa;color:#1a1a1a}h1{color:'+c+';border-bottom:3px solid '+c+';padding-bottom:10px;font-size:26px}h2{color:#333;margin-top:28px;font-size:18px}.badge{padding:3px 10px;border-radius:4px;background:'+c+'22;color:'+c+';font-size:12px;font-weight:bold;border:1px solid '+c+'44}table{width:100%;border-collapse:collapse;margin-top:12px}th{background:#f0f0f0;padding:9px;text-align:left;font-size:12px;border-bottom:2px solid #ddd}td{padding:8px;border-bottom:1px solid #eee;font-size:13px}.pass{color:#0a9a5a}.warn{color:#d97706}.fail{color:#dc2626}pre{background:#f4f4f4;padding:18px;border-radius:8px;font-size:12px;white-space:pre-wrap;line-height:1.7}.step{padding:8px 12px;margin:4px 0;border-left:3px solid '+c+';background:#f8f8f8;font-size:12px}</style></head><body><h1>NGS Analysis Report</h1><p><span class="badge">'+ds.seqType+'</span> &nbsp;<strong>'+ds.title+'</strong></p><p>Accession: <strong>'+ds.accession+'</strong> | Source: '+ds.source+' | Organism: '+ds.organism+'</p><p>Condition: <strong>'+ds.condition+'</strong> | Samples: '+ds.samples+' | Reference genome: <strong>'+S.selectedGenomeId+'</strong></p><h2>QC Summary</h2><table><table> <tr><th>Metric</th><th>Value</th></tr>'+Object.entries(st||{}).map(([k,v])=>'<tr><td>'+k+'</td><td><strong>'+v+'</strong></td></tr>').join('')+'</table><h2>Key Findings</h2><p>Top features: <strong>'+genes+'</strong></p><h2>Biological Interpretation</h2><pre>'+(interp||'Not generated.')+'</pre><h2>Pipeline Steps</h2>'+steps.map((s,i)=>'<div class="step"><strong>'+(i+1)+'. '+s.name+'</strong> <em>('+s.tool+')</em> → '+s.out+'</div>').join('')+'<hr style="margin-top:32px"><p style="font-size:11px;color:#999">Generated by NGS Analysis Platform on '+new Date().toLocaleString()+' using Groq / '+S.selectedModel+'</p></body></html>';
  downloadFile(html,ds.accession+'_report.html','text/html');
}
function generateAllFiles(){
  generateResultsCSV();
  setTimeout(()=>generateAlignmentTSV(),500);
  setTimeout(()=>generateFastQCTxt(),1000);
  setTimeout(()=>generateHTMLReport(),1500);
}

// ═══════════════════════════════════════
//  SVG CHARTS (unchanged)
// ═══════════════════════════════════════
function svgBase(W,H){return '<svg viewBox="0 0 '+W+' '+H+'" style="width:100%;max-height:'+(H+10)+'px" xmlns="http://www.w3.org/2000/svg">';}
function svgAxes(W,H,pL,pB,pT,pR,xLabel,yLabel){
  return '<line x1="'+pL+'" y1="'+pT+'" x2="'+pL+'" y2="'+(H-pB)+'" stroke="#142028" stroke-width="0.8"/>'
        +'<line x1="'+pL+'" y1="'+(H-pB)+'" x2="'+(W-pR)+'" y2="'+(H-pB)+'" stroke="#142028" stroke-width="0.8"/>'
        +(xLabel?'<text x="'+(W/2)+'" y="'+(H-1)+'" font-size="8.5" fill="#3a7a94" text-anchor="middle" font-family="JetBrains Mono,monospace">'+xLabel+'</text>':'')
        +(yLabel?'<text x="10" y="'+(H/2)+'" font-size="8.5" fill="#3a7a94" text-anchor="middle" font-family="JetBrains Mono,monospace" transform="rotate(-90,10,'+(H/2)+')">'+yLabel+'</text>':'');
}
function loadingPlot(title){return '<div style="height:160px;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px;color:var(--text3)"><div class="spin" style="font-size:20px;color:var(--cyan)">⟳</div><div style="font-size:10px">'+title+' loading...</div></div>';}

function perBaseQualSVG(data){
  if(!data||!data.length)return loadingPlot('Per Base Sequence Quality');
  const W=500,H=215,pL=44,pB=32,pT=18,pR=14;
  const xs=i=>pL+(i/(data.length-1||1))*(W-pL-pR);
  const ys=v=>H-pB-((v-0)/42)*(H-pB-pT);
  let s=svgBase(W,H);
  s+='<rect x="'+pL+'" y="'+ys(28).toFixed(1)+'" width="'+(W-pL-pR)+'" height="'+(ys(0)-ys(28)).toFixed(1)+'" fill="rgba(255,78,106,.06)"/>';
  s+='<rect x="'+pL+'" y="'+ys(36).toFixed(1)+'" width="'+(W-pL-pR)+'" height="'+(ys(28)-ys(36)).toFixed(1)+'" fill="rgba(240,180,41,.05)"/>';
  s+='<rect x="'+pL+'" y="'+pT+'" width="'+(W-pL-pR)+'" height="'+(ys(36)-pT).toFixed(1)+'" fill="rgba(0,200,240,.04)"/>';
  s+='<text x="'+(W-pR+3)+'" y="'+(ys(14)+3).toFixed(1)+'" font-size="7" fill="#3a0010" text-anchor="start">Poor</text>';
  s+='<text x="'+(W-pR+3)+'" y="'+(ys(32)+3).toFixed(1)+'" font-size="7" fill="#3a2000" text-anchor="start">Acceptable</text>';
  s+='<text x="'+(W-pR+3)+'" y="'+(ys(38)+3).toFixed(1)+'" font-size="7" fill="#003a18" text-anchor="start">Good</text>';
  const iqrPath=data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.q25||d.median-3).toFixed(1)).join(' ')
    +' '+data.slice().reverse().map((d,i,arr)=>'L'+xs(arr.length-1-i).toFixed(1)+','+ys(d.q75||d.median+3).toFixed(1)).join(' ')+'Z';
  s+='<path d="'+iqrPath+'" fill="rgba(0,200,240,.13)" stroke="none"/>';
  s+='<path d="'+data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.median).toFixed(1)).join(' ')+'" fill="none" stroke="var(--cyan)" stroke-width="2"/>';
  data.forEach((d,i)=>{s+='<line x1="'+xs(i).toFixed(1)+'" y1="'+ys(d.whisker_lo||d.median-5).toFixed(1)+'" x2="'+xs(i).toFixed(1)+'" y2="'+ys(d.whisker_hi||d.median+5).toFixed(1)+'" stroke="#1c3848" stroke-width="0.6"/>';});
  [0,10,20,28,30,40].forEach(v=>{
    s+='<line x1="'+pL+'" y1="'+ys(v).toFixed(1)+'" x2="'+(W-pR)+'" y2="'+ys(v).toFixed(1)+'" stroke="#0e1e28" stroke-width="0.5" stroke-dasharray="3,4"/>';
    s+='<text x="'+(pL-5)+'" y="'+(ys(v)+3.5).toFixed(1)+'" font-size="8" fill="#2a5a72" text-anchor="end">'+v+'</text>';
  });
  data.filter((_,i)=>i%5===0||i===data.length-1).forEach(d=>{const i=data.indexOf(d);s+='<text x="'+xs(i).toFixed(1)+'" y="'+(H-pB+12)+'" font-size="8" fill="#2a5a72" text-anchor="middle">'+d.pos+'</text>';});
  s+=svgAxes(W,H,pL,pB,pT,pR,'Position in Read (bp)','Phred Quality Score');
  s+='<rect x="'+(pL+5)+'" y="'+(pT+4)+'" width="8" height="5" fill="rgba(0,200,240,.25)" stroke="var(--cyan)" stroke-width="0.8"/><text x="'+(pL+16)+'" y="'+(pT+9)+'" font-size="7.5" fill="var(--text2)">IQR (Q1–Q3)</text>';
  s+='<line x1="'+(pL+72)+'" y1="'+(pT+6.5)+'" x2="'+(pL+84)+'" y2="'+(pT+6.5)+'" stroke="var(--cyan)" stroke-width="2"/><text x="'+(pL+86)+'" y="'+(pT+9)+'" font-size="7.5" fill="var(--text2)">Median</text>';
  s+='</svg>';return s;
}

function perSeqQualSVG(data){
  if(!data||!data.length)return loadingPlot('Per Sequence Quality');
  const maxC=Math.max(...data.map(d=>d.count));
  const W=420,H=200,pL=44,pB=32,pT=18,pR=12;
  const xs=i=>pL+(i/(data.length-1||1))*(W-pL-pR);
  const ys=v=>H-pB-(v/maxC)*(H-pB-pT);
  const areaPath=data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.count).toFixed(1)).join(' ')+' L'+xs(data.length-1).toFixed(1)+','+(H-pB)+' L'+xs(0).toFixed(1)+','+(H-pB)+'Z';
  let s=svgBase(W,H);
  s+='<defs><linearGradient id="pq-grad" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stop-color="var(--cyan)" stop-opacity="0.3"/><stop offset="100%" stop-color="var(--cyan)" stop-opacity="0.02"/></linearGradient></defs>';
  s+='<path d="'+areaPath+'" fill="url(#pq-grad)" stroke="none"/>';
  s+='<path d="'+data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.count).toFixed(1)).join(' ')+'" fill="none" stroke="var(--cyan)" stroke-width="2"/>';
  const peak=data.reduce((a,b)=>a.count>b.count?a:b,data[0]);const pi=data.indexOf(peak);
  s+='<circle cx="'+xs(pi).toFixed(1)+'" cy="'+ys(peak.count).toFixed(1)+'" r="4" fill="var(--cyan)"/>';
  s+='<text x="'+(xs(pi)+5).toFixed(1)+'" y="'+(ys(peak.count)-4).toFixed(1)+'" font-size="8" fill="var(--cyan)">Peak Q'+peak.score+'</text>';
  const q30idx=data.findIndex(d=>d.score>=30);if(q30idx>=0){
    s+='<line x1="'+xs(q30idx).toFixed(1)+'" y1="'+pT+'" x2="'+xs(q30idx).toFixed(1)+'" y2="'+(H-pB)+'" stroke="rgba(0,200,240,.4)" stroke-width="0.8" stroke-dasharray="4,3"/>';
    s+='<text x="'+(xs(q30idx)+3).toFixed(1)+'" y="'+(pT+10)+'" font-size="7.5" fill="#2a6a84">Q30 threshold</text>';
  }
  data.filter((_,i)=>i%2===0).forEach(d=>{const i=data.indexOf(d);s+='<text x="'+xs(i).toFixed(1)+'" y="'+(H-pB+12)+'" font-size="8" fill="#2a5a72" text-anchor="middle">'+d.score+'</text>';});
  s+=svgAxes(W,H,pL,pB,pT,pR,'Mean Quality Score (Phred)','Read Count');
  s+='</svg>';return s;
}

function gcContentSVG(data){
  if(!data||!data.length)return loadingPlot('GC Content');
  const maxV=Math.max(...data.flatMap(d=>[d.actual||0,d.theoretical||0]));
  const W=440,H=200,pL=44,pB=32,pT=24,pR=14;
  const xs=i=>pL+(i/(data.length-1||1))*(W-pL-pR);
  const ys=v=>H-pB-(v/(maxV*1.12))*(H-pB-pT);
  let s=svgBase(W,H);
  s+='<path d="'+data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.actual||0).toFixed(1)).join(' ')+'" fill="none" stroke="#f0b429" stroke-width="2"/>';
  s+='<path d="'+data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.theoretical||0).toFixed(1)).join(' ')+'" fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-dasharray="5,3"/>';
  data.filter((_,i)=>i%4===0).forEach(d=>{const i=data.indexOf(d);s+='<text x="'+xs(i).toFixed(1)+'" y="'+(H-pB+12)+'" font-size="8" fill="#2a5a72" text-anchor="middle">'+d.gc+'%</text>';});
  s+=svgAxes(W,H,pL,pB,pT,pR,'GC Content (%)','Read Count');
  s+='<line x1="'+(pL+5)+'" y1="'+(pT-8)+'" x2="'+(pL+18)+'" y2="'+(pT-8)+'" stroke="#f0b429" stroke-width="2"/><text x="'+(pL+22)+'" y="'+(pT-5)+'" font-size="7.5" fill="var(--text2)">Observed GC</text>';
  s+='<line x1="'+(pL+95)+'" y1="'+(pT-8)+'" x2="'+(pL+108)+'" y2="'+(pT-8)+'" stroke="#38bdf8" stroke-width="1.8" stroke-dasharray="4,2"/><text x="'+(pL+112)+'" y="'+(pT-5)+'" font-size="7.5" fill="var(--text2)">Expected (Normal dist.)</text>';
  s+='</svg>';return s;
}

function seqDupSVG(data){
  if(!data||!data.length)return loadingPlot('Duplication Levels');
  const maxV=Math.max(...data.map(d=>d.pct));
  const W=420,H=205,pL=44,pB=48,pT=18,pR=12;
  const bW=(W-pL-pR)/data.length-2;
  let s=svgBase(W,H);
  data.forEach((d,i)=>{
    const bH=(d.pct/maxV)*(H-pB-pT);const x=pL+i*(bW+2);const y=H-pB-bH;
    const c=i===0?'var(--cyan)':i<3?'var(--gold)':'var(--red)';
    s+='<rect x="'+x.toFixed(1)+'" y="'+y.toFixed(1)+'" width="'+bW.toFixed(1)+'" height="'+bH.toFixed(1)+'" fill="'+c+'" opacity="0.85" rx="2"/>';
    s+='<text x="'+(x+bW/2).toFixed(1)+'" y="'+(H-pB+11)+'" font-size="7.5" fill="#2a5a72" text-anchor="middle" transform="rotate(-35,'+(x+bW/2).toFixed(1)+','+(H-pB+11)+')">'+d.level+'</text>';
    s+='<text x="'+(x+bW/2).toFixed(1)+'" y="'+(y-3).toFixed(1)+'" font-size="7.5" fill="'+c+'" text-anchor="middle" opacity="0.9">'+d.pct.toFixed(1)+'%</text>';
  });
  [0,25,50,75,100].forEach(v=>{if(v>maxV*1.05)return;const y=H-pB-(v/maxV)*(H-pB-pT);s+='<text x="'+(pL-4)+'" y="'+(y+3).toFixed(1)+'" font-size="8" fill="#2a5a72" text-anchor="end">'+v+'%</text><line x1="'+pL+'" y1="'+y.toFixed(1)+'" x2="'+(W-pR)+'" y2="'+y.toFixed(1)+'" stroke="#0e1e28" stroke-width="0.4" stroke-dasharray="3,4"/>';});
  s+=svgAxes(W,H,pL,pB,pT,pR,'Duplication Level','% Total Reads');
  s+='</svg>';return s;
}

function adapterContentSVG(data){
  if(!data||!data.length)return loadingPlot('Adapter Content');
  const maxV=Math.max(2,...data.flatMap(d=>[d.illumina||0,d.nextera||0,d.small_rna||0]));
  const W=480,H=205,pL=44,pB=32,pT=28,pR=14;
  const xs=i=>pL+(i/(data.length-1||1))*(W-pL-pR);
  const ys=v=>H-pB-(v/maxV)*(H-pB-pT);
  let s=svgBase(W,H);
  const lines=[{key:'illumina',c:'var(--cyan)'},{key:'nextera',c:'var(--gold)'},{key:'small_rna',c:'var(--purple)'}];
  lines.forEach(l=>{s+='<path d="'+data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d[l.key]||0).toFixed(1)).join(' ')+'" fill="none" stroke="'+l.c+'" stroke-width="2"/>';});
  data.filter((_,i)=>i%1===0).forEach(d=>{const i=data.indexOf(d);s+='<text x="'+xs(i).toFixed(1)+'" y="'+(H-pB+12)+'" font-size="8" fill="#2a5a72" text-anchor="middle">'+d.pos+'</text>';});
  s+=svgAxes(W,H,pL,pB,pT,pR,'Position in Read (bp)','% Reads with Adapter');
  const leg=[{c:'var(--cyan)',t:'Illumina Universal'},{c:'var(--gold)',t:'Nextera Transposase'},{c:'var(--purple)',t:'Illumina Small RNA'}];
  leg.forEach((l,i)=>{s+='<line x1="'+(pL+5+i*130)+'" y1="'+(pT-9)+'" x2="'+(pL+18+i*130)+'" y2="'+(pT-9)+'" stroke="'+l.c+'" stroke-width="2"/><text x="'+(pL+22+i*130)+'" y="'+(pT-5)+'" font-size="7.5" fill="var(--text2)">'+l.t+'</text>';});
  s+='</svg>';return s;
}

function perBaseNSVG(data){
  if(!data||!data.length)return loadingPlot('Per Base N Content');
  const maxV=Math.max(1,...data.map(d=>d.n||0));
  const W=420,H=180,pL=44,pB=32,pT=18,pR=12;
  const xs=i=>pL+(i/(data.length-1||1))*(W-pL-pR);
  const ys=v=>H-pB-(v/Math.max(maxV,5))*(H-pB-pT);
  let s=svgBase(W,H);
  const areaPath=data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.n||0).toFixed(1)).join(' ')+' L'+xs(data.length-1).toFixed(1)+','+(H-pB)+' L'+xs(0).toFixed(1)+','+(H-pB)+'Z';
  s+='<path d="'+areaPath+'" fill="rgba(255,78,106,.12)" stroke="var(--red)" stroke-width="1.6"/>';
  data.filter((_,i)=>i%5===0).forEach(d=>{const i=data.indexOf(d);s+='<text x="'+xs(i).toFixed(1)+'" y="'+(H-pB+12)+'" font-size="8" fill="#2a5a72" text-anchor="middle">'+d.pos+'</text>';});
  s+=svgAxes(W,H,pL,pB,pT,pR,'Position in Read (bp)','% N (uncalled bases)');
  s+='<text x="'+(pL+4)+'" y="'+(ys(0)+4).toFixed(1)+'" font-size="7.5" fill="var(--cyan)" opacity="0.6">Ideal: 0%</text>';
  s+='</svg>';return s;
}

function seqLengthSVG(data){
  if(!data||!data.length)return loadingPlot('Sequence Length Distribution');
  const maxC=Math.max(...data.map(d=>d.count));
  const W=380,H=180,pL=44,pB=32,pT=18,pR=12;
  const bW=(W-pL-pR)/data.length-3;
  let s=svgBase(W,H);
  data.forEach((d,i)=>{
    const bH=(d.count/maxC)*(H-pB-pT);const x=pL+i*(bW+3);
    s+='<rect x="'+x.toFixed(1)+'" y="'+(H-pB-bH).toFixed(1)+'" width="'+bW.toFixed(1)+'" height="'+bH.toFixed(1)+'" fill="var(--teal)" opacity="0.85" rx="2"/>';
    s+='<text x="'+(x+bW/2).toFixed(1)+'" y="'+(H-pB+12)+'" font-size="9" fill="#2a5a72" text-anchor="middle">'+d.length+'</text>';
    s+='<text x="'+(x+bW/2).toFixed(1)+'" y="'+(H-pB-bH-4).toFixed(1)+'" font-size="8" fill="var(--teal)" text-anchor="middle">'+d.count.toLocaleString()+'</text>';
  });
  s+=svgAxes(W,H,pL,pB,pT,pR,'Read Length (bp)','Count');
  s+='</svg>';return s;
}

function volcanoSVG(bio,qc){
  const genes=bio?.topGenes||[],lfc=bio?.lfc||[],padj=bio?.padj||[];
  const pts=[];
  genes.forEach((g,i)=>{const l=+lfc[i]||(i%2===0?rnd(1.5,4,2):-rnd(1.5,3.5,2));const p=Math.min(-Math.log10(parseFloat(padj[i])||1e-5),7);pts.push({lfc:l,p,sig:true,label:g});});
  for(let i=0;i<300;i++){const sig=i<(qc.degUp||80)-genes.length/2?1:i<(qc.degUp||80)+(qc.degDown||60)-genes.length?-1:0;const l=sig===1?rnd(1,4.5,2):sig===-1?-rnd(1,4.5,2):(Math.random()-.5)*1.8;const p=sig!==0?rnd(1.5,6.5,2):rnd(0,1.3,2);pts.push({lfc:+l,p:+p,sig:sig!==0});}
  const W=500,H=235,pL=44,pB=32,pT=18,pR=18;
  const xs=v=>pL+((v+5.5)/11)*(W-pL-pR);
  const ys=v=>H-pB-(v/7.5)*(H-pB-pT);
  let s=svgBase(W,H);
  s+='<rect x="'+xs(1).toFixed(1)+'" y="'+pT+'" width="'+(W-pR-xs(1)).toFixed(1)+'" height="'+(H-pB-pT)+'" fill="rgba(255,78,106,.03)"/>';
  s+='<rect x="'+pL+'" y="'+pT+'" width="'+(xs(-1)-pL).toFixed(1)+'" height="'+(H-pB-pT)+'" fill="rgba(0,200,240,.03)"/>';
  pts.forEach(p=>{s+='<circle cx="'+xs(p.lfc).toFixed(1)+'" cy="'+ys(p.p).toFixed(1)+'" r="'+(p.label?3.5:p.sig?2:1.2)+'" fill="'+(p.lfc>1&&p.p>1.3?'var(--red)':p.lfc<-1&&p.p>1.3?'var(--cyan)':'#142a38')+'" opacity="'+(p.label?1:p.sig?.75:.3)+'"/>';});
  pts.filter(p=>p.label).forEach(p=>{s+='<text x="'+(xs(p.lfc)+5).toFixed(1)+'" y="'+(ys(p.p)-2).toFixed(1)+'" font-size="7.5" fill="'+(p.lfc>0?'var(--red)':'var(--cyan)')+'" font-weight="700">'+p.label+'</text>';});
  s+='<line x1="'+xs(1).toFixed(1)+'" y1="'+pT+'" x2="'+xs(1).toFixed(1)+'" y2="'+(H-pB)+'" stroke="var(--red)" stroke-width="0.9" stroke-dasharray="4,3" opacity="0.5"/>';
  s+='<line x1="'+xs(-1).toFixed(1)+'" y1="'+pT+'" x2="'+xs(-1).toFixed(1)+'" y2="'+(H-pB)+'" stroke="var(--cyan)" stroke-width="0.9" stroke-dasharray="4,3" opacity="0.5"/>';
  s+='<line x1="'+pL+'" y1="'+ys(1.3).toFixed(1)+'" x2="'+(W-pR)+'" y2="'+ys(1.3).toFixed(1)+'" stroke="#1e4a5a" stroke-width="0.6" stroke-dasharray="4,3"/>';
  s+='<text x="'+(W-pR-2)+'" y="'+(ys(1.3)-3).toFixed(1)+'" font-size="7.5" fill="#2a5a72" text-anchor="end">padj = 0.05</text>';
  s+='<text x="'+xs(2.8).toFixed(1)+'" y="'+(pT+12)+'" font-size="9" fill="var(--red)" text-anchor="middle" opacity="0.85">↑ UP ('+( qc.degUp||'?')+')</text>';
  s+='<text x="'+xs(-2.8).toFixed(1)+'" y="'+(pT+12)+'" font-size="9" fill="var(--cyan)" text-anchor="middle" opacity="0.85">↓ DOWN ('+(qc.degDown||'?')+')</text>';
  [-4,-2,0,2,4].forEach(v=>{s+='<text x="'+xs(v).toFixed(1)+'" y="'+(H-pB+12)+'" font-size="8" fill="#2a5a72" text-anchor="middle">'+v+'</text>';});
  [0,2,4,6].forEach(v=>{s+='<text x="'+(pL-4)+'" y="'+(ys(v)+3).toFixed(1)+'" font-size="8" fill="#2a5a72" text-anchor="end">'+v+'</text>';});
  s+=svgAxes(W,H,pL,pB,pT,pR,'log₂ Fold Change','−log₁₀(padj)');
  s+='</svg>';return s;
}

function heatmapSVG(bio){
  const genes=(bio?.topGenes||[]).slice(0,10);
  const dirs=bio?.directions||genes.map((_,i)=>i<5?'UP':'DOWN');
  const samps=['D1','D2','D3','D4','D5','N1','N2','N3','N4','N5'];
  const rows=genes.map((_,gi)=>{
    const up=dirs[gi]==='UP'||dirs[gi]==='Hyper';
    return samps.map((_,si)=>{const d=si<5;const b=up?(d?rnd(2,4.5,2):rnd(-1.8,-0.2,2)):(d?rnd(-4,-1.5,2):rnd(0.2,2.2,2));return +(b+(Math.random()-.5)*0.35).toFixed(2);});
  });
  const cW=33,cH=18,lW=80,tP=26,scW=55;
  const W=lW+samps.length*cW+scW+10,H=tP+rows.length*cH+24;
  const clr=v=>{const t=(+v+5)/10;if(t>.6)return 'rgb('+Math.round(220-t*40)+','+Math.round(20+t*18)+',30)';if(t<.38)return 'rgb(10,'+Math.round(80+(1-t)*70)+','+Math.round(170+(1-t)*40)+')';return 'rgb(10,18,14)';};
  let s=svgBase(W,H);
  samps.forEach((sm,si)=>{s+='<text x="'+(lW+si*cW+cW/2)+'" y="'+(tP-8)+'" font-size="8" fill="'+(si<5?'rgba(255,78,106,.8)':'rgba(0,200,240,.8)')+'" text-anchor="middle" font-weight="700">'+sm+'</text>';});
  s+='<text x="'+(lW+2.5*cW)+'" y="'+H+'" font-size="8" fill="rgba(255,78,106,.6)" text-anchor="middle">▲ Disease</text>';
  s+='<text x="'+(lW+7*cW)+'" y="'+H+'" font-size="8" fill="rgba(0,200,240,.6)" text-anchor="middle">▼ Control</text>';
  rows.forEach((row,gi)=>{
    s+='<text x="'+(lW-5)+'" y="'+(tP+gi*cH+cH*.72)+'" font-size="8.5" fill="'+(dirs[gi]==='UP'||dirs[gi]==='Hyper'?'var(--red)':'var(--cyan)')+'" text-anchor="end" font-weight="600">'+(genes[gi]||'')+'</text>';
    row.forEach((v,si)=>{s+='<rect x="'+(lW+si*cW)+'" y="'+(tP+gi*cH)+'" width="'+(cW-1)+'" height="'+(cH-1)+'" fill="'+clr(v)+'" rx="1.5"><title>'+( genes[gi]||'')+' '+samps[si]+': z='+v+'</title></rect>';});
    s+='<text x="'+(lW+samps.length*cW+5)+'" y="'+(tP+gi*cH+cH*.72)+'" font-size="7.5" fill="'+(dirs[gi]==='UP'||dirs[gi]==='Hyper'?'var(--red)':'var(--cyan)')+'">'+dirs[gi]+'</text>';
  });
  const scX=lW+samps.length*cW+16,scY=tP+4;
  s+='<defs><linearGradient id="hm-sc" x1="0" x2="0" y1="0" y2="1"><stop offset="0%" stop-color="rgb(220,30,30)"/><stop offset="50%" stop-color="rgb(10,18,14)"/><stop offset="100%" stop-color="rgb(10,130,200)"/></linearGradient></defs>';
  s+='<rect x="'+scX+'" y="'+scY+'" width="8" height="60" fill="url(#hm-sc)" rx="2"/>';
  s+='<text x="'+(scX+12)+'" y="'+(scY+3)+'" font-size="7" fill="var(--red)">+5</text>';
  s+='<text x="'+(scX+12)+'" y="'+(scY+32)+'" font-size="7" fill="#3a6a5a">0</text>';
  s+='<text x="'+(scX+12)+'" y="'+(scY+62)+'" font-size="7" fill="var(--cyan)">-5</text>';
  s+='<text x="'+(scX+4)+'" y="'+(scY-4)+'" font-size="7" fill="var(--text3)" text-anchor="middle">z</text>';
  s+='</svg>';return s;
}

function pcaSVG(ds){
  const parts=(ds?.condition||'Disease vs Control').split(/\s+vs\s+/i);
  const l1=(parts[0]||'Disease').trim().slice(0,14);
  const l2=(parts[1]||'Control').trim().slice(0,14);
  const grps=[{label:l1,c:'var(--red)',pts:Array.from({length:10},()=>[rnd(-4.5,-.5,2),rnd(-3,3,2)])},{label:l2,c:'var(--cyan)',pts:Array.from({length:10},()=>[rnd(.5,4.5,2),rnd(-3,3,2)])}];
  const W=460,H=230,pad=42;
  const xs=v=>pad+((+v+5)/10.5)*(W-pad*2);
  const ys=v=>H-pad-((+v+3.5)/7.5)*(H-pad*2);
  let s=svgBase(W,H);
  s+='<line x1="'+pad+'" y1="'+(H/2)+'" x2="'+(W-pad)+'" y2="'+(H/2)+'" stroke="#0e2030" stroke-width="0.7"/>';
  s+='<line x1="'+(W/2)+'" y1="'+pad+'" x2="'+(W/2)+'" y2="'+(H-pad)+'" stroke="#0e2030" stroke-width="0.7"/>';
  grps.forEach(gr=>{
    const avgX=gr.pts.reduce((a,p)=>a+p[0],0)/gr.pts.length;
    const avgY=gr.pts.reduce((a,p)=>a+p[1],0)/gr.pts.length;
    s+='<ellipse cx="'+xs(avgX).toFixed(1)+'" cy="'+ys(avgY).toFixed(1)+'" rx="50" ry="35" fill="'+gr.c+'" fill-opacity="0.06" stroke="'+gr.c+'" stroke-width="0.8" stroke-dasharray="4,3"/>';
    gr.pts.forEach(p=>{s+='<circle cx="'+xs(p[0]).toFixed(1)+'" cy="'+ys(p[1]).toFixed(1)+'" r="6.5" fill="'+gr.c+'" opacity="0.75"/>';});
  });
  grps.forEach((gr,i)=>{s+='<circle cx="'+(pad+10+i*150)+'" cy="'+(H-10)+'" r="5.5" fill="'+gr.c+'" opacity="0.8"/><text x="'+(pad+22+i*150)+'" y="'+(H-5)+'" font-size="9.5" fill="var(--text2)">'+gr.label+'</text>';});
  s+=svgAxes(W,H,pad,pad,pad,pad,'PC1 (38.2% variance explained)','PC2 (21.7% variance)');
  s+='</svg>';return s;
}

function qualBarSVG(q30,mr){
  const bars=[{l:'Q30 Bases',v:parseFloat(q30||'88'),c:'var(--cyan)',desc:'Bases exceeding Phred Q30 quality threshold'},{l:'Mapping Rate',v:parseFloat(mr||'94'),c:'var(--green)',desc:'Reads successfully mapped to reference genome'}];
  const W=400,H=138;let s=svgBase(W,H);
  bars.forEach((b,i)=>{const y=14+i*58;const pct=Math.min(b.v,100);
    s+='<text x="90" y="'+(y+14)+'" font-size="9.5" fill="var(--text2)" text-anchor="end">'+b.l+'</text>';
    s+='<rect x="96" y="'+y+'" width="240" height="26" fill="var(--bg3)" rx="4"/>';
    s+='<rect x="96" y="'+y+'" width="'+(pct/100*240).toFixed(1)+'" height="26" fill="'+b.c+'" rx="4" opacity="0.85"/>';
    s+='<text x="'+(98+pct/100*240).toFixed(1)+'" y="'+(y+17)+'" font-size="11" fill="'+b.c+'" font-weight="700">'+b.v.toFixed(1)+'%</text>';
    s+='<text x="96" y="'+(y+40)+'" font-size="8" fill="var(--text3)">'+b.desc+'</text>';
  });
  s+='</svg>';return s;
}

function methylBarSVG(bio){
  if(!bio?.topGenes)return qualBarSVG('88','82');
  const genes=bio.topGenes.slice(0,8),dirs=bio.directions||[],delta=bio.deltaBeta||[];
  const W=460,pH=18,lW=82,bW=220,gap=5,pad=8,headH=20;const H=pad+headH+genes.length*(pH+gap)+pad;
  let s=svgBase(W,H);
  s+='<text x="'+lW+'" y="'+(pad+13)+'" font-size="8.5" fill="var(--text2)">◀ Hypo-methylated</text>';
  s+='<text x="'+(lW+bW-20)+'" y="'+(pad+13)+'" font-size="8.5" fill="var(--text2)" text-anchor="end">Hyper-methylated ▶</text>';
  genes.forEach((g,i)=>{
    const d=dirs[i]||'Hypo';const db=Math.abs(delta[i]||0.2);
    const c=d==='Hyper'?'var(--red)':'var(--cyan)';
    const bLen=(db/0.6*bW).toFixed(1);const y=pad+headH+i*(pH+gap);
    s+='<text x="'+(lW-5)+'" y="'+(y+pH*.72)+'" font-size="8.5" fill="'+c+'" text-anchor="end" font-weight="700">'+g+'</text>';
    s+='<rect x="'+lW+'" y="'+y+'" width="'+bW+'" height="'+pH+'" fill="var(--bg3)" rx="3"/>';
    s+='<rect x="'+lW+'" y="'+y+'" width="'+bLen+'" height="'+pH+'" fill="'+c+'" rx="3" opacity="0.85"/>';
    s+='<text x="'+(lW+parseFloat(bLen)+6)+'" y="'+(y+pH*.75)+'" font-size="8.5" fill="'+c+'">'+d+' Δβ='+(delta[i]||0).toFixed(2)+'</text>';
  });
  s+='</svg>';return s;
}

function motifBarSVG(bio){
  if(!bio?.topMotifs)return qualBarSVG('88','82');
  const motifs=bio.topMotifs.slice(0,7),pcts=bio.motifPct||motifs.map(()=>rnd(15,60)+'%'),pvals=bio.motifPval||motifs.map(()=>'1e-'+Math.floor(rnd(18,45,0)));
  const W=500,pH=18,lW=115,bW=185,gap=5,pad=8,headH=18;const H=pad+headH+motifs.length*(pH+gap)+pad;
  let s=svgBase(W,H);
  s+='<text x="'+lW+'" y="'+(pad+12)+'" font-size="8.5" fill="var(--text2)">% Targets with Motif</text>';
  motifs.forEach((m,i)=>{const pct=parseFloat(pcts[i]||'30');const y=pad+headH+i*(pH+gap);
    s+='<text x="'+(lW-5)+'" y="'+(y+pH*.72)+'" font-size="8.5" fill="var(--purple)" text-anchor="end" font-weight="700">'+m+'</text>';
    s+='<rect x="'+lW+'" y="'+y+'" width="'+bW+'" height="'+pH+'" fill="var(--bg3)" rx="3"/>';
    s+='<rect x="'+lW+'" y="'+y+'" width="'+(pct/100*bW).toFixed(1)+'" height="'+pH+'" fill="var(--purple)" rx="3" opacity="0.8"/>';
    s+='<text x="'+(lW+pct/100*bW+6)+'" y="'+(y+pH*.75)+'" font-size="8.5" fill="var(--purple)">'+pcts[i]+' · p='+pvals[i]+'</text>';
  });
  s+='</svg>';return s;
}

function insertSizeSVG(data){
  if(!data||!data.length)return loadingPlot('Insert Size Distribution');
  const maxC=Math.max(...data.map(d=>d.count));
  const W=420,H=200,pL=44,pB=32,pT=18,pR=12;
  const xs=i=>pL+(i/(data.length-1||1))*(W-pL-pR);
  const ys=v=>H-pB-(v/maxC)*(H-pB-pT);
  let s=svgBase(W,H);
  s+='<defs><linearGradient id="is-g" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stop-color="var(--teal)" stop-opacity="0.3"/><stop offset="100%" stop-color="var(--teal)" stop-opacity="0.02"/></linearGradient></defs>';
  const areaPath=data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.count).toFixed(1)).join(' ')+' L'+xs(data.length-1).toFixed(1)+','+(H-pB)+' L'+xs(0).toFixed(1)+','+(H-pB)+'Z';
  s+='<path d="'+areaPath+'" fill="url(#is-g)" stroke="none"/>';
  s+='<path d="'+data.map((d,i)=>(i===0?'M':'L')+xs(i).toFixed(1)+','+ys(d.count).toFixed(1)).join(' ')+'" fill="none" stroke="var(--teal)" stroke-width="2"/>';
  data.filter((_,i)=>i%3===0).forEach(d=>{const i=data.indexOf(d);s+='<text x="'+xs(i).toFixed(1)+'" y="'+(H-pB+12)+'" font-size="8" fill="#2a5a72" text-anchor="middle">'+d.size+'</text>';});
  s+=svgAxes(W,H,pL,pB,pT,pR,'Insert Size (bp)','Count');
  s+='</svg>';return s;
}

function coverageSVG(data){
  if(!data||!data.length)return loadingPlot('Coverage per Chromosome');
  const maxV=Math.max(...data.map(d=>d.mean||0));
  const W=430,H=200,pL=44,pB=42,pT=18,pR=12;
  const bW=(W-pL-pR)/data.length-3;
  let s=svgBase(W,H);
  data.forEach((d,i)=>{
    const bH=((d.mean||0)/Math.max(maxV,1))*(H-pB-pT);const x=pL+i*(bW+3);
    s+='<rect x="'+x.toFixed(1)+'" y="'+(H-pB-bH).toFixed(1)+'" width="'+bW.toFixed(1)+'" height="'+bH.toFixed(1)+'" fill="var(--cyan)" opacity="0.75" rx="2"/>';
    s+='<text x="'+(x+bW/2).toFixed(1)+'" y="'+(H-pB+13)+'" font-size="7.5" fill="#2a5a72" text-anchor="middle" transform="rotate(-35,'+(x+bW/2).toFixed(1)+','+(H-pB+13)+')">'+( d.chr||'')+'</text>';
    s+='<text x="'+(x+bW/2).toFixed(1)+'" y="'+(H-pB-bH-3).toFixed(1)+'" font-size="7.5" fill="var(--cyan)" text-anchor="middle">'+( d.mean||0).toFixed(0)+'x</text>';
  });
  s+=svgAxes(W,H,pL,pB,pT,pR,'Chromosome','Mean Coverage (×)');
  s+='</svg>';return s;
}

// ═══════════════════════════════════════
//  SCREEN RENDERERS (unchanged but rely on robust data)
// ═══════════════════════════════════════
function apiBar(){
  const connected=!!S.groqKey;
  const model=GROQ_MODELS.find(m=>m.id===S.selectedModel)||GROQ_MODELS[0];
  return '<div class="api-bar">'
    +'<div class="dot '+(connected?'dot-cyan':'dot-dim')+'"></div>'
    +'<span style="font-size:10px;color:var(--text2);letter-spacing:.5px">GROQ API</span>'
    +(connected?'<span style="font-size:10px;color:var(--cyan)">✓ Connected</span>':'<span style="font-size:10px;color:var(--gold)" class="pulse">⚠ Key required</span>')
    +'<span style="font-size:10px;color:var(--text3)">Model: '+model.label+'</span>'
    +'<span class="tag" style="background:var(--cbg);color:var(--cyan);margin-left:4px;font-size:8px">'+model.badge+'</span>'
    +'<span style="font-size:10px;color:var(--text3);margin-left:auto">800+ tokens/sec · Free tier</span>'
    +'</div>';
}

function renderHome(){
  return '<div class="page">'
  +'<div class="hero">'
  +'<div class="hero-title">NGS Analysis Platform</div>'
  +'<div class="hero-sub">Full next-generation sequencing pipeline powered by <b style="color:var(--cyan)">Groq free LLM</b> (Llama 3.3 70B). FastQC quality reports, MultiQC summaries, DEG/variant/methylation analysis, biological interpretation, and real file downloads — all dataset-specific.</div>'
  +'</div>'
  +apiBar()
  +'<div class="card" style="margin-bottom:14px">'
  +'<div class="card-title">Groq API Key + Model Selection</div>'
  +'<div style="display:flex;gap:10px;margin-bottom:12px;flex-wrap:wrap">'
  +'<input class="inp" id="groq-key-inp" type="password" value="'+h(S.groqKey)+'" placeholder="gsk_...  (get free key at console.groq.com)" style="flex:1;min-width:240px"/>'
  +'<select class="inp" style="width:240px" id="model-sel">'
  +GROQ_MODELS.map(m=>'<option value="'+m.id+'"'+(S.selectedModel===m.id?' selected':'')+'>'+m.label+' ['+m.badge+']</option>').join('')
  +'</select>'
  +'</div>'
  +'<div style="font-size:10px;color:var(--text3)">Free at <a href="https://console.groq.com" target="_blank" style="color:var(--cyan)">console.groq.com</a> — 14,400 requests/day · 800+ tokens/sec · No credit card required</div>'
  +'</div>'
  +'<div style="display:flex;gap:10px;margin-bottom:16px">'
  +[['query','🔍 Search','Find public datasets from GEO/SRA/ENA'],['path','📂 Directory','Local FASTQ/BAM/VCF path'],['upload','⬆ Upload','Upload your sequencing files']].map(([id,ic,lb])=>'<button class="mode-btn '+(S.inputMode===id?'active':'')+'" onclick="set({inputMode:\''+id+'\'})"><div style="font-size:13px;font-weight:700;color:'+(S.inputMode===id?'var(--cyan)':'var(--text2)')+';margin-bottom:4px">'+ic+'</div><div style="font-size:10px;color:var(--text3)">'+lb+'</div></button>').join('')
  +'</div>'
  +'<div class="card">'
  +(S.inputMode==='query'?
    '<div class="card-title">Disease / phenotype / biological condition</div>'
    +'<div style="display:flex;gap:8px;margin-bottom:12px">'
    +'<input class="inp" id="query-inp" value="'+h(S.queryInput)+'" placeholder="e.g. Alzheimer ChIP-seq, breast cancer WGBS, COPD transcriptome"/>'
    +'<button class="btn" onclick="set({queryInput:document.getElementById(\'query-inp\')?.value||\'\'});doSearch()">Search →</button>'
    +'</div>'
    +'<div style="font-size:10px;color:var(--text3);margin-bottom:10px">Returns realistic public dataset accessions from GEO · NCBI SRA · ENA · ArrayExpress</div>'
    +'<div style="display:flex;gap:6px;flex-wrap:wrap">'+EXAMPLES.map(ex=>'<button class="btn-sm" onclick="set({queryInput:\''+ex.replace(/'/g,"\\'")+'\'})">'+ex+'</button>').join('')+'</div>'
  :'')
  +(S.inputMode==='path'?
    '<div class="card-title">Local directory or file path</div>'
    +'<div style="display:flex;gap:8px;margin-bottom:8px">'
    +'<input class="inp" id="dir-inp" value="'+h(S.dirInput)+'" placeholder="/data/rnaseq_project   or   ~/Desktop/wgs_samples"/>'
    +'<button class="btn" onclick="set({dirInput:document.getElementById(\'dir-inp\')?.value||\'\'});doSearch()">Detect →</button>'
    +'</div>'
    +'<div style="font-size:10px;color:var(--text3)">Auto-detects FASTQ, BAM, SAM, VCF, BED files. Infers sequencing type from filenames.</div>'
  :'')
  +(S.inputMode==='upload'?
    '<div class="card-title">Upload sequencing files</div>'
    // Category selector
    +'<div style="margin-bottom:14px">'
    +'<label style="font-size:10px;color:var(--text2);display:block;margin-bottom:7px;letter-spacing:1px">SEQUENCING CATEGORY <span style="color:var(--red)">*</span></label>'
    +'<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px">'
    +Object.entries(UPLOAD_CATEGORIES).map(([k,v])=>'<button class="mode-btn '+(S.uploadCategory===k?'active':'')+'" style="padding:10px 12px" onclick="set({uploadCategory:\''+k+'\'})">'
      +'<div style="font-size:16px;margin-bottom:3px">'+v.icon+'</div>'
      +'<div style="font-size:10px;font-weight:700;color:'+(S.uploadCategory===k?'var(--cyan)':'var(--text)')+';margin-bottom:2px">'+k+'</div>'
      +'<div style="font-size:8.5px;color:var(--text3);line-height:1.4">'+v.desc+'</div>'
      +'</button>').join('')
    +'</div></div>'
    // Requirements panel — shown after category selected
    +(S.uploadCategory&&UPLOAD_CATEGORIES[S.uploadCategory]?
      (()=>{const cat=UPLOAD_CATEGORIES[S.uploadCategory];return ''
        +'<div style="background:var(--bg3);border:1px solid var(--border2);border-radius:10px;padding:14px 16px;margin-bottom:14px">'
        +'<div style="font-size:9px;letter-spacing:1.5px;color:var(--text2);margin-bottom:10px;text-transform:uppercase">'+cat.icon+' Required files — '+S.uploadCategory+'</div>'
        +'<div style="margin-bottom:10px">'+cat.required.map(r=>'<div style="display:flex;gap:8px;align-items:flex-start;padding:4px 0;font-size:10.5px;color:var(--text);border-bottom:1px solid var(--border)"><span style="color:var(--cyan);flex-shrink:0;margin-top:1px">✓</span>'+r+'</div>').join('')+'</div>'
        +(cat.optional.length?'<div style="font-size:9px;color:var(--text3);letter-spacing:1px;margin-bottom:6px">OPTIONAL / ACCEPTED</div>'
          +cat.optional.map(o=>'<div style="display:flex;gap:8px;align-items:flex-start;padding:3px 0;font-size:10px;color:var(--text3)"><span style="color:var(--border2);flex-shrink:0">◦</span>'+o+'</div>').join(''):'')
        +'<div style="margin-top:10px;padding:8px 10px;background:var(--bg4);border-radius:6px;font-size:9.5px;color:var(--text3)">ℹ '+cat.notes+'</div>'
        +'</div>';})()
    :'<div style="padding:12px;background:var(--bg3);border-radius:8px;font-size:11px;color:var(--text3);margin-bottom:14px">← Select a sequencing category above to see file requirements</div>')
    // Drop zone — disabled if no category
    +'<div class="drop-zone" id="drop-z" style="'+(S.uploadCategory?'':'opacity:.4;pointer-events:none')+'" onclick="document.getElementById(\'file-inp\').click()">'
    +'<div style="font-size:32px;margin-bottom:8px">⬆</div>'
    +'<div style="font-size:13px;color:var(--text2);font-weight:600">Click to browse or drag & drop</div>'
    +'<div style="font-size:10px;color:var(--text3);margin-top:6px">'+(S.uploadCategory?UPLOAD_CATEGORIES[S.uploadCategory]?.accept?.replace(/\./g,'').toUpperCase().replace(/,/g,' · '):'FASTQ · FASTQ.GZ · BAM · SAM · VCF · BED · GTF')+'</div>'
    +'</div>'
    +'<input type="file" id="file-inp" multiple style="display:none" accept="'+(S.uploadCategory?UPLOAD_CATEGORIES[S.uploadCategory]?.accept||'.fastq,.fq,.gz,.bam,.sam,.vcf,.bed,.gtf,.txt':'.fastq,.fq,.gz,.bam,.sam,.vcf,.bed,.gtf,.txt')+'" onchange="handleFiles(this.files)"/>'
    +(S.uploadedFiles.length?'<div style="margin-top:10px">'+S.uploadedFiles.map(f=>'<div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid var(--border);font-size:11px"><span>📄 '+h(f.name)+'</span><span style="color:var(--text2)">'+(f.size/1e6).toFixed(1)+' MB</span></div>').join('')+'</div>':'')
    +'<div style="margin-top:12px;display:flex;gap:10px;align-items:center">'
    +'<button class="btn" onclick="doSearch()" '+(!S.uploadedFiles.length||!S.uploadCategory?'disabled':'')+'>Analyse '+( S.uploadedFiles.length||'')+' file(s) →</button>'
    +(!S.uploadCategory&&S.uploadedFiles.length?'<span style="font-size:10px;color:var(--gold)">⚠ Select a category to enable analysis</span>':'')
    +'</div>'
  :'')
  +(S.searchErr?'<div class="err-box">⚠ '+h(S.searchErr)+'</div>':'')
  +'</div>'
  +'<div class="g4" style="margin-top:6px">'
  +Object.entries({'RNA-seq':'STAR + DESeq2, volcano, PCA, heatmap, GSEA','WGS/WGRS':'BWA-MEM2 + GATK4, SNV/InDel annotation, VQSR','ChIP-seq':'Bowtie2 + MACS2, Homer motifs, IDR reproducibility','Bisulfite-seq':'Bismark + DSS, CpG context, differential methylation'}).map(([t,d])=>'<div class="card" style="margin-bottom:0;border-left:3px solid '+SEQ_C[t]+'"><div class="tag" style="background:'+SEQ_B[t]+';color:'+SEQ_C[t]+';margin-bottom:8px">'+t+'</div><div style="font-size:10px;color:var(--text3);line-height:1.7">'+d+'</div></div>').join('')
  +'</div>'
  +'</div>';
}

function renderSelect(){
  const PAGE_SIZE=4;
  const totalPages=Math.ceil(S.searchResults.length/PAGE_SIZE);
  const page=Math.min(S.searchPage||0,Math.max(0,totalPages-1));
  const pageResults=S.searchResults.slice(page*PAGE_SIZE,(page+1)*PAGE_SIZE);

  return '<div class="page">'
  +'<div style="display:flex;align-items:center;gap:12px;margin-bottom:22px">'
  +'<button class="btn-ghost" onclick="reset()">← Back</button>'
  +'<div><div style="font-size:20px;font-weight:700;font-family:var(--font-sans)">Select Dataset</div>'
  +'<div style="font-size:11px;color:var(--text2)">'+S.searchResults.length+' datasets found · choose one to configure & run</div></div>'
  +'</div>'
  +pageResults.map(ds=>{
    const c=SEQ_C[ds.seqType]||'var(--cyan)',b=SEQ_B[ds.seqType]||'var(--bg3)',sel=S.selectedDs?.id===ds.id;
    return '<div style="background:var(--bg2);border:1px solid '+(sel?c:'var(--border)')+';border-left:3px solid '+c+';border-radius:12px;padding:18px 20px;margin-bottom:10px;cursor:pointer;transition:all .15s;'+(sel?'background:'+b+';box-shadow:0 0 20px rgba(0,200,240,.08)':'')+'" onclick=\'selectDs('+JSON.stringify(ds).replace(/</g,'\\u003c').replace(/'/g,"&#39;")+')\' >'
      +'<div style="display:flex;align-items:flex-start;gap:12px">'
      +'<div style="flex:1">'
      +'<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;flex-wrap:wrap">'
      +'<span class="tag" style="background:'+b+';color:'+c+'">'+ds.seqType+'</span>'
      +'<span class="tag" style="background:var(--bg3);color:var(--text3)">'+ds.source+'</span>'
      +'<code style="font-size:10px;color:var(--text3)">'+h(ds.accession)+'</code>'
      +(ds.pmid?'<span style="font-size:10px;color:'+c+'">PMID: '+ds.pmid+'</span>':'')
      +'</div>'
      +'<div style="font-size:14px;font-weight:600;margin-bottom:5px;font-family:var(--font-sans)">'+h(ds.title)+'</div>'
      +'<div style="font-size:11px;color:var(--text2);line-height:1.7;margin-bottom:8px">'+h(ds.description)+'</div>'
      +'<div style="display:flex;gap:14px;flex-wrap:wrap;font-size:10px;color:var(--text2)">'
      +'<span>🧬 '+h(ds.organism)+'</span><span>📊 '+ds.samples+' samples</span><span>📅 '+ds.year+'</span><span>💾 '+h(ds.sizeGB)+' GB</span><span>🔬 '+h(ds.condition)+'</span>'
      +'</div></div>'
      +'<div style="width:22px;height:22px;border-radius:50%;border:2px solid '+(sel?c:'var(--border2)')+';background:'+(sel?c:'transparent')+';display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:10px;color:#000">'+(sel?'✓':'')+'</div>'
      +'</div></div>';
  }).join('')
  +(S.selectedDs?'<div class="sticky-cta"><button class="btn" style="font-size:13px;padding:12px 32px;box-shadow:0 4px 24px rgba(0,200,240,.3)" onclick="set({screen:\'genome\'})">Select Reference Genome →</button></div>':'')
  // Pagination controls
  +(totalPages>1?'<div style="display:flex;align-items:center;justify-content:center;gap:8px;margin-top:18px;padding-bottom:8px">'
    +'<button class="btn-ghost" style="padding:6px 14px;font-size:11px" onclick="set({searchPage:Math.max(0,'+(page-1)+''+')})" '+(page===0?'disabled':'')+'>← Prev</button>'
    +Array.from({length:totalPages},(_,i)=>'<button class="btn-sm '+(i===page?'active':'')+'" onclick="set({searchPage:'+i+'})" style="min-width:32px;text-align:center">'+(i+1)+'</button>').join('')
    +'<button class="btn-ghost" style="padding:6px 14px;font-size:11px" onclick="set({searchPage:Math.min('+(totalPages-1)+','+(page+1)+''+')})" '+(page===totalPages-1?'disabled':'')+'>Next →</button>'
    +'<span style="font-size:9.5px;color:var(--text3);margin-left:8px">Page '+(page+1)+' of '+totalPages+' · '+S.searchResults.length+' total</span>'
    +'</div>':'')
  +'</div>';
}

function renderGenome(){
  const ds=S.selectedDs;
  const c=SEQ_C[ds.seqType];
  const orgs=Object.keys(REFERENCE_GENOMES);
  const curGenomes=REFERENCE_GENOMES[S.selectedGenomeOrg]||[];
  return '<div class="page">'
  +'<div style="display:flex;align-items:center;gap:12px;margin-bottom:22px">'
  +'<button class="btn-ghost" onclick="set({screen:\'select\'})">← Back</button>'
  +'<div><div style="font-size:20px;font-weight:700;font-family:var(--font-sans)">Reference Genome</div>'
  +'<div style="font-size:11px;color:var(--text2)">Choose organism and reference assembly for alignment</div>'
  +'</div></div>'
  +'<div class="card">'
  +'<div class="card-title">Selected Dataset</div>'
  +'<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">'
  +'<span class="tag" style="background:'+SEQ_B[ds.seqType]+';color:'+c+'">'+ds.seqType+'</span>'
  +'<span style="font-size:13px;font-weight:600">'+h(ds.title)+'</span>'
  +'<span style="font-size:11px;color:var(--text2)">'+h(ds.organism)+'</span>'
  +'</div></div>'
  +'<div class="card">'
  +'<div class="card-title">Organism</div>'
  +'<div class="genome-org-tabs">'
  +orgs.map(org=>'<button class="genome-org-tab '+(S.selectedGenomeOrg===org?'active':'')+'" onclick="set({selectedGenomeOrg:\''+org+'\',selectedGenomeId:\''+( REFERENCE_GENOMES[org][0]?.id||'')+'\'})" >'+org+'</button>').join('')
  +'</div>'
  +'<div class="card-title" style="margin-top:16px">Assembly / Build</div>'
  +'<div class="genome-grid">'
  +curGenomes.map(g=>'<div class="genome-card '+(S.selectedGenomeId===g.id?'active':'')+'" onclick="set({selectedGenomeId:\''+g.id+'\'})">'
    +'<div class="genome-card-id">'+g.label+'</div>'
    +'<div class="genome-card-desc">'+g.desc+'</div>'
    +(S.selectedGenomeId===g.id?'<div style="margin-top:6px;font-size:9px;color:var(--cyan)">✓ Selected</div>':'')
    +'</div>').join('')
  +'</div>'
  +'</div>'
  +'<div class="card">'
  +'<div style="font-size:11px;color:var(--text2);line-height:1.8">'
  +'<b style="color:var(--text)">Selected:</b> <span style="color:var(--cyan)">'+( (curGenomes.find(g=>g.id===S.selectedGenomeId)||curGenomes[0])?.label||S.selectedGenomeId)+'</span> — '+( (curGenomes.find(g=>g.id===S.selectedGenomeId)||curGenomes[0])?.desc||'')
  +'<br><span style="color:var(--text3)">The aligner ('+( ds.seqType==='RNA-seq'?'STAR':ds.seqType==='WGS/WGRS'?'BWA-MEM2':ds.seqType==='ChIP-seq'?'Bowtie2':'Bismark')+') will build a genome index from this assembly + GTF annotation before alignment.</span>'
  +'</div></div>'
  +'<div style="display:flex;gap:10px;justify-content:flex-end">'
  +'<button class="btn-ghost" onclick="set({screen:\'select\'})">Change dataset</button>'
  +'<button class="btn" style="font-size:13px;padding:12px 28px" onclick="set({screen:\'config\'})">Configure Pipeline →</button>'
  +'</div></div>';
}

function renderConfig(){
  const ds=S.selectedDs,c=SEQ_C[ds.seqType],b=SEQ_B[ds.seqType];
  const genome=(REFERENCE_GENOMES[S.selectedGenomeOrg]||[]).find(g=>g.id===S.selectedGenomeId)||{label:S.selectedGenomeId};
  const steps=PIPE_STEPS[ds.seqType]||[];
  return '<div class="page">'
  +'<div style="display:flex;align-items:center;gap:12px;margin-bottom:22px">'
  +'<button class="btn-ghost" onclick="set({screen:\'genome\'})">← Back</button>'
  +'<div><div style="font-size:20px;font-weight:700;font-family:var(--font-sans)">Configure Pipeline</div>'
  +'<div style="font-size:11px;color:var(--text2)">Email notifications · output path · review pipeline steps</div>'
  +'</div></div>'
  +'<div class="card" style="border-left:3px solid '+c+'">'
  +'<div style="font-size:9px;color:var(--text3);margin-bottom:4px;letter-spacing:1px">DATASET</div>'
  +'<div style="font-size:15px;font-weight:700;margin-bottom:10px;font-family:var(--font-sans)">'+h(ds.title)+'</div>'
  +'<div style="display:flex;gap:8px;flex-wrap:wrap">'
  +'<span class="tag" style="background:'+b+';color:'+c+'">'+ds.seqType+'</span>'
  +'<span class="tag" style="background:var(--bg3);color:var(--text3)">'+ds.samples+' samples</span>'
  +'<span class="tag" style="background:var(--bg3);color:var(--text3)">'+ds.accession+'</span>'
  +'<span class="tag" style="background:var(--bg3);color:var(--cyan)">'+genome.label+'</span>'
  +'</div></div>'
  +'<div class="card">'
  +'<div class="card-title">Email Notifications (optional)</div>'
  +'<div class="g2" style="margin-bottom:12px">'
  +'<div><label style="font-size:10px;color:var(--text2);display:block;margin-bottom:5px">Email address</label><input class="inp" type="email" id="cfg-email" value="'+h(S.cfg.email)+'" placeholder="you@example.com"/></div>'
  +'<div><label style="font-size:10px;color:var(--text2);display:block;margin-bottom:5px">Notify address</label><input class="inp" type="email" id="cfg-notify" value="'+h(S.cfg.notifyEmail)+'" placeholder="same or different"/></div>'
  +'</div>'
  +'<div style="font-size:10px;color:var(--text3);padding:8px 12px;background:var(--bg3);border-radius:6px">ℹ After pipeline completes, a mailto: link will open your email client with a pre-filled notification. For automated SMTP delivery, configure a backend endpoint.</div>'
  +'</div>'
  +'<div class="card">'
  +'<div class="card-title">Output Directory</div>'
  +'<input class="inp" id="cfg-outdir" value="'+h(S.cfg.outDir)+'" placeholder="~/NGS_Results/'+h(ds.accession)+'_'+new Date().toISOString().slice(0,10)+' (auto-created if blank)"/>'
  +'<div style="font-size:10px;color:var(--text3);margin-top:8px">All files downloadable from Results page. Results directory will contain: fastqc_report/, multiqc_report.html, results.csv, report.html</div>'
  +'</div>'
  +'<div class="card">'
  +'<div class="card-title">Pipeline Preview — '+h(ds.seqType)+' ('+steps.length+' steps)</div>'
  +'<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">'
  +steps.map((s,i)=>'<div style="padding:9px 12px;background:var(--bg3);border-radius:7px;border-left:2px solid '+c+'"><div style="font-size:10px;font-weight:700;color:'+c+';margin-bottom:2px">'+(i+1)+'. '+s.name.split('—')[0].trim()+'</div><div style="font-size:9px;color:var(--text3)">'+s.tool+' → '+s.out+'</div></div>').join('')
  +'</div></div>'
  +'<div style="display:flex;gap:10px;justify-content:flex-end">'
  +'<button class="btn-ghost" onclick="set({screen:\'genome\'})">Change genome</button>'
  +'<button class="btn" style="font-size:13px;padding:12px 32px" onclick="saveCfgRun()">▶ Run Pipeline</button>'
  +'</div></div>';
}

function saveCfgRun(){
  const v=id=>document.getElementById(id)?.value||'';
  S.cfg={email:v('cfg-email'),notifyEmail:v('cfg-notify'),outDir:v('cfg-outdir')};
  runPipeline();
}

function renderPipeline(){
  const ds=S.selectedDs,steps=PIPE_STEPS[ds?.seqType||'RNA-seq'],c=SEQ_C[ds?.seqType]||'var(--cyan)';
  const prog=S.pipeProgress||0;
  const genome=(REFERENCE_GENOMES[S.selectedGenomeOrg]||[]).find(g=>g.id===S.selectedGenomeId)||{label:S.selectedGenomeId};
  return '<div class="page">'
  +'<div style="margin-bottom:6px">'
  +'<div style="font-size:22px;font-weight:800;letter-spacing:-1px;font-family:var(--font-sans)">▶ Running '+h(ds?.seqType)+' Pipeline</div>'
  +'<div style="font-size:11px;color:var(--text2)">'+h(ds?.title)+' · '+genome.label+' · '+h(ds?.condition)+'</div>'
  +'</div>'
  +'<div style="margin-bottom:20px">'
  +'<div style="display:flex;justify-content:space-between;font-size:10px;color:var(--text3);margin-bottom:5px"><span>Overall Progress</span><span style="color:'+(prog===100?'var(--cyan)':'var(--text2)')+'">'+prog+'%</span></div>'
  +'<div class="prog-bar"><div class="prog-fill" style="width:'+prog+'%"></div></div>'
  +'</div>'
  +'<div style="display:grid;grid-template-columns:1fr 1.2fr;gap:16px;align-items:start">'
  // Left: pipeline visual
  +'<div>'
  +'<div class="card" style="padding:16px 18px">'
  +'<div class="card-title">Pipeline Steps</div>'
  +'<div class="pipe-track">'
  +steps.map((s,i)=>{
    const done=(i<S.pipeStep)||S.pipeDone;const active=i===S.pipeStep&&!S.pipeDone;
    return '<div class="pipe-stage '+(done?'done-stage':active?'active-stage':'')+'">'
      +'<div class="pipe-node '+(done?'done':active?'active':'pending')+'">'+(done?'✓':i+1)+'</div>'
      +'<div>'
      +'<div class="pipe-stage-name '+(done?'done-name':active?'active-name':'')+'" style="cursor:'+(active?'default':'pointer')+'" onclick="set({expandedStep:'+(active||done?i:-1)+'})">'+s.name+(active?' <span class="pulse" style="color:var(--gold);font-size:9px;margin-left:6px">running...</span>':'')+'</div>'
      +'<div class="pipe-stage-detail">'+s.tool+'</div>'
      +(done?'<div class="pipe-stage-out done-out">→ '+s.out+'</div>':'')
      +(S.expandedStep===i?'<div class="step-explain">'+s.explain+'</div>':'')
      +'</div></div>';
  }).join('')
  +'</div></div>'
  +(S.activeStepExplain&&!S.pipeDone?'<div class="card" style="border-left:3px solid var(--gold);padding:14px 16px"><div style="font-size:9px;color:var(--gold);letter-spacing:1.5px;margin-bottom:6px">● CURRENT STEP</div><div style="font-size:11px;color:var(--text2);line-height:1.8">'+S.activeStepExplain+'</div></div>':'')
  +'</div>'
  // Right: log
  +'<div class="log-wrap">'
  +'<div class="log-head"><div class="dot dot-cyan"></div><span>PIPELINE LOG</span><span style="margin-left:auto">'+new Date().toLocaleTimeString()+'</span></div>'
  +'<div class="log-body" id="pipelog">'
  +S.pipeLog.map(l=>'<div class="'+ ({s:'ls',i:'li',d:'ld',w:'lw',e:'le',p:'lp'}[l.type]||'li')+'"><span class="lt">'+l.t+'</span>'+h(l.msg)+'</div>').join('')
  +(!S.pipeDone?'<span class="ls pulse">▌</span>':'')
  +'</div></div>'
  +'</div>'
  +(S.pipeDone?'<div style="text-align:center;margin-top:26px"><button class="btn" style="font-size:13px;padding:12px 40px;box-shadow:0 4px 28px rgba(0,200,240,.3)" onclick="set({screen:\'results\',resTab:\'overview\'})">View Results →</button></div>':'')
  +'</div>';
}

// ─── RESULTS ────────────────────────────────
function renderResults(){
  const ds=S.selectedDs,st=S.stats,bio=S.bio,fqc=S.fastqc,mqc=S.multiqc;
  if(!st||!ds)return '<div class="page"><div style="padding:60px;color:var(--text2)">No results yet.</div></div>';
  const c=SEQ_C[ds.seqType],b=SEQ_B[ds.seqType];
  const isRNA=ds.seqType==='RNA-seq',isWGS=ds.seqType==='WGS/WGRS',isChIP=ds.seqType==='ChIP-seq',isBis=ds.seqType==='Bisulfite-seq';

  const metrics=isRNA?[
    {l:'Genes Detected',v:st.genesDetected?.toLocaleString(),c},{l:'UP-regulated',v:st.degUp,c:'var(--red)'},{l:'DOWN-regulated',v:st.degDown,c:'var(--cyan)'},{l:'Mapping Rate',v:st.mappingRate,c:'var(--green)'},{l:'Q30 Bases',v:st.q30,c:'var(--gold)'},{l:'Total Reads',v:st.totalReads,c}
  ]:isWGS?[
    {l:'SNVs Called',v:st.snvCount?.toLocaleString(),c},{l:'InDels',v:st.indelCount?.toLocaleString(),c:'var(--cyan)'},{l:'Pathogenic Vars',v:st.pathogenic,c:'var(--red)'},{l:'Coverage',v:st.coverage,c:'var(--gold)'},{l:'Q30 Bases',v:st.q30,c:'var(--green)'},{l:'Mapping Rate',v:st.mappingRate,c}
  ]:isChIP?[
    {l:'Peaks Found',v:st.peaksFound?.toLocaleString(),c},{l:'FRiP Score',v:st.frip,c:'var(--cyan)'},{l:'Enrichment',v:st.enrichmentScore,c:'var(--gold)'},{l:'Total Reads',v:st.totalReads,c:'var(--green)'},{l:'Mapping Rate',v:st.mappingRate,c},{l:'Top Motif',v:(bio?.topMotifs||[])[0]?.slice(0,12)||'—',c:'var(--purple)'}
  ]:[
    {l:'DMRs Found',v:st.dmrCount?.toLocaleString(),c},{l:'Hyper-meth',v:st.hyperMeth?.toLocaleString(),c:'var(--red)'},{l:'Hypo-meth',v:st.hypoMeth?.toLocaleString(),c:'var(--cyan)'},{l:'Bisulfite Conv.',v:st.bisulfiteConv,c:'var(--green)'},{l:'CpG Coverage',v:st.cpgCoverage,c:'var(--gold)'},{l:'Mapping Rate',v:st.mappingRate,c}
  ];

  // OVERVIEW TAB
  const overviewContent='<div class="g3" style="margin-bottom:16px">'+metrics.map(m=>'<div class="ov-metric"><div class="ov-metric-val" style="color:'+m.c+'">'+(m.v||'—')+'</div><div class="ov-metric-label">'+m.l+'</div></div>').join('')+'</div>'
  +(bio?'<div class="g2">'
    +(isRNA?'<div class="card"><div class="card-title">Top DEGs</div><table class="qtable"><thead><tr><th>Gene</th><th>Dir</th><th>LFC</th><th>padj</th></tr></thead><tbody>'+(bio.topGenes||[]).map((g,i)=>'<tr><td style="font-weight:700;color:'+(bio.directions?.[i]==='UP'?'var(--red)':'var(--cyan)')+'">'+h(g)+'</td><td><span style="font-size:8.5px;padding:1px 6px;border-radius:3px;background:'+(bio.directions?.[i]==='UP'?'rgba(255,78,106,.15)':'rgba(0,200,240,.15)')+';color:'+(bio.directions?.[i]==='UP'?'var(--red)':'var(--cyan)')+'">'+( bio.directions?.[i]||'')+'</span></td><td>'+(+( bio.lfc?.[i]||0)).toFixed(2)+'</td><td style="color:var(--text3);font-size:10px">'+h(bio.padj?.[i]||'')+'</td></tr>').join('')+'</tbody></table></div>':'')
    +(isWGS?'<div class="card"><div class="card-title">Key Variants</div><table class="qtable"><thead><tr><th>Gene</th><th>Variant</th><th>Significance</th></tr></thead><tbody>'+(bio.topGenes||[]).map((g,i)=>{const s=bio.significance?.[i]||'VUS';const col=s==='Pathogenic'?'var(--red)':s==='VUS'?'var(--gold)':'var(--cyan)';return '<tr><td style="font-weight:700;color:'+c+'">'+h(g)+'</td><td style="font-size:10px;color:var(--text2)">'+h(bio.variantType?.[i]||'')+'</td><td><span style="font-size:8px;padding:1px 7px;border-radius:3px;background:rgba(0,0,0,.3);color:'+col+'">'+s+'</span></td></tr>';}).join('')+'</tbody></table></div>':'')
    +(isChIP?'<div class="card"><div class="card-title">Top TF Motifs</div>'+motifBarSVG(bio)+'</div>':'')
    +(isBis?'<div class="card"><div class="card-title">Top DMRs</div>'+methylBarSVG(bio)+'</div>':'')
    +'<div class="card"><div class="card-title">Sample Separation (PCA)</div>'+pcaSVG(ds)+'</div>'
    +'</div>'
  :'<div style="padding:40px;text-align:center;color:var(--text3)" class="pulse">Biological results not available (API error).</div>')
  +(S.interpretation?'<div class="card" style="margin-top:4px"><div class="card-title">AI Biological Interpretation</div><div style="font-size:12px;line-height:2;color:var(--text);white-space:pre-wrap">'+h(S.interpretation)+'</div></div>':'');

  // FASTQC TAB — always render, use fallback if needed
  const fqcData = fqc || createFallbackFastQC(st||{});
  const fastqcContent='<div class="card"><div class="card-title">FastQC Module Summary — '+h(ds.title)+'</div>'
  +'<div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:14px;font-size:11px">'
  +'<span>Total reads: <b style="color:'+c+'">'+( fqcData.summary?.totalReads||st.totalReads||'N/A')+'</b></span>'
  +'<span>Bases: <b>'+( fqcData.summary?.totalBases||'N/A')+'</b></span>'
  +'<span>Poor quality: <b style="color:var(--red)">'+( fqcData.summary?.poorQualReads||'N/A')+'</b></span>'
  +'<span>Flagged: <b style="color:var(--gold)">'+( fqcData.summary?.flaggedPct||'N/A')+'</b></span>'
  +(!fqc?'<span style="padding:2px 8px;background:#1a1000;border:1px solid #3a2800;border-radius:4px;font-size:9px;color:var(--gold)">⚠ Using local fallback data — Groq API unavailable</span>':'')
  +'</div>'
  +'<div class="g3">'+Object.entries(fqcData.modules||{}).map(([mod,status])=>'<div style="display:flex;align-items:center;justify-content:space-between;padding:6px 10px;background:var(--bg3);border-radius:6px">'+statusBadge(status)+'<span style="font-size:9.5px;color:var(--text2);text-align:right">'+mod+'</span></div>').join('')+'</div>'
  +'</div>'
  +'<div class="g2">'
  +'<div class="card"><div class="card-title">Per Base Sequence Quality '+statusBadge(fqcData.modules?.['Per base sequence quality']||'pass')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">Quality score at each position. Whiskers = 10th–90th percentile; box = Q1–Q3; line = median. Aim for median above Q28 (green zone).</div></div>'+perBaseQualSVG(fqcData.perBaseQuality)+'</div>'
  +'<div class="card"><div class="card-title">Per Sequence Quality Scores '+statusBadge(fqcData.modules?.['Per sequence quality scores']||'pass')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">Distribution of mean quality per read. Peak should be at Q30+. Low-quality tail on left indicates poor reads.</div></div>'+perSeqQualSVG(fqcData.perSeqQuality)+'</div>'
  +'<div class="card"><div class="card-title">Per Sequence GC Content '+statusBadge(fqcData.modules?.['Per sequence GC content']||'warn')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">Actual GC (orange) vs theoretical normal distribution (blue dashed). Deviations suggest contamination or library bias.</div></div>'+gcContentSVG(fqcData.gcContent)+'</div>'
  +'<div class="card"><div class="card-title">Sequence Duplication Levels '+statusBadge(fqcData.modules?.['Sequence duplication levels']||'warn')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">High duplication (>50%) may indicate low library complexity or PCR over-amplification. Cyan = unique, gold = low dup, red = high dup.</div></div>'+seqDupSVG(fqcData.duplicationLevels)+'</div>'
  +'<div class="card"><div class="card-title">Adapter Content '+statusBadge(fqcData.modules?.['Adapter content']||'pass')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">% reads containing adapter sequence at each position. Should be near 0% after trimming. Rising curve toward 3\' end is common in short-insert libraries.</div></div>'+adapterContentSVG(fqcData.adapterContent)+'</div>'
  +'<div class="card"><div class="card-title">Per Base N Content '+statusBadge(fqcData.modules?.['Per base N content']||'pass')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">% uncalled bases (N) per position. Should be near 0% throughout. High N at 5\' indicates sequencer calibration issues.</div></div>'+perBaseNSVG(fqcData.perBaseN)+'</div>'
  +'<div class="card"><div class="card-title">Sequence Length Distribution '+statusBadge(fqcData.modules?.['Sequence length distribution']||'pass')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">Distribution of read lengths. Should be a tight peak at the expected read length. Width after trimming indicates quality-driven trimming variation.</div></div>'+seqLengthSVG(fqcData.seqLengthDist)+'</div>'
  +'<div class="card"><div class="card-title">Overrepresented Sequences '+statusBadge(fqcData.modules?.['Overrepresented sequences']||'warn')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">Sequences making up >0.1% of total reads. Common hits include adapter dimers, rRNA, and mitochondrial sequences.</div></div>'
  +(fqcData.overrepresentedSeqs?.length?'<table class="qtable"><thead><tr><th>Sequence</th><th>Count</th><th>%</th><th>Source</th></tr></thead><tbody>'+fqcData.overrepresentedSeqs.map(s=>'<tr><td><code style="font-size:9px;color:var(--text3)">'+h((s.seq||'').slice(0,24))+'…</code></td><td>'+( s.count||0).toLocaleString()+'</td><td>'+s.pct+'%</td><td style="color:var(--gold)">'+h(s.source)+'</td></tr>').join('')+'</tbody></table>':'<div style="font-size:11px;color:var(--text3)">No overrepresented sequences detected ✓</div>')
  +'</div>'
  +'</div>'
  +(fqcData.kmerContent?.length?'<div class="card" style="margin-top:4px"><div class="card-title">Kmer Content '+statusBadge(fqcData.modules?.['Kmer content']||'pass')+'<div style="font-size:9px;color:var(--text3);font-weight:400;margin-top:3px;text-transform:none;letter-spacing:0">Enriched 7-mers that appear more often than expected at certain positions — may indicate primer bias or secondary structure.</div></div><table class="qtable"><thead><tr><th>Kmer</th><th>Count%</th><th>Obs/Exp Ratio</th><th>Interpretation</th></tr></thead><tbody>'+fqcData.kmerContent.map(k=>'<tr><td><code style="color:'+c+'">'+h(k.kmer)+'</code></td><td>'+k.pct+'%</td><td style="color:'+(k.ratio>1.5?'var(--red)':'var(--cyan)')+'">'+( k.ratio||0).toFixed(2)+'</td><td style="font-size:9.5px;color:var(--text3)">'+(k.ratio>2?'⚠ Enriched — possible adapter/primer artifact':k.ratio>1.2?'Slightly elevated':'Normal range')+'</td></tr>').join('')+'</tbody></table></div>':'')
  +'<div style="margin-top:14px;display:flex;gap:8px;flex-wrap:wrap"><button class="btn-dl" onclick="generateFastQCTxt()">⬇ FastQC Report (.txt)</button><button class="btn-dl" onclick="generateHTMLReport()">⬇ Full HTML Report</button></div>';

  // MULTIQC TAB — always render, use fallback if needed
  const mqcData = mqc || createFallbackMultiQC(ds, st||{});
  const multiqcContent='<div class="card"><div class="card-title">MultiQC — All Samples ('+(mqcData.sampleStats||[]).length+')</div>'
  +(!mqc?'<div style="margin-bottom:10px;padding:6px 12px;background:#1a1000;border:1px solid #3a2800;border-radius:6px;font-size:9.5px;color:var(--gold)">⚠ API unavailable — showing locally-generated fallback data</div>':'')
  +'<div style="overflow-x:auto"><table class="qtable"><thead><tr><th>Sample</th><th>Reads</th><th>Mapped</th><th>Map%</th><th>Dup%</th><th>Q30</th><th>GC%</th><th>Status</th></tr></thead><tbody>'+(mqcData.sampleStats||[]).map(s=>'<tr><td style="color:'+c+';font-weight:700">'+h(s.name)+'</td><td>'+h(s.totalReads)+'</td><td>'+h(s.mapped)+'</td><td>'+h(s.mappingRate)+'</td><td>'+h(s.duplicates)+'</td><td>'+h(s.q30)+'</td><td>'+h(s.gcContent)+'</td><td>'+statusBadge(s.status||'pass')+'</td></tr>').join('')+'</tbody></table></div>'
  +'</div>'
  +'<div class="g2"><div class="card"><div class="card-title">Alignment Statistics<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Breakdown of how reads mapped to the reference genome</div></div>'+Object.entries(mqcData.alignmentStats||{}).map(([k,v])=>'<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--border);font-size:11px"><span style="color:var(--text2)">'+k.replace(/([A-Z])/g,' $1').trim()+'</span><span style="color:'+c+';font-weight:700">'+v+'</span></div>').join('')+'</div>'
  +'<div class="card"><div class="card-title">Trimming Statistics<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Read processing metrics from Trimmomatic/Cutadapt</div></div>'+Object.entries(mqcData.trimStats||{}).map(([k,v])=>'<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--border);font-size:11px"><span style="color:var(--text2)">'+k.replace(/([A-Z])/g,' $1').trim()+'</span><span style="color:var(--gold);font-weight:700">'+v+'</span></div>').join('')+'</div>'
  +(mqcData.insertSize?.length?'<div class="card"><div class="card-title">Insert Size Distribution<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Distribution of fragment sizes from paired-end reads. Normal peak at 150–400 bp indicates good library prep.</div></div>'+insertSizeSVG(mqcData.insertSize)+'</div>':'')
  +(mqcData.coverage?.length?'<div class="card"><div class="card-title">Coverage per Chromosome<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Mean read depth across each chromosome. Even coverage is expected for WGS; enrichment visible in ChIP-seq.</div></div>'+coverageSVG(mqcData.coverage)+'</div>':'')
  +'</div>'
  +'<div style="margin-top:12px"><button class="btn-dl" onclick="generateAlignmentTSV()">⬇ MultiQC Stats (.tsv)</button></div>';

  // BIO RESULTS TAB (similar to overview but more detailed)
  let bioContent='';
  if(!bio){bioContent='<div style="padding:60px;text-align:center;color:var(--text3)" class="pulse">Biological results not available (API error).</div>';}
  else if(isRNA){
    bioContent='<div class="g3" style="margin-bottom:16px">'+metrics.map(m=>'<div class="met" style="border-color:'+m.c+'"><div class="met-label">'+m.l+'</div><div class="met-val" style="color:'+m.c+'">'+( m.v||'—')+'</div></div>').join('')+'</div>'
    +'<div class="g2">'
    +'<div class="card"><div class="card-title">Top DEGs — '+h(ds.condition)+'<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Differentially expressed genes ranked by statistical significance (padj) and effect size (|LFC|)</div></div><table class="qtable"><thead><tr><th>Gene</th><th>Dir</th><th>log₂FC</th><th>padj</th><th>BaseMean</th><th>Description</th></tr></thead><tbody>'+(bio.topGenes||[]).map((g,i)=>'<tr><td style="font-weight:700;color:'+(bio.directions?.[i]==='UP'?'var(--red)':'var(--cyan)')+'">'+h(g)+'</td><td><span style="font-size:8.5px;padding:1px 6px;border-radius:3px;background:'+(bio.directions?.[i]==='UP'?'rgba(255,78,106,.15)':'rgba(0,200,240,.15)')+';color:'+(bio.directions?.[i]==='UP'?'var(--red)':'var(--cyan)')+'">'+( bio.directions?.[i]||'')+'</span></td><td style="color:var(--text)">'+(+( bio.lfc?.[i]||0)).toFixed(2)+'</td><td style="color:var(--text3);font-size:10px">'+h(bio.padj?.[i]||'')+'</td><td>'+(( bio.baseMean?.[i]||0).toLocaleString())+'</td><td style="font-size:9.5px;color:var(--text3);max-width:160px">'+h((bio.geneDesc?.[i]||'').slice(0,80))+'...</td></tr>').join('')+'</tbody></table></div>'
    +'<div class="card"><div class="card-title">Enriched Pathways<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">KEGG/Reactome pathways enriched in differentially expressed gene sets (GSEA pre-ranked)</div></div>'+(bio.pathways||[]).map((pw,i)=>'<div style="padding:7px 0;border-bottom:1px solid var(--border);font-size:11px;display:flex;align-items:center;gap:8px"><span style="color:'+c+';font-size:10px;font-weight:700">'+(i+1)+'.</span>'+h(pw)+'</div>').join('')+'</div>'
    +'</div>'
    +'<div class="g2" style="margin-top:4px">'
    +'<div class="card"><div class="card-title">Volcano Plot<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Each dot = one gene. X-axis: fold change; Y-axis: significance. Red = significantly upregulated; cyan = significantly downregulated; grey = not significant.</div></div>'+volcanoSVG(bio,st)+'</div>'
    +'<div class="card"><div class="card-title">PCA — Sample Separation<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Principal component analysis of normalised gene expression. Well-separated clusters indicate strong transcriptomic difference between conditions.</div></div>'+pcaSVG(ds)+'</div>'
    +'<div class="card" style="grid-column:1/-1"><div class="card-title">Expression Heatmap — Top DEGs<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Z-score normalised expression of top DEGs. Red = high expression; blue = low expression. Columns D1–D5: disease; N1–N5: normal control.</div></div>'+heatmapSVG(bio)+'</div>'
    +'</div>';
  } else if(isWGS){
    bioContent='<div class="g3" style="margin-bottom:16px">'+metrics.map(m=>'<div class="met" style="border-color:'+m.c+'"><div class="met-label">'+m.l+'</div><div class="met-val" style="color:'+m.c+'">'+( m.v||'—')+'</div></div>').join('')+'</div>'
    +'<div class="card"><div class="card-title">Key Variants — '+h(ds.condition)+'<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Clinically significant and candidate variants identified by GATK HaplotypeCaller and annotated by SnpEff. Sorted by clinical significance.</div></div>'
    +'<table class="qtable"><thead><tr><th>Gene</th><th>Chr</th><th>Variant</th><th>Clinical Significance</th><th>Allele Freq</th><th>Zygosity</th><th>Gene Role</th></tr></thead><tbody>'+(bio.topGenes||[]).map((g,i)=>{const s=bio.significance?.[i]||'VUS';const col=s==='Pathogenic'?'var(--red)':s==='Likely pathogenic'?'var(--gold)':s==='VUS'?'var(--purple)':'var(--cyan)';return '<tr><td style="font-weight:700;color:'+c+'">'+h(g)+'</td><td style="color:var(--text3)">'+h(bio.chr?.[i]||'')+'</td><td style="font-size:10px;color:var(--text2)">'+h(bio.variantType?.[i]||'')+'</td><td><span style="font-size:8.5px;padding:2px 7px;border-radius:3px;background:rgba(0,0,0,.3);color:'+col+'">'+s+'</span></td><td>'+h(bio.af?.[i]||'')+'</td><td style="color:var(--text3)">'+h(bio.zygosity?.[i]||'')+'</td><td style="font-size:10px;color:var(--text2)">'+h((bio.geneRole?.[i]||'').slice(0,60))+'...</td></tr>';}).join('')+'</tbody></table></div>'
    +'<div class="g2" style="margin-top:4px"><div class="card"><div class="card-title">PCA — Sample Clustering</div>'+pcaSVG(ds)+'</div><div class="card"><div class="card-title">Alignment Quality</div>'+qualBarSVG(st.q30,st.mappingRate)+'</div></div>';
  } else if(isChIP){
    bioContent='<div class="g3" style="margin-bottom:16px">'+metrics.map(m=>'<div class="met" style="border-color:'+m.c+'"><div class="met-label">'+m.l+'</div><div class="met-val" style="color:'+m.c+'">'+( m.v||'—')+'</div></div>').join('')+'</div>'
    +'<div class="g2">'
    +'<div class="card"><div class="card-title">TF Motif Enrichment — '+h(ds.condition)+'<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Top transcription factor binding motifs enriched in peak regions by HOMER. Bar = % targets containing motif.</div></div>'+motifBarSVG(bio)+'</div>'
    +'<div class="card"><div class="card-title">Peak Annotation<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Genomic feature distribution of called peaks. High promoter enrichment expected for TF ChIP.</div></div>'+Object.entries(bio.peakAnnotation||{}).map(([k,v])=>'<div style="display:flex;justify-content:space-between;padding:7px 0;border-bottom:1px solid var(--border);font-size:11px"><span style="color:var(--text2)">'+k+'</span><span style="color:'+c+';font-weight:700">'+v+'</span></div>').join('')+'</div>'
    +'<div class="card"><div class="card-title">PCA — Sample Clustering</div>'+pcaSVG(ds)+'</div>'
    +'<div class="card"><div class="card-title">Alignment QC</div>'+qualBarSVG(st.q30,st.mappingRate)+'</div>'
    +'</div>';
  } else {
    bioContent='<div class="g3" style="margin-bottom:16px">'+metrics.map(m=>'<div class="met" style="border-color:'+m.c+'"><div class="met-label">'+m.l+'</div><div class="met-val" style="color:'+m.c+'">'+( m.v||'—')+'</div></div>').join('')+'</div>'
    +'<div class="g2">'
    +'<div class="card"><div class="card-title">DMR Δβ Values — '+h(ds.condition)+'<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Δβ = difference in methylation proportion between conditions. Red = hypermethylated (gene silencing); cyan = hypomethylated (activation).</div></div>'+methylBarSVG(bio)+'</div>'
    +'<div class="card"><div class="card-title">DMR Details<div style="font-size:9px;color:var(--text3);font-weight:400;text-transform:none;letter-spacing:0">Differentially methylated regions with CpG context and island annotation from DSS/annotatr.</div></div>'
    +'<table class="qtable"><thead><tr><th>Gene</th><th>Direction</th><th>Δβ</th><th>Context</th><th>CpG Annotation</th></tr></thead><tbody>'+(bio.topGenes||[]).map((g,i)=>'<tr><td style="font-weight:700;color:'+(bio.directions?.[i]==='Hyper'?'var(--red)':'var(--cyan)')+'">'+h(g)+'</td><td>'+( bio.directions?.[i]||'')+'</td><td>'+(+( bio.deltaBeta?.[i]||0)).toFixed(3)+'</td><td style="font-size:10px;color:var(--text3)">'+h(bio.context?.[i]||'')+'</td><td style="font-size:10px">'+h(bio.island?.[i]||'')+'</td></tr>').join('')+'</tbody></table>'
    +'</div>'
    +'<div class="card"><div class="card-title">PCA — Sample Clustering</div>'+pcaSVG(ds)+'</div>'
    +'<div class="card"><div class="card-title">Alignment QC</div>'+qualBarSVG(st.q30,st.mappingRate)+'</div>'
    +'</div>';
  }

  // INTERPRETATION TAB
  const interpContent='<div class="card"><div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:14px"><div class="card-title" style="margin:0">AI Biological Interpretation — '+h(ds.condition)+'</div>'+(S.interpretation?'<button class="btn-dl" onclick="downloadFile(S.interpretation,\''+ds.accession+'_interpretation.txt\')">⬇ Download</button>':'')+'</div>'+(S.interpretation?'<div style="font-size:12px;line-height:2.1;color:var(--text);white-space:pre-wrap">'+h(S.interpretation)+'</div>':'<div style="color:var(--text3)" class="pulse">Generating interpretation...</div>')+'<div style="margin-top:16px;padding:10px 14px;background:var(--bg3);border-radius:7px;font-size:10px;color:var(--text3)">Generated by Groq ('+S.selectedModel+') · '+new Date().toLocaleString()+' · Dataset: '+h(ds.accession)+'</div></div>';

  // CHAT TAB
  const chatContent='<div class="card"><div class="card-title">Ask AI about your results</div>'
  +'<div id="chat-box" style="max-height:400px;overflow-y:auto;margin-bottom:14px;display:flex;flex-direction:column;gap:10px">'
  +S.chatHistory.map(hh=>'<div style="display:flex;justify-content:flex-end;margin-bottom:2px"><div class="chat-u">'+h(hh.user)+'</div></div><div style="display:flex"><div class="chat-a">'+h(hh.ai)+'</div></div>').join('')
  +(S.chatLoading?'<div style="display:flex"><div class="chat-a pulse">Thinking...</div></div>':'')
  +'</div>'
  +'<div style="display:flex;gap:8px;margin-bottom:10px">'
  +'<input class="inp" id="chat-inp" value="'+h(S.chatInput)+'" placeholder="Ask about pathways, drug targets, follow-up experiments, clinical implications..."/>'
  +'<button class="btn" style="flex-shrink:0;padding:9px 18px" onclick="S.chatInput=document.getElementById(\'chat-inp\')?.value||\'\';;sendChat()" '+(S.chatLoading?'disabled':'')+'>Send</button>'
  +'</div>'
  +'<div style="display:flex;gap:6px;flex-wrap:wrap">'
  +['What pathways are dysregulated?','Which drugs target these genes?','Clinical implications?','Recommended follow-up experiments?','Statistical robustness?','Compare to published literature?'].map(q=>'<button class="btn-sm" onclick="document.getElementById(\'chat-inp\').value=\''+q+'\'">'+q+'</button>').join('')
  +'</div></div>';

  // DOWNLOADS TAB
  const dlContent='<div class="card"><div class="card-title">Download All Results</div>'
  +'<div class="g2" style="margin-bottom:16px">'
  +[['results.csv','Main analysis results (DEGs/variants/motifs/DMRs)','generateResultsCSV()'],['alignment_stats.tsv','MultiQC sample alignment statistics','generateAlignmentTSV()'],['fastqc_report.txt','FastQC quality control report text','generateFastQCTxt()'],['report.html','Full interactive HTML analysis report','generateHTMLReport()']].map(([fn,desc,fn2])=>'<div style="background:var(--bg3);border:1px solid var(--border);border-radius:10px;padding:16px"><div style="font-weight:700;color:'+c+';font-size:12px;margin-bottom:5px">📄 '+ds.accession+'_'+fn+'</div><div style="font-size:10px;color:var(--text3);margin-bottom:12px">'+desc+'</div><button class="btn-dl" onclick="'+fn2+'">⬇ Download</button></div>').join('')
  +'</div>'
  +'<div style="background:var(--bg3);border:1px solid var(--border);border-radius:10px;padding:16px;margin-bottom:14px"><div style="font-weight:700;color:var(--text);font-size:12px;margin-bottom:5px">📦 Download All 4 Files</div><div style="font-size:10px;color:var(--text3);margin-bottom:12px">Downloads results.csv, alignment_stats.tsv, fastqc_report.txt, and report.html sequentially</div><button class="btn" onclick="generateAllFiles()">⬇ Download All</button></div>'
  +(S.emailSent&&S.mailtoLink?'<div style="background:var(--cbg);border:1px solid #0a3040;border-radius:10px;padding:16px;margin-bottom:14px"><div style="font-weight:700;color:var(--cyan);font-size:12px;margin-bottom:5px">📧 Email Notification Ready</div><div style="font-size:10px;color:var(--text2);margin-bottom:12px">Prepared for: '+h(S.cfg.notifyEmail||S.cfg.email)+'</div><a href="'+S.mailtoLink+'" target="_blank"><button class="btn-dl">Open in Mail Client</button></a></div>':'')
  +'<div style="padding:12px 14px;background:var(--bg3);border-radius:8px;font-size:10px;color:var(--text3)">All files generated locally in your browser. No data transmitted to external servers beyond Groq API calls during analysis.</div>'
  +'</div>';

  const tabs=['overview','fastqc','multiqc','results','interpretation','chat','downloads'];
  const tabLabels={overview:'Overview',fastqc:'FastQC',multiqc:'MultiQC',results:'Bio Results',interpretation:'Interpretation',chat:'AI Chat',downloads:'Downloads'};
  const tabContent={overview:overviewContent,fastqc:fastqcContent,multiqc:multiqcContent,results:bioContent,interpretation:interpContent,chat:chatContent,downloads:dlContent};

  return '<div class="page">'
  +'<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px">'
  +'<div><div style="font-size:22px;font-weight:800;font-family:var(--font-sans)">Analysis Complete ✓</div>'
  +'<div style="font-size:11px;color:var(--text2)">'+h(ds.title)+' · '+h(ds.accession)+' · '+h(ds.condition)+'</div></div>'
  +'<div style="display:flex;gap:8px;align-items:center"><span class="tag" style="background:'+b+';color:'+c+'">'+ds.seqType+'</span><button class="btn-ghost" onclick="reset()">New analysis</button></div>'
  +'</div>'
  +'<div class="tab-row">'+tabs.map(t=>'<button class="tab-btn '+(S.resTab===t?'active':'')+'" onclick="set({resTab:\''+t+'\'})">'+tabLabels[t]+'</button>').join('')+'</div>'
  +(tabContent[S.resTab]||'')
  +'</div>';
}

// ═══════════════════════════════════════
//  NAV + RENDER
// ═══════════════════════════════════════
function renderNav(){
  const steps=[['home','Input'],['select','Datasets'],['genome','Genome'],['config','Config'],['pipeline','Pipeline'],['results','Results']];
  return steps.map(([id,lb])=>{
    const order=steps.findIndex(s=>s[0]===id);
    const cur=steps.findIndex(s=>s[0]===S.screen);
    const dis=(id==='select'&&!S.searchResults.length)||(id==='genome'&&!S.selectedDs)||(id==='config'&&!S.selectedDs)||(id==='pipeline'&&!S.selectedDs)||(id==='results'&&!S.pipeDone);
    const act=S.screen===id,done=cur>order&&id!=='home';
    return '<button class="nav-step '+(act?'active':'')+(done?' done':'')+'" onclick="'+(dis||act?'':' set({screen:\''+id+'\'})')+'" '+(dis&&!act?'disabled':'')+' >'+(done&&!act?'✓ ':'')+lb+'</button>';
  }).join('');
}

function render(){
  const app=document.getElementById('app');
  let body='';
  if(S.screen==='home') body=renderHome();
  else if(S.screen==='searching') body='<div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;padding:100px 0"><div class="spin" style="font-size:52px;color:var(--cyan)">⟳</div><div style="font-size:18px;font-weight:700;font-family:var(--font-sans)">Querying Groq...</div><div style="font-size:11px;color:var(--text3);letter-spacing:1.5px">GEO · NCBI SRA · ENA · ArrayExpress</div><div style="font-size:10px;color:var(--text3)">Model: '+S.selectedModel+'</div></div>';
  else if(S.screen==='select') body=renderSelect();
  else if(S.screen==='genome') body=renderGenome();
  else if(S.screen==='config') body=renderConfig();
  else if(S.screen==='pipeline') body=renderPipeline();
  else if(S.screen==='results') body=renderResults();

  app.innerHTML='<nav class="nav">'
    +'<div class="nav-logo" onclick="reset()"><div class="logo-hex">N</div><div><div class="nav-brand">NGS<span>Platform</span></div><div style="font-size:7.5px;color:var(--text3);letter-spacing:2.5px">GROQ POWERED</div></div></div>'
    +'<div class="nav-steps">'+renderNav()+'</div>'
    +'<div class="nav-right"><span style="font-size:9.5px;color:var(--text3)">'+S.selectedModel.split('-').slice(0,3).join('-')+'</span><div class="dot '+(S.groqKey?'dot-cyan':'dot-dim')+'"></div></div>'
    +'</nav>'
    +'<div style="flex:1;display:flex;flex-direction:column">'+body+'</div>';

  // Bind inputs
  const gk=document.getElementById('groq-key-inp');
  if(gk){gk.oninput=e=>{S.groqKey=e.target.value;};}
  const ms=document.getElementById('model-sel');
  if(ms){ms.onchange=e=>{S.selectedModel=e.target.value;};}
  const qi=document.getElementById('query-inp');
  if(qi){qi.oninput=e=>S.queryInput=e.target.value;qi.onkeydown=e=>{if(e.key==='Enter'){S.queryInput=qi.value;doSearch();}};}
  const di=document.getElementById('dir-inp');
  if(di){di.oninput=e=>S.dirInput=e.target.value;di.onkeydown=e=>{if(e.key==='Enter'){S.dirInput=di.value;doSearch();}};}
  const ci=document.getElementById('chat-inp');
  if(ci){ci.oninput=e=>S.chatInput=e.target.value;ci.onkeydown=e=>{if(e.key==='Enter'&&!e.shiftKey){S.chatInput=ci.value;sendChat();}};
    const cb=document.getElementById('chat-box');if(cb)cb.scrollTop=cb.scrollHeight;}
  const pl=document.getElementById('pipelog');if(pl)pl.scrollTop=pl.scrollHeight;

  // Drop zone
  const dz=document.getElementById('drop-z');
  if(dz){
    dz.ondragover=e=>{e.preventDefault();dz.classList.add('drag');};
    dz.ondragleave=()=>dz.classList.remove('drag');
    dz.ondrop=e=>{e.preventDefault();dz.classList.remove('drag');handleFiles(e.dataTransfer.files);};
  }
}

async function sendChat(){
  if(!S.chatInput.trim()||S.chatLoading)return;
  const msg=S.chatInput.trim();S.chatInput='';S.chatLoading=true;
  S.chatHistory=[...S.chatHistory,{user:msg,ai:'...'}];render();
  try{const ans=await chatWithAI(S.chatHistory.slice(0,-1),msg,S.selectedDs,S.bio);S.chatHistory[S.chatHistory.length-1].ai=ans;}
  catch(e){S.chatHistory[S.chatHistory.length-1].ai='Error: '+e.message;}
  S.chatLoading=false;render();
}

function handleFiles(files){S.uploadedFiles=Array.from(files);render();}
function selectDs(ds){set({selectedDs:ds});}

render();
</script>
</body>
</html>