File size: 112,547 Bytes
3f792e8
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb974bb
 
 
 
 
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
 
3e27995
 
 
 
 
 
 
 
 
 
 
3f792e8
 
3e27995
 
 
3f792e8
3e27995
 
 
 
 
 
 
 
3f792e8
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb974bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
3e27995
 
 
 
 
 
 
3f792e8
 
 
 
 
 
3e27995
3f792e8
 
3e27995
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb974bb
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
 
 
 
 
 
 
 
 
3f792e8
 
 
3e27995
3f792e8
3e27995
3f792e8
 
 
3e27995
3f792e8
 
3e27995
3f792e8
 
 
 
 
 
 
3e27995
3f792e8
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
 
 
 
 
3f792e8
 
 
 
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
3e27995
 
3f792e8
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
3e27995
 
3f792e8
3e27995
 
 
 
 
 
 
 
3f792e8
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
3e27995
 
 
 
 
 
 
 
 
 
3f792e8
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
 
 
3e27995
 
 
 
 
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
 
 
 
3f792e8
 
3e27995
 
 
 
 
3f792e8
 
 
 
 
3e27995
 
 
 
 
3f792e8
3e27995
 
 
 
 
 
 
 
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
3e27995
3f792e8
 
3e27995
3f792e8
 
3e27995
3f792e8
 
 
3e27995
 
 
 
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
3e27995
3f792e8
 
3e27995
3f792e8
 
 
 
3e27995
3f792e8
 
 
 
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
 
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
3f792e8
 
 
3e27995
3f792e8
 
 
3e27995
3f792e8
 
 
3e27995
3f792e8
 
 
 
 
3e27995
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d2733f
 
 
3e27995
 
 
 
 
0d2733f
 
3e27995
 
 
 
 
 
 
0d2733f
3f792e8
 
 
0d2733f
 
 
 
 
 
 
 
 
 
3f792e8
 
 
 
0d2733f
 
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d2733f
3f792e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d36e8b
 
 
 
3e27995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f792e8
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multilingual Audio Intelligence System</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>
    <style>
        .upload-area {
            border: 2px dashed #cbd5e1;
            transition: all 0.3s ease;
        }
        .upload-area:hover {
            border-color: #3b82f6;
            background-color: #f8fafc;
        }
        .upload-area.dragover {
            border-color: #2563eb;
            background-color: #eff6ff;
        }
        .progress-bar {
            background: linear-gradient(90deg, #3b82f6 0%, #1d4ed8 100%);
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .page-section {
            display: none;
        }
        .page-section.active {
            display: block;
        }
        .loading-spinner {
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        .hero-pattern {
            background-image: radial-gradient(circle at 1px 1px, rgba(59, 130, 246, 0.15) 1px, transparent 0);
            background-size: 20px 20px;
        }
        
        /* Scrollable demo tabs styles */
        .scrollbar-hide {
            -ms-overflow-style: none;
            scrollbar-width: none;
        }
        .scrollbar-hide::-webkit-scrollbar {
            display: none;
        }
        
        .demo-file-option {
            transition: all 0.2s ease;
        }
        
        .demo-file-option:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .demo-file-option.selected {
            border-color: #3b82f6;
            background-color: #eff6ff;
        }
        
        .scroll-indicator {
            transition: all 0.2s ease;
        }
        
        .scroll-indicator.active {
            background-color: #3b82f6;
            transform: scale(1.2);
        }
        
        /* Smooth scrolling for demo files */
        #demo-files-container {
            scroll-snap-type: x mandatory;
        }
        
        .demo-file-option {
            scroll-snap-align: start;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <h1 class="text-2xl font-bold text-gray-900 cursor-pointer" id="home-link">Audio Intelligence System</h1>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="demo-mode-btn" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i class="fas fa-play-circle mr-2"></i>
                        Demo Mode
                    </button>
                    <button id="processing-mode-btn" class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i class="fas fa-cog mr-2"></i>
                        Full Processing
                    </button>
                    <!-- <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                        <!-- <i class="fas fa-circle w-2 h-2 mr-2"></i> -->
                    <!-- <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"> -->
                        <!-- <i class="fas fa-circle w-2 h-2 mr-1"></i> -->
                        <!--⬀ Operational
                    </span> -->
                    <span id="server-status" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
                        ⬀ Checking...
                    </span>
                    <button id="system-info-btn" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-info-circle"></i>
                    </button>
                </div>
            </div>
        </div>
    </header>

    <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <!-- Home Page Section -->
        <div id="home-section" class="page-section active">
            <!-- Hero Section -->
            <div class="relative bg-white overflow-hidden rounded-lg shadow-lg mb-8">
                <div class="hero-pattern absolute inset-0"></div>
                <div class="relative px-4 py-16 sm:px-6 sm:py-24 lg:py-32 lg:px-8">
                    <div class="text-center">
                        <h1 class="text-4xl font-extrabold tracking-tight text-gray-900 sm:text-5xl lg:text-6xl">
                            Multilingual Audio Intelligence
                        </h1>
                        <p class="mt-6 max-w-3xl mx-auto text-xl text-gray-500 leading-relaxed">
                            Advanced AI-powered speaker diarization, transcription, and translation system.
                            Transform any audio into structured, actionable insights with speaker attribution and cross-lingual understanding.
                        </p>
                        <div class="mt-10 flex justify-center space-x-4">
                            <button id="get-started-btn" class="inline-flex items-center px-8 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                                <i class="fas fa-rocket mr-2"></i>
                                Get Started
                            </button>
                            <button id="try-demo-btn" class="inline-flex items-center px-8 py-3 border border-gray-300 text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                                <i class="fas fa-play mr-2"></i>
                                Try Demo
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Features Grid -->
            <div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 mb-12">
                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-users text-2xl text-blue-600"></i>
                            </div>
                            <div class="ml-4">
                                <h3 class="text-lg font-medium text-gray-900">Speaker Diarization</h3>
                                <p class="text-sm text-gray-500 mt-1">Identify who spoke when with 95%+ accuracy</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-language text-2xl text-green-600"></i>
                            </div>
                            <div class="ml-4">
                                <h3 class="text-lg font-medium text-gray-900">Multilingual Recognition</h3>
                                <p class="text-sm text-gray-500 mt-1">Support for 99+ languages with auto-detection</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-exchange-alt text-2xl text-purple-600"></i>
                            </div>
                            <div class="ml-4">
                                <h3 class="text-lg font-medium text-gray-900">Neural Translation</h3>
                                <p class="text-sm text-gray-500 mt-1">High-quality translation to multiple languages</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-chart-line text-2xl text-red-600"></i>
                            </div>
                            <div class="ml-4">
                                <h3 class="text-lg font-medium text-gray-900">Interactive Visualization</h3>
                                <p class="text-sm text-gray-500 mt-1">Real-time waveform analysis and insights</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-download text-2xl text-yellow-600"></i>
                            </div>
                            <div class="ml-4">
                                <h3 class="text-lg font-medium text-gray-900">Multiple Formats</h3>
                                <p class="text-sm text-gray-500 mt-1">Export as JSON, SRT, TXT, or CSV</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-bolt text-2xl text-orange-600"></i>
                            </div>
                            <div class="ml-4">
                                <h3 class="text-lg font-medium text-gray-900">Fast Processing</h3>
                                <p class="text-sm text-gray-500 mt-1">14x real-time processing speed</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Technical Details -->
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Technical Specifications</h3>
                    <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <div>
                            <h4 class="text-sm font-medium text-gray-700 mb-2">Supported Audio Formats</h4>
                            <div class="flex flex-wrap gap-2">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">WAV</span>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">MP3</span>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">OGG</span>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">FLAC</span>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">M4A</span>
                            </div>
                        </div>
                        <div>
                            <h4 class="text-sm font-medium text-gray-700 mb-2">Performance</h4>
                            <ul class="text-sm text-gray-600 space-y-1">
                                <li>β€’ Processing: 2-14x real-time</li>
                                <li>β€’ Maximum file size: 100MB</li>
                                <li>β€’ Recommended duration: Under 30 minutes</li>
                                <li>β€’ CPU optimized (no GPU required)</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Processing Section -->
        <div id="processing-section" class="page-section">
            <div class="px-4 py-6 sm:px-0">
                <div class="text-center mb-8">
                    <h2 class="text-3xl font-extrabold text-gray-900 sm:text-4xl">
                        Process Audio File
                    </h2>
                    <p class="mt-4 max-w-2xl mx-auto text-xl text-gray-500">
                        Upload your audio file and select processing options to get comprehensive analysis.
                    </p>
                    <div class="mt-4">
                        <span id="processing-mode-indicator" class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                            <i class="fas fa-cog mr-2"></i>
                            Full Processing Mode
                        </span>
                    </div>
                </div>
            </div>

            <!-- Upload Section -->
            <div class="px-4 sm:px-0">
                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="px-4 py-5 sm:p-6">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Select Audio File</h3>
                        
                        <form id="upload-form" enctype="multipart/form-data">
                            <!-- Demo Mode Section -->
                            <div id="demo-mode-section" class="mb-6 hidden">
                                
                                <!-- Scrollable demo files container -->
                                <div class="relative">
                                    <!-- Scroll buttons for mobile -->
                                    <div class="flex justify-between items-center mb-2 sm:hidden">
                                        <button type="button" id="scroll-left" class="p-2 text-gray-500 hover:text-gray-700 disabled:opacity-50" disabled>
                                            <i class="fas fa-chevron-left"></i>
                                        </button>
                                        <button type="button" id="scroll-right" class="p-2 text-gray-500 hover:text-gray-700">
                                            <i class="fas fa-chevron-right"></i>
                                        </button>
                                    </div>
                                    
                                    <!-- Scrollable demo files grid -->
                                    <div id="demo-files-container" class="flex gap-4 overflow-x-auto pb-4 scrollbar-hide" style="scroll-behavior: smooth;">
                                        <!-- Demo files will be populated dynamically -->
                                    </div>
                                    
                                    <!-- Scroll indicators -->
                                    <!-- <div class="flex justify-center mt-2 space-x-1">
                                        <div class="w-2 h-2 bg-gray-300 rounded-full scroll-indicator active"></div>
                                        <div class="w-2 h-2 bg-gray-300 rounded-full scroll-indicator"></div>
                                        <div class="w-2 h-2 bg-gray-300 rounded-full scroll-indicator"></div>
                                        <div class="w-2 h-2 bg-gray-300 rounded-full scroll-indicator"></div>
                                    </div> -->
                                </div>
                                
                                <input type="hidden" id="selected-demo-file" name="demo_file_id" value="">
                            </div>

                            <!-- File Upload Area (Full Processing Mode) -->
                            <div id="file-upload-section" class="mb-6">
                                <div class="upload-area rounded-lg p-6 text-center mb-6" id="upload-area">
                                    <input type="file" id="file-input" name="file" class="hidden" accept=".wav,.mp3,.ogg,.flac,.m4a">
                                    <div id="upload-prompt">
                                        <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
                                        <p class="text-lg text-gray-600 mb-2">Click to upload or drag and drop</p>
                                        <p class="text-sm text-gray-500">WAV, MP3, OGG, FLAC, or M4A files up to 100MB</p>
                                    </div>
                                    <div id="file-info" class="hidden">
                                        <i class="fas fa-file-audio text-4xl text-blue-500 mb-4"></i>
                                        <p id="file-name" class="text-lg text-gray-800 mb-2"></p>
                                        <p id="file-size" class="text-sm text-gray-500"></p>
                                    </div>
                                </div>
                            </div>

                            <!-- Audio Preview Section -->
                            <div id="audio-preview" class="mb-6 hidden">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Audio Preview</label>
                                <div class="bg-gray-50 p-4 rounded-lg border">
                                    <audio id="audio-player" controls class="w-full mb-4">
                                        Your browser does not support the audio element.
                                    </audio>
                                    <!-- Waveform Visualization -->
                                    <div id="waveform-container" class="mt-4">
                                        <canvas id="waveform-canvas" class="w-full h-20 bg-gray-100 rounded"></canvas>
                                    </div>
                                </div>
                            </div>

                            <!-- Configuration Options -->
                            <div id="config-options" class="grid grid-cols-1 gap-6 sm:grid-cols-2 mb-6">
                                <div>
                                    <label for="whisper-model" class="block text-sm font-medium text-gray-700">Model Size</label>
                                    <select id="whisper-model" name="whisper_model" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                                        <option value="tiny">Tiny (Fast, Lower Accuracy)</option>
                                        <option value="small" selected>Small (Balanced)</option>
                                        <option value="medium">Medium (Better Accuracy)</option>
                                        <option value="large">Large (Best Accuracy, Slower)</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="target-language" class="block text-sm font-medium text-gray-700">Target Language</label>
                                    <select id="target-language" name="target_language" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                                        <option value="en" selected>English</option>
                                        <option value="es">Spanish</option>
                                        <option value="fr">French</option>
                                        <option value="de">German</option>
                                        <option value="it">Italian</option>
                                        <option value="pt">Portuguese</option>
                                        <option value="zh">Chinese</option>
                                        <option value="ja">Japanese</option>
                                        <option value="ko">Korean</option>
                                        <option value="ar">Arabic</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Submit Button (hidden in demo mode) -->
                            <div id="process-btn-container" class="flex justify-center">
                                <button type="submit" id="process-btn" class="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
                                    <i class="fas fa-play mr-2"></i>
                                    Process Audio
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Progress Section -->
            <div id="progress-section" class="px-4 sm:px-0 mt-6 hidden">
                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="px-4 py-5 sm:p-6">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Processing Status</h3>
                        <div class="mb-4">
                            <div class="flex justify-between text-sm text-gray-600 mb-1">
                                <span id="progress-text">Initializing...</span>
                                <span id="progress-percent">0%</span>
                            </div>
                            <div class="bg-gray-200 rounded-full h-2">
                                <div id="progress-bar" class="progress-bar h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
                            </div>
                        </div>
                        <p id="progress-detail" class="text-sm text-gray-500">Please wait while we process your audio file...</p>
                    </div>
                </div>
            </div>

            <!-- Results Section -->
            <div id="results-section" class="px-4 sm:px-0 mt-6 hidden">
                <div class="bg-white overflow-hidden shadow rounded-lg">
                    <div class="px-4 py-5 sm:p-6">
                        <div class="flex justify-between items-center mb-6">
                            <h3 class="text-lg font-medium text-gray-900">Analysis Results</h3>
                            <div class="flex space-x-2">
                                <button id="download-json" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                    <i class="fas fa-download mr-2"></i>JSON
                                </button>
                                <button id="download-srt" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                    <i class="fas fa-download mr-2"></i>SRT
                                </button>
                                <button id="download-txt" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                    <i class="fas fa-download mr-2"></i>Text
                                </button>
                            </div>
                        </div>

                        <!-- Tabs -->
                        <div class="border-b border-gray-200 mb-6">
                            <nav class="-mb-px flex space-x-8">
                                <button class="tab-btn whitespace-nowrap py-2 px-1 border-b-2 border-blue-500 font-medium text-sm text-blue-600" data-tab="transcript">
                                    Transcript & Translation
                                </button>
                                <button class="tab-btn whitespace-nowrap py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300" data-tab="visualization">
                                    Analytics & Insights
                                </button>
                                <button class="tab-btn whitespace-nowrap py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300" data-tab="summary">
                                    Summary
                                </button>
                            </nav>
                        </div>

                        <!-- Tab Content -->
                        <div id="transcript-tab" class="tab-content active">
                            <div id="transcript-content">
                                <!-- Transcript and translation will be populated here -->
                            </div>
                        </div>

                        <div id="visualization-tab" class="tab-content">
                            <div class="grid grid-cols-1 gap-6">
                                <div id="language-chart" style="width:100%;height:300px;"></div>
                                <div id="speaker-timeline" style="width:100%;height:300px;"></div>
                            </div>
                        </div>

                        <div id="summary-tab" class="tab-content">
                            <div id="summary-content">
                                <!-- Summary will be populated here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- System Info Modal -->
    <div id="system-info-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-medium text-gray-900">System Information</h3>
                    <button id="close-modal" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div id="system-info-content">
                    <div class="loading text-center py-4">
                        <div class="inline-block">
                            <i class="fas fa-spinner fa-spin text-2xl text-blue-500"></i>
                        </div>
                        <p class="mt-2 text-gray-600">Loading system information...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Global variables
        let currentTaskId = null;
        let progressInterval = null;
        let isDemoMode = false;

        // DOM elements
        const homeSection = document.getElementById('home-section');
        const processingSection = document.getElementById('processing-section');
        const uploadArea = document.getElementById('upload-area');
        const fileInput = document.getElementById('file-input');
        const uploadForm = document.getElementById('upload-form');
        const processBtn = document.getElementById('process-btn');
        const progressSection = document.getElementById('progress-section');
        const resultsSection = document.getElementById('results-section');
        const systemInfoBtn = document.getElementById('system-info-btn');
        const systemInfoModal = document.getElementById('system-info-modal');
        const closeModal = document.getElementById('close-modal');

        // Navigation elements
        const homeLink = document.getElementById('home-link');
        const getStartedBtn = document.getElementById('get-started-btn');
        const tryDemoBtn = document.getElementById('try-demo-btn');
        const demoModeBtn = document.getElementById('demo-mode-btn');
        const processingModeBtn = document.getElementById('processing-mode-btn');
        const processingModeIndicator = document.getElementById('processing-mode-indicator');

        async function updateServerStatus() {
            const el = document.getElementById("server-status");
            try {
                const res = await fetch("/health"); // or your FastAPI health endpoint
                if (!res.ok) throw new Error("Bad response");
                el.textContent = "⬀ Live";
                el.className = "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800";
            } catch (err) {
                // Could be error or down
                fetch("/").catch(() => {
                    el.textContent = "⬀ Server Down";
                    el.className = "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800";
                });

                el.textContent = "⬀ Error";
                el.className = "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800";
            }
        }
        // setInterval(updateServerStatus, 5000);
        // updateServerStatus();
        document.addEventListener("DOMContentLoaded", updateServerStatus);

        // Navigation handling
        function showHome() {
            homeSection.classList.add('active');
            processingSection.classList.remove('active');
            resetProcessing();
        }

        function showProcessing(demoMode = false) {
            homeSection.classList.remove('active');
            processingSection.classList.add('active');
            isDemoMode = demoMode;
            updateProcessingMode();
            resetProcessing();
        }

        function updateProcessingMode() {
            if (isDemoMode) {
                processingModeIndicator.innerHTML = '<i class="fas fa-play-circle mr-2"></i>Demo Mode';
                processingModeIndicator.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800';
                demoModeBtn.className = 'inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500';
                processingModeBtn.className = 'inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500';
                
                // Show demo section, hide file upload and config options
                document.getElementById('demo-mode-section').classList.remove('hidden');
                document.getElementById('file-upload-section').classList.add('hidden');
                document.getElementById('config-options').classList.add('hidden');
                
                // Hide Process Audio button in demo mode
                document.getElementById('process-btn-container').classList.add('hidden');
                
                // Load demo files when switching to demo mode
                loadDemoFiles();
            } else {
                processingModeIndicator.innerHTML = '<i class="fas fa-cog mr-2"></i>Full Processing Mode';
                processingModeIndicator.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800';
                demoModeBtn.className = 'inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500';
                processingModeBtn.className = 'inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500';
                
                // Hide demo section, show file upload and config options
                document.getElementById('demo-mode-section').classList.add('hidden');
                document.getElementById('file-upload-section').classList.remove('hidden');
                document.getElementById('config-options').classList.remove('hidden');
                
                // Show Process Audio button in full mode
                document.getElementById('process-btn-container').classList.remove('hidden');
            }
        }

        function resetProcessing() {
            progressSection.classList.add('hidden');
            resultsSection.classList.add('hidden');
            if (progressInterval) {
                clearInterval(progressInterval);
                progressInterval = null;
            }
            currentTaskId = null;
            
            // Reset form
            document.getElementById('upload-prompt').classList.remove('hidden');
            document.getElementById('file-info').classList.add('hidden');
            document.getElementById('audio-preview').classList.add('hidden');
            
            // Reset demo selection
            document.querySelectorAll('.demo-file-option').forEach(opt => {
                opt.classList.remove('border-blue-500', 'bg-blue-50');
                opt.classList.add('border-gray-200');
            });
            document.getElementById('selected-demo-file').value = '';
            
            uploadForm.reset();
        }

        // Demo file selection handling
        document.addEventListener('DOMContentLoaded', () => {
            const demoOptions = document.querySelectorAll('.demo-file-option');
            demoOptions.forEach(option => {
                option.addEventListener('click', () => {
                    // Remove selection from all options
                    document.querySelectorAll('.demo-file-option').forEach(opt => {
                        opt.classList.remove('border-blue-500', 'bg-blue-50');
                        opt.classList.add('border-gray-200');
                    });
                    
                    // Select clicked option
                    option.classList.add('border-blue-500', 'bg-blue-50');
                    option.classList.remove('border-gray-200');
                    
                    // Set selected demo file ID
                    const demoId = option.dataset.demoId;
                    const selectedDemoFile = document.getElementById('selected-demo-file');
                    if (selectedDemoFile) {
                        selectedDemoFile.value = demoId;
                    }
                    
                    // Load demo audio preview
                    loadDemoAudioPreview(demoId);
                });
            });
        });

        async function loadDemoAudioPreview(demoId) {
            try {
                // For demo purposes, we'll show a placeholder waveform
                const audioPreview = document.getElementById('audio-preview');
                const audioPlayer = document.getElementById('audio-player');
                
                // Set demo audio source (if files are available locally)
                const demoConfig = {
                    'yuri_kizaki': {
                        name: 'Yuri Kizaki - Japanese Audio',
                        filename: 'Yuri_Kizaki.mp3',
                        duration: 23.0
                    },
                    'film_podcast': {
                        name: 'French Film Podcast',
                        filename: 'Film_Podcast.mp3',
                        duration: 25.0
                    }
                };
                
                if (demoConfig[demoId]) {
                    // Try to load demo file if available
                    try {
                        // audioPlayer.src = `/demo_audio/${demoConfig[demoId].name.replace(' - ', ' - ').replace('Japanese Audio', '03.mp3').replace('French Film Podcast', 'film-podcast.mp3')}`;
                        audioPlayer.src = `/demo_audio/${demoConfig[demoId].filename}`;
                        audioPlayer.load();

                        // πŸ”Ή Enable live waveform updates
                        audioPlayer.addEventListener('loadedmetadata', () => {
                            generateWaveformFromAudio(audioPlayer);
                        });

                    } catch (e) {
                        console.log('Demo audio file not directly accessible, will be processed on server');
                    }
                    
                    // Generate demo waveform
                    // generateDemoWaveform(demoConfig[demoId].duration);
                    audioPreview.classList.remove('hidden');
                }
            } catch (error) {
                console.error('Error loading demo preview:', error);
            }
        }

        function generateDemoWaveform(canvasElement, fileName = 'Audio Preview') {
            // Support both old (duration) and new (canvas, fileName) calling patterns
            let canvas;
            if (typeof canvasElement === 'string' || typeof canvasElement === 'number') {
                // Old calling pattern with duration
                canvas = document.getElementById('waveform-canvas');
            } else {
                // New calling pattern with canvas element
                canvas = canvasElement || document.getElementById('waveform-canvas');
            }
            const ctx = canvas.getContext('2d');
            
            // Set canvas size
            const canvasHeight = canvas.offsetHeight || 80;
            canvas.width = canvas.offsetWidth * window.devicePixelRatio;
            canvas.height = canvasHeight * window.devicePixelRatio;
            ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
            
            // Clear canvas
            ctx.clearRect(0, 0, canvas.offsetWidth, canvasHeight);
            
            // Generate sample waveform data
            const samples = 100;  // Reduced from 200 for cleaner look
            const barWidth = canvas.offsetWidth / samples;
            
            ctx.fillStyle = '#3B82F6';
            
            for (let i = 0; i < samples; i++) {
                // Generate realistic waveform pattern
                const amplitude = Math.sin(i * 0.1) * Math.random() * 0.8 + 0.2;
                const height = amplitude * (canvasHeight * 0.8);
                const x = i * barWidth;
                const y = (canvasHeight - height) / 2;
                
                ctx.fillRect(x, y, barWidth - 1, height);
            }
        }

        function handleFileSelect() {
            const file = fileInput.files[0];
            if (file) {
                document.getElementById('upload-prompt').classList.add('hidden');
                document.getElementById('file-info').classList.remove('hidden');
                document.getElementById('file-name').textContent = file.name;
                document.getElementById('file-size').textContent = formatFileSize(file.size);
                
                // Show audio preview with waveform
                const audioPreview = document.getElementById('audio-preview');
                const audioPlayer = document.getElementById('audio-player');
                if (file.type.startsWith('audio/')) {
                    const url = URL.createObjectURL(file);
                    audioPlayer.src = url;
                    audioPreview.classList.remove('hidden');
                    
                    // Generate waveform when audio loads
                    audioPlayer.addEventListener('loadedmetadata', () => {
                        generateWaveformFromAudio(audioPlayer);
                    });
                    
                    // Also generate static waveform immediately
                    const canvas = document.getElementById('waveform-canvas');
                    if (canvas) {
                        generateDemoWaveform(canvas, file.name);
                    }
                }
            }
        }

        function generateWaveformFromAudio(audioElement, targetCanvas = null, audioSource = null) {
            console.log('🎨 Generating waveform visualization...');
            
            // Find the right canvas element 
            const canvas = targetCanvas || 
                          document.getElementById('demo-waveform-canvas') || 
                          document.getElementById('waveform-canvas');
                          
            if (!canvas) {
                console.warn('⚠️ No canvas element found for waveform');
                return;
            }

            // Set canvas dimensions
            canvas.width = canvas.offsetWidth * (window.devicePixelRatio || 1);
            canvas.height = (canvas.offsetHeight || 80) * (window.devicePixelRatio || 1);
            const ctx = canvas.getContext('2d');
            ctx.scale(window.devicePixelRatio || 1, window.devicePixelRatio || 1);

            // Always generate static waveform first as fallback
            generateDemoWaveform(canvas, 'Audio Preview');

            // Try to generate actual waveform from audio data
            if (audioElement && audioElement.src) {
                console.log('πŸ“Š Attempting to generate real waveform from audio data...');
                
                try {
                    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                    
                    // Fetch and decode audio data for static waveform
                    fetch(audioElement.src)
                        .then(response => response.arrayBuffer())
                        .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
                        .then(audioBuffer => {
                            console.log('βœ… Audio decoded successfully, drawing real waveform');
                            drawWaveformFromBuffer(audioBuffer, canvas);
                            
                            // Setup live waveform when audio plays
                            setupLiveWaveform(audioElement, canvas);
                        })
                        .catch(err => {
                            console.warn("⚠️ Could not decode audio, using static fallback", err);
                        });
                        
                } catch (error) {
                    console.warn('⚠️ Web Audio API not available, using static fallback', error);
                }
            }

            function drawWaveformFromBuffer(audioBuffer, canvas) {
                const ctx = canvas.getContext('2d');
                const rawData = audioBuffer.getChannelData(0); // mono
                const samples = 100; // number of bars
                const blockSize = Math.floor(rawData.length / samples);
                const filteredData = [];
                
                // Process audio data into sample points
                for (let i = 0; i < samples; i++) {
                    let sum = 0;
                    for (let j = 0; j < blockSize; j++) {
                        const sample = rawData[i * blockSize + j];
                        sum += Math.abs(sample);
                    }
                    filteredData.push(sum / blockSize);
                }

                // Clear and draw waveform
                ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
                ctx.fillStyle = '#3B82F6';

                const barWidth = canvas.offsetWidth / samples;
                const maxHeight = canvas.offsetHeight * 0.9;
                
                filteredData.forEach((val, i) => {
                    const barHeight = val * maxHeight;
                    const x = i * barWidth;
                    const y = (canvas.offsetHeight - barHeight) / 2;
                    ctx.fillRect(x, y, barWidth - 1, barHeight);
                });
            }
            
            function setupLiveWaveform(audioElement, canvas) {
                // Setup live visualization when audio plays
                audioElement.addEventListener('play', () => {
                    console.log('🎡 Starting live waveform visualization...');
                    
                    try {
                        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                        
                        if (audioContext.state === 'suspended') {
                            audioContext.resume();
                        }
                        
                        const source = audioContext.createMediaElementSource(audioElement);
                        const analyser = audioContext.createAnalyser();
                        
                        source.connect(analyser);
                        analyser.connect(audioContext.destination);
                        
                        analyser.fftSize = 256;
                        const bufferLength = analyser.frequencyBinCount;
                        const dataArray = new Uint8Array(bufferLength);
                        
                        const ctx = canvas.getContext('2d');
                        
                        function drawLiveWaveform() {
                            if (audioElement.paused) return;
                            
                            analyser.getByteFrequencyData(dataArray);
                            
                            ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
                            ctx.fillStyle = '#10B981'; // Green for live
                            
                            const barWidth = canvas.offsetWidth / bufferLength;
                            const maxHeight = canvas.offsetHeight * 0.8;
                            
                            for (let i = 0; i < bufferLength; i++) {
                                const barHeight = (dataArray[i] / 255) * maxHeight;
                                const x = i * barWidth;
                                const y = (canvas.offsetHeight - barHeight) / 2;
                                
                                ctx.fillRect(x, y, barWidth - 1, barHeight);
                            }
                            
                            requestAnimationFrame(drawLiveWaveform);
                        }
                        
                        drawLiveWaveform();
                        
                    } catch (error) {
                        console.warn('⚠️ Live waveform not available:', error);
                    }
                });
                
                // Restore static waveform when audio stops
                audioElement.addEventListener('pause', () => {
                    setTimeout(() => {
                        if (audioElement.paused) {
                            generateWaveformFromAudio(audioElement, canvas);
                        }
                    }, 100);
                });
            }
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // Event listeners for navigation
        homeLink.addEventListener('click', showHome);
        getStartedBtn.addEventListener('click', () => showProcessing(false));
        tryDemoBtn.addEventListener('click', () => showProcessing(true));
        demoModeBtn.addEventListener('click', () => showProcessing(true));
        processingModeBtn.addEventListener('click', () => showProcessing(false));

        // File upload handling
        uploadArea.addEventListener('click', () => fileInput.click());
        uploadArea.addEventListener('dragover', handleDragOver);
        uploadArea.addEventListener('dragleave', handleDragLeave);
        uploadArea.addEventListener('drop', handleDrop);
        fileInput.addEventListener('change', handleFileSelect);

        function handleDragOver(e) {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                fileInput.files = files;
                handleFileSelect();
            }
        }

        // Form submission
        uploadForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            // Validate based on mode
            if (isDemoMode) {
                const selectedDemo = document.getElementById('demo-selector').value;
                if (!selectedDemo) {
                    alert('Please select a demo audio file.');
                    return;
                }
            } else {
                if (!fileInput.files[0]) {
                    alert('Please select a file to upload.');
                    return;
                }
            }

            const formData = new FormData();
            
            // Add form data based on mode
            if (isDemoMode) {
                formData.append('demo_file_id', document.getElementById('demo-selector').value);
                formData.append('whisper_model', document.getElementById('whisper-model').value);
                formData.append('target_language', document.getElementById('target-language').value);
            } else {
                formData.append('file', fileInput.files[0]);
                formData.append('whisper_model', document.getElementById('whisper-model').value);
                formData.append('target_language', document.getElementById('target-language').value);
            }
            
            try {
                processBtn.disabled = true;
                processBtn.innerHTML = '<i class="fas fa-spinner loading-spinner mr-2"></i>Starting...';
                
                // Choose endpoint based on mode
                let response;
                if (isDemoMode) {
                    // In demo mode, use the same approach as "View Results" button
                    const selector = document.getElementById('demo-selector');
                    if (!selector || !selector.value) {
                        alert('Please select a demo audio file first.');
                        return;
                    }
                    const demoId = selector.value;
                    response = await fetch(`/api/process-demo/${demoId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                } else {
                    // Full processing mode
                    response = await fetch('/api/upload', {
                        method: 'POST',
                        body: formData
                    });
                }

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();
                
                if (result.status === 'complete') {
                    // Demo mode returns immediate results
                    showResults(result.results);
                } else {
                    // Real processing mode - handle async processing
                    currentTaskId = result.task_id;
                    showProgress();
                    startProgressPolling();
                }

            } catch (error) {
                console.error('Upload error:', error);
                alert('Error processing request: ' + error.message);
            } finally {
                processBtn.disabled = false;
                processBtn.innerHTML = '<i class="fas fa-play mr-2"></i>Process Audio';
            }
        });

        function showProgress() {
            progressSection.classList.remove('hidden');
            resultsSection.classList.add('hidden');
        }

        function startProgressPolling() {
            if (!currentTaskId) return;
            
            progressInterval = setInterval(async () => {
                try {
                    const response = await fetch(`/api/status/${currentTaskId}`);
                    
                    if (!response.ok) {
                        throw new Error(`Status fetch failed: ${response.status}`);
                    }
                    
                    const status = await response.json();
                    
                    if (!status) {
                        console.warn('⚠️ Empty status response');
                        return;
                    }
                    
                    updateProgress(status);
                    
                    if (status.status === 'complete') {
                        clearInterval(progressInterval);
                        const resultsResponse = await fetch(`/api/results/${currentTaskId}`);
                        
                        if (!resultsResponse.ok) {
                            throw new Error(`Results fetch failed: ${resultsResponse.status}`);
                        }
                        
                        const results = await resultsResponse.json();
                        
                        if (results && results.results) {
                            showResults(results.results);
                        } else if (results) {
                            // Handle direct results format (full processing mode)
                            showResults(results);
                        } else {
                            console.error('❌ Invalid results format:', results);
                            alert('Error: No results available');
                            progressSection.classList.add('hidden');
                        }
                    } else if (status.status === 'error') {
                        clearInterval(progressInterval);
                        alert('Processing error: ' + status.error);
                        progressSection.classList.add('hidden');
                    }
                } catch (error) {
                    console.error('Status polling error:', error);
                }
            }, 1000);
        }

        function updateProgress(status) {
            const progressBar = document.getElementById('progress-bar');
            const progressText = document.getElementById('progress-text');
            const progressPercent = document.getElementById('progress-percent');
            const progressDetail = document.getElementById('progress-detail');
            
            const progress = status.progress || 0;
            progressBar.style.width = `${progress}%`;
            progressPercent.textContent = `${progress}%`;
            
            const statusMessages = {
                'initializing': 'Initializing processing pipeline...',
                'processing': 'Analyzing audio and identifying speakers...',
                'generating_outputs': 'Generating transcripts and translations...',
                'complete': 'Processing complete!'
            };
            
            progressText.textContent = statusMessages[status.status] || 'Processing...';
            progressDetail.textContent = isDemoMode ? 
                'Demo mode - results will be shown shortly.' : 
                'This may take a few minutes depending on audio length.';
        }

        function showResults(results) {
            progressSection.classList.add('hidden');
            resultsSection.classList.remove('hidden');
            
            console.log('🎯 Processing results:', results);
            
            // Handle different result formats (old vs new pipeline output)
            let segments, summary;
            
            if (results.segments && results.summary) {
                // Old format: direct segments and summary
                segments = results.segments;
                summary = results.summary;
            } else if (results.outputs && results.outputs.json) {
                // New format: segments in outputs.json (JSON string)
                try {
                    const jsonData = JSON.parse(results.outputs.json);
                    segments = jsonData.segments || [];
                    summary = jsonData.statistics || results.processing_stats || {};
                } catch (e) {
                    console.error('❌ Failed to parse JSON output:', e);
                    segments = [];
                    summary = {};
                }
            } else if (results.processed_segments) {
                // Alternative new format: processed_segments array (string representations need parsing)
                segments = results.processed_segments.map(seg => {
                    // Handle string representation of ProcessedSegment
                    if (typeof seg === 'string' && seg.startsWith('ProcessedSegment(')) {
                        // Extract data from string representation
                        const match = seg.match(/ProcessedSegment\(start_time=([\d.]+), end_time=([\d.]+), speaker_id='([^']+)', original_text='([^']+)', original_language='([^']+)', translated_text='([^']+)'/);
                        if (match) {
                            return {
                                speaker: match[3],
                                start_time: parseFloat(match[1]),
                                end_time: parseFloat(match[2]),
                                text: match[4],
                                translated_text: match[6],
                                language: match[5]
                            };
                        }
                    }
                    
                    // Handle object representation
                    return {
                        speaker: seg.speaker_id || 'Unknown',
                        start_time: seg.start_time,
                        end_time: seg.end_time,
                        text: seg.original_text || seg.text,
                        translated_text: seg.translated_text,
                        language: seg.original_language || seg.language
                    };
                });
                summary = results.processing_stats || {};
            } else {
                console.error('❌ Unknown results format:', results);
                alert('Error: Unable to display results - unknown format');
                return;
            }
            
            console.log('βœ… Processed segments:', segments.length);
            console.log('βœ… Summary data:', summary);
            
            // Populate transcript
            populateTranscript(segments);
            
            // Populate visualizations
            populateVisualizations(segments);
            
            // Populate summary
            populateSummary(summary);
            
            // Setup download buttons
            setupDownloadButtons();
            
            // Schedule delayed cleanup for non-demo processing
            if (!isDemoMode) {
                scheduleDelayedCleanup();
            }
        }

        function populateVisualizations(segments) {
            // Language Distribution Chart
            createLanguageChart(segments);
            
            // Speaker Timeline
            createSpeakerTimeline(segments);
            
        }

        function createLanguageChart(segments) {
            const languages = {};
            const languageDurations = {};
            
            segments.forEach(seg => {
                const lang = (seg.language || seg.original_language || 'unknown').toUpperCase();
                const duration = (seg.end_time || 0) - (seg.start_time || 0);
                
                languages[lang] = (languages[lang] || 0) + 1;
                languageDurations[lang] = (languageDurations[lang] || 0) + duration;
            });

            const data = [{
                values: Object.values(languages),
                labels: Object.keys(languages),
                type: 'pie',
                marker: {
                    colors: ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6']
                },
                textinfo: 'label+percent',
                textposition: 'auto'
            }];

            const layout = {
                title: {
                    text: '🌍 Language Distribution',
                    font: { size: 18, family: 'Arial, sans-serif' }
                },
                showlegend: true,
                height: 300,
                margin: { t: 50, b: 20, l: 20, r: 20 }
            };

            Plotly.newPlot('language-chart', data, layout, {responsive: true});
        }

        function createSpeakerTimeline(segments) {
            const speakers = [...new Set(segments.map(seg => seg.speaker || seg.speaker_id || 'Unknown'))];
            const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];
            
            const data = speakers.map((speaker, index) => {
                const speakerSegments = segments.filter(seg => (seg.speaker || seg.speaker_id || 'Unknown') === speaker);
                
                return {
                    x: speakerSegments.map(seg => seg.start_time || 0),
                    y: speakerSegments.map(() => speaker),
                    mode: 'markers',
                    type: 'scatter',
                    marker: {
                        size: speakerSegments.map(seg => ((seg.end_time || 0) - (seg.start_time || 0)) * 5),
                        color: colors[index % colors.length],
                        opacity: 0.7
                    },
                    name: speaker,
                    text: speakerSegments.map(seg => `${(seg.text || seg.original_text || '').substring(0, 50)}...`),
                    hovertemplate: '%{text}<br>Time: %{x:.1f}s<extra></extra>'
                };
            });

            const layout = {
                title: {
                    text: 'πŸ‘₯ Speaker Activity Timeline', 
                    font: { size: 18, family: 'Arial, sans-serif' }
                },
                xaxis: { title: 'Time (seconds)' },
                yaxis: { title: 'Speakers' },
                height: 300,
                margin: { t: 50, b: 50, l: 100, r: 20 }
            };

            Plotly.newPlot('speaker-timeline', data, layout, {responsive: true});
        }

        function populateTranscript(segments) {
            const transcriptContent = document.getElementById('transcript-content');
            transcriptContent.innerHTML = '';
            
            segments.forEach((segment, index) => {
                const segmentDiv = document.createElement('div');
                segmentDiv.className = 'mb-6 p-4 border border-gray-200 rounded-lg bg-white shadow-sm';
                
                segmentDiv.innerHTML = `
                    <div class="flex justify-between items-start mb-3">
                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                            ${segment.speaker}
                        </span>
                        <span class="text-sm text-gray-500">
                            ${formatTime(segment.start_time)} - ${formatTime(segment.end_time)}
                        </span>
                    </div>
                    
                    <div class="space-y-3">
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <div class="flex items-center mb-2">
                                <i class="fas fa-microphone text-gray-600 mr-2"></i>
                                <span class="text-sm font-medium text-gray-700">Original (${(segment.language || segment.original_language || 'Unknown').toUpperCase()})</span>
                            </div>
                            <p class="text-gray-800 leading-relaxed">${segment.text}</p>
                        </div>
                        
                        ${segment.translated_text && segment.translated_text !== segment.text && (segment.language || segment.original_language) !== 'en' ? `
                        <div class="bg-blue-50 p-3 rounded-lg">
                            <div class="flex items-center mb-2">
                                <i class="fas fa-language text-blue-600 mr-2"></i>
                                <span class="text-sm font-medium text-blue-700">English Translation</span>
                            </div>
                            <p class="text-blue-800 leading-relaxed italic">${segment.translated_text}</p>
                        </div>
                        ` : ''}
                    </div>
                `;
                
                transcriptContent.appendChild(segmentDiv);
            });
        }

        function populateSummary(summary) {
            const summaryContent = document.getElementById('summary-content');
            summaryContent.innerHTML = `
                <div class="grid grid-cols-2 gap-4">
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h4 class="text-sm font-medium text-gray-700">Total Duration</h4>
                        <p class="text-2xl font-bold text-gray-900">${formatTime(summary.total_duration || 0)}</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h4 class="text-sm font-medium text-gray-700">Speakers Detected</h4>
                        <p class="text-2xl font-bold text-gray-900">${summary.num_speakers || 0}</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h4 class="text-sm font-medium text-gray-700">Speech Segments</h4>
                        <p class="text-2xl font-bold text-gray-900">${summary.num_segments || 0}</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h4 class="text-sm font-medium text-gray-700">Processing Time</h4>
                        <p class="text-2xl font-bold text-gray-900">${Math.round(summary.processing_time || 0)}s</p>
                    </div>
                </div>
                <div class="mt-4">
                    <h4 class="text-sm font-medium text-gray-700 mb-2">Languages Detected</h4>
                    <div class="flex flex-wrap gap-2">
                        ${(summary.languages || []).map(lang => 
                            `<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">${lang}</span>`
                        ).join('')}
                    </div>
                </div>
            `;
        }

        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);
            return `${minutes}:${secs.toString().padStart(2, '0')}`;
        }

        function setupDownloadButtons() {
            document.getElementById('download-json').onclick = () => downloadFile('json');
            document.getElementById('download-srt').onclick = () => downloadFile('srt');
            document.getElementById('download-txt').onclick = () => downloadFile('txt');
        }

        function downloadFile(format) {
            if (currentTaskId) {
                window.open(`/api/download/${currentTaskId}/${format}`, '_blank');
            }
        }

        // Tab handling
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const tabName = e.target.dataset.tab;
                
                // Update tab buttons
                document.querySelectorAll('.tab-btn').forEach(b => {
                    b.classList.remove('border-blue-500', 'text-blue-600');
                    b.classList.add('border-transparent', 'text-gray-500');
                });
                e.target.classList.add('border-blue-500', 'text-blue-600');
                e.target.classList.remove('border-transparent', 'text-gray-500');
                
                // Update tab content
                document.querySelectorAll('.tab-content').forEach(content => {
                    content.classList.remove('active');
                });
                document.getElementById(`${tabName}-tab`).classList.add('active');
            });
        });

        // System info modal
        systemInfoBtn.addEventListener('click', async () => {
            systemInfoModal.classList.remove('hidden');

            const content = document.getElementById('system-info-content');
            content.innerHTML = `
                <div class="loading text-center py-4 flex flex-col items-center">
                    <div class="mb-2">
                        <i class="fas fa-spinner text-2xl text-blue-500 animate-spin"></i>
                    </div>
                    <p class="text-gray-600">Loading system information...</p>
                </div>
            `;
            // content.innerHTML = `
            //     <div class="loading text-center py-4">
            //         <i class="fas fa-spinner text-2xl text-blue-500 animate-spin"></i>
            //         <p class="mt-2 text-gray-600">Loading system information...</p>
            //     </div>
            // `;


            try {
                const response = await fetch('/api/system-info');
                const info = await response.json();

                const statusColors = {
                    green: "bg-green-100 text-green-800",
                    yellow: "bg-yellow-100 text-yellow-800",
                    red: "bg-red-100 text-red-800",
                    gray: "bg-gray-100 text-gray-800"
                };

                const colorClass = statusColors[info.statusColor] || statusColors.gray;

                content.innerHTML = `
                    <div class="space-y-3">
                        <div>
                            <span class="font-medium">Status:</span>
                            <span class="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colorClass}">
                                ⬀ ${info.status}
                            </span>
                        </div>
                        <div>
                            <span class="font-medium">Version:</span>
                            <span class="ml-2 text-gray-600">${info.version}</span>
                        </div>
                        <div>
                            <span class="font-medium">Features:</span>
                            <div class="mt-2 flex flex-wrap gap-1">
                                ${info.features.map(feature => 
                                    `<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-blue-100 text-blue-800">${feature}</span>`
                                ).join('')}
                            </div>
                        </div>
                    </div>
                `;
            } catch (error) {
                content.innerHTML = `<p class="text-red-600">Error loading system information</p>`;
            }
        });

        closeModal.addEventListener('click', () => {
            systemInfoModal.classList.add('hidden');
        });

        // Close modal when clicking outside
        systemInfoModal.addEventListener('click', (e) => {
            if (e.target === systemInfoModal) {
                systemInfoModal.classList.add('hidden');
            }
        });

        // Initialize page
        updateProcessingMode();
        
        // Load demo files if we start in demo mode
        if (isDemoMode) {
            loadDemoFiles();
        }
        
        // Demo files management
        let demoFiles = [];
        
        // Create fallback demo files if API fails
        function createFallbackDemoFiles() {
            demoFiles = [
                {
                    id: "yuri_kizaki",
                    name: "Yuri Kizaki",
                    filename: "Yuri_Kizaki.mp3",
                    language: "ja",
                    description: "Japanese audio message about website communication",
                    duration: "00:01:45",
                    available: true,
                    download_status: "ready"
                },
                {
                    id: "film_podcast",
                    name: "Film Podcast", 
                    filename: "Film_Podcast.mp3",
                    language: "fr",
                    description: "French podcast discussing various films and cinema",
                    duration: "00:03:32",
                    available: true,
                    download_status: "ready"
                },
                {
                    id: "tamil_interview",
                    name: "Tamil Wikipedia Interview",
                    filename: "Tamil_Wikipedia_Interview.ogg",
                    language: "ta",
                    description: "Discussion on Tamil Wikipedia and collaborative knowledge sharing",
                    duration: "00:36:17",
                    available: true,
                    download_status: "ready"
                },
                {
                    id: "car_trouble",
                    name: "Car Trouble",
                    filename: "Car_Trouble.mp3", 
                    language: "hi",
                    description: "Conversation about waiting for a mechanic and basic assistance",
                    duration: "00:02:45",
                    available: true,
                    download_status: "ready"
                }
            ];
            populateDemoFiles();
            
            // Auto-select the first demo file (Yuri Kizaki)
            setTimeout(() => {
                selectDemoFile(demoFiles[0].id);
                const firstOption = document.querySelector(`[data-demo-id="${demoFiles[0].id}"]`);
                if (firstOption) {
                    firstOption.classList.add('border-blue-500', 'bg-blue-50');
                    firstOption.classList.remove('border-gray-200');
                }
            }, 100);
        }
        
        // Get appropriate icon for language
        function getIconForLanguage(language) {
            const icons = {
                'ja': 'fas fa-microphone',
                'fr': 'fas fa-podcast',
                'ta': 'fas fa-headphones',
                'hi': 'fas fa-volume-up'
            };
            return icons[language] || 'fas fa-music';
        }
        
        // Get status class for download status
        function getStatusClass(status) {
            const classes = {
                'pending': 'bg-gray-100 text-gray-800',
                'downloading': 'bg-yellow-100 text-yellow-800',
                'completed': 'bg-green-100 text-green-800',
                'ready': 'bg-green-100 text-green-800',
                'failed': 'bg-red-100 text-red-800'
            };
            return classes[status] || 'bg-gray-100 text-gray-800';
        }
        
        // Get status text for download status
        function getStatusText(status) {
            const texts = {
                'pending': 'Pending',
                'downloading': 'Downloading...',
                'completed': 'Available',
                'ready': 'Ready',
                'failed': 'Failed'
            };
            return texts[status] || 'Unknown';
        }
        
        // Select demo file
        function selectDemoFile(demoId) {
            document.getElementById('selected-demo-file').value = demoId;
            console.log('Selected demo file:', demoId);
        }
        
        // Scroll functionality for demo files
        function updateScrollIndicators() {
            const container = document.getElementById('demo-files-container');
            const indicators = document.querySelectorAll('.scroll-indicator');
            const scrollLeft = container.scrollLeft;
            const maxScroll = container.scrollWidth - container.clientWidth;
            
            // Update scroll buttons
            const leftBtn = document.getElementById('scroll-left');
            const rightBtn = document.getElementById('scroll-right');
            
            if (leftBtn) leftBtn.disabled = scrollLeft <= 0;
            if (rightBtn) rightBtn.disabled = scrollLeft >= maxScroll;
            
            // Update indicators
            const scrollPercentage = maxScroll > 0 ? scrollLeft / maxScroll : 0;
            const activeIndex = Math.floor(scrollPercentage * (indicators.length - 1));
            
            indicators.forEach((indicator, index) => {
                indicator.classList.toggle('active', index === activeIndex);
            });
        }
        
        // Scroll event handlers
        document.addEventListener('DOMContentLoaded', () => {
            const container = document.getElementById('demo-files-container');
            if (container) {
                container.addEventListener('scroll', updateScrollIndicators);
            }
            
            // Scroll button handlers
            const leftBtn = document.getElementById('scroll-left');
            const rightBtn = document.getElementById('scroll-right');
            
            if (leftBtn) {
                leftBtn.addEventListener('click', () => {
                    container.scrollBy({ left: -300, behavior: 'smooth' });
                });
            }
            
            if (rightBtn) {
                rightBtn.addEventListener('click', () => {
                    container.scrollBy({ left: 300, behavior: 'smooth' });
                });
            }
        });
        
        // Load demo files when switching to demo mode
        const demoModeToggle = document.getElementById('demo-mode-toggle');
        if (demoModeToggle) {
            demoModeToggle.addEventListener('change', function() {
                if (this.checked) {
                    loadDemoFiles();
                }
            });
            
            // Load demo files on page load if demo mode is enabled
            if (demoModeToggle.checked) {
                loadDemoFiles();
            }
        }
        
        // Load demo files from server or use fallback
        async function loadDemoFiles() {
            console.log('πŸ”„ Loading demo files from API...');
            try {
                const response = await fetch('/api/demo-files');
                console.log('πŸ“‘ API Response status:', response.status);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                console.log('πŸ“‹ API returned demo files:', data);
                
                // Check if data has demo_files property or is direct array
                if (data.demo_files && Array.isArray(data.demo_files)) {
                    demoFiles = data.demo_files;
                    console.log('βœ… Demo files loaded from API:', demoFiles.length);
                    console.log('πŸ“‹ Demo files details:', demoFiles);
                    populateDemoFiles();
                } else if (Array.isArray(data)) {
                    demoFiles = data;
                    console.log('βœ… Demo files loaded as direct array:', demoFiles.length);
                    populateDemoFiles();
                } else {
                    console.warn('⚠️ Unexpected API response format, using fallback');
                    createFallbackDemoFiles();
                }
            } catch (error) {
                console.error('❌ Failed to load demo files:', error);
                console.error('Error details:', error.message);
                createFallbackDemoFiles();
            }
        }
        
        // Populate demo files in the UI - showing one at a time like uploaded files
        function populateDemoFiles() {
            console.log('πŸ—οΈ Starting populateDemoFiles...');
            console.log('πŸ“‹ Demo files to populate:', demoFiles);
            
            const container = document.getElementById('demo-files-container');
            console.log('🎯 Container element:', container);
            
            if (!container) {
                console.error('❌ Demo files container not found! Expected element with id="demo-files-container"');
                return;
            }
            
            console.log('βœ… Container found, clearing existing content...');
            container.innerHTML = '';
            
            if (demoFiles.length === 0) {
                console.warn('⚠️ No demo files to display');
                container.innerHTML = '<p class="text-gray-500 text-center py-8">No demo files available</p>';
                return;
            }
            
            console.log(`πŸ”§ Creating single demo file selector for ${demoFiles.length} files...`);
            console.log('πŸ“‹ Available demo files:', demoFiles.map(f => ({ id: f.id, name: f.name })));
            
            // Create a single full-width demo file display (like uploaded file)
            const demoContainer = document.createElement('div');
            demoContainer.className = 'w-full';
            
            // Create dropdown selector for demo files
            const selectorHTML = `
                <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-6 border border-blue-200 w-full">
                    <div class="flex items-center space-x-4 mb-4">
                        <div class="flex-shrink-0">
                            <div class="w-12 h-12 bg-blue-500 rounded-lg flex items-center justify-center">
                                <i class="fas fa-play text-white text-lg"></i>
                            </div>
                        </div>
                        <div class="flex-1">
                            <label for="demo-selector" class="block text-sm font-medium text-gray-700 mb-2">
                                Choose a sample:
                            </label>
                            <select id="demo-selector" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                ${demoFiles.map(file => 
                                    `<option value="${file.id}" data-name="${file.name}" data-filename="${file.filename || ''}" data-description="${file.description || ''}" data-language="${file.language || 'Unknown'}" data-duration="${file.duration || 'Unknown'}">
                                        ${file.name}
                                    </option>`
                                ).join('')}
                            </select>
                        </div>
                    </div>
                    
                    <!-- Demo file details (will be updated when selection changes) -->
                    <div id="demo-details" class="bg-white rounded-lg p-4 border border-gray-200">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                            <div>
                                <span class="font-medium text-gray-600">Language:</span>
                                <span id="demo-language" class="ml-2 text-gray-800">${demoFiles[0]?.language || 'Unknown'}</span>
                            </div>
                            <div>
                                <span class="font-medium text-gray-600">Duration:</span>
                                <span id="demo-duration" class="ml-2 text-gray-800">${demoFiles[0]?.duration || 'Unknown'}</span>
                            </div>
                            <div>
                                <span class="font-medium text-gray-600">Status:</span>
                                <span class="ml-2 px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">Ready</span>
                            </div>
                        </div>
                        <div class="mt-3">
                            <span class="font-medium text-gray-600">Description:</span>
                            <p id="demo-description" class="mt-1 text-gray-700">${demoFiles[0]?.description || 'Demo audio file for testing'}</p>
                        </div>
                    </div>
                    
                    <!-- Audio Preview and Processing -->
                    <div class="mt-4 space-y-4">
                        <!-- Audio Preview -->
                        <div class="bg-white rounded-lg p-4 border border-gray-200">
                            <h4 class="text-sm font-medium text-gray-700 mb-3">
                                <i class="fas fa-headphones mr-2"></i>Audio Preview
                            </h4>
                            <audio id="demo-audio-player" controls class="w-full mb-3">
                                <source id="demo-audio-source" type="audio/mpeg">
                                Your browser does not support the audio element.
                            </audio>
                            <!-- Waveform Visualization -->
                            <div id="demo-waveform-container" class="mt-3">
                                <canvas id="demo-waveform-canvas" class="w-full h-16 bg-gray-50 rounded border"></canvas>
                            </div>
                        </div>
                        
                        <!-- Demo Results Section -->
                        <div class="flex justify-center">
                            <button onclick="loadDemoResults()" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors">
                                <i class="fas fa-eye mr-2"></i>View Processing Results
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            demoContainer.innerHTML = selectorHTML;
            container.appendChild(demoContainer);
            
            // Add event listener for dropdown changes
            const selector = document.getElementById('demo-selector');
            if (selector) {
                selector.addEventListener('change', function() {
                    const selectedOption = this.options[this.selectedIndex];
                    updateDemoDetails(selectedOption);
                    loadDemoAudio(this.value, selectedOption.dataset.filename || selectedOption.dataset.name);
                });
                
                // Load initial demo audio
                if (selector.options.length > 0) {
                    const firstOption = selector.options[0];
                    loadDemoAudio(selector.value, firstOption.dataset.name);
                }
            }
            
            console.log('βœ… Demo files populated successfully');
        }
        
        // Update demo file details when selection changes
        function updateDemoDetails(selectedOption) {
            const languageEl = document.getElementById('demo-language');
            const durationEl = document.getElementById('demo-duration');
            const descriptionEl = document.getElementById('demo-description');
            
            if (languageEl) languageEl.textContent = selectedOption.dataset.language || 'Unknown';
            if (durationEl) durationEl.textContent = selectedOption.dataset.duration || 'Unknown';
            if (descriptionEl) descriptionEl.textContent = selectedOption.dataset.description || 'Demo audio file for testing';
            
            console.log('βœ… Updated demo details for:', selectedOption.dataset.name);
        }
        
        // Load demo audio for preview
        function loadDemoAudio(demoId, fileName) {
            console.log('🎡 Loading demo audio:', demoId, fileName);
            
            const audioPlayer = document.getElementById('demo-audio-player');
            const audioSource = document.getElementById('demo-audio-source');
            const waveformCanvas = document.getElementById('demo-waveform-canvas');
            
            if (!audioPlayer || !audioSource || !waveformCanvas) {
                console.warn('⚠️ Demo audio elements not found');
                return;
            }
            
            // Get actual filename from demo files data or use the provided fileName
            let actualFileName = fileName;
            
            // Get actual filename from demo files data or use mapping
            if (demoFiles && demoFiles.length > 0) {
                const demoFile = demoFiles.find(file => file.id === demoId);
                if (demoFile && demoFile.filename) {
                    actualFileName = demoFile.filename;
                }
            } else {
                // Fallback mapping
                const filenameMap = {
                    'yuri_kizaki': 'Yuri_Kizaki.mp3',
                    'film_podcast': 'Film_Podcast.mp3', 
                    'car_trouble': 'Car_Trouble.mp3',
                    'tamil_interview': 'Tamil_Wikipedia_Interview.ogg'
                };
                
                if (filenameMap[demoId]) {
                    actualFileName = filenameMap[demoId];
                }
            }
            
            console.log(`🎡 Mapped ${demoId} -> ${actualFileName}`);
            
            // Set audio source using the server route
            const audioPath = `/demo_audio/${actualFileName}`;
            
            console.log(`πŸ” Loading audio from: ${audioPath}`);
            
            // Set the audio source directly
            audioSource.src = audioPath;
            audioPlayer.load();
            
            // Handle audio loading events
            const onCanPlay = function() {
                console.log('βœ… Demo audio loaded successfully');
                generateWaveformFromAudio(audioPlayer, waveformCanvas, audioSource);
                audioPlayer.removeEventListener('canplaythrough', onCanPlay);
                audioPlayer.removeEventListener('error', onError);
            };
            
            const onError = function() {
                console.warn(`❌ Failed to load audio: ${audioPath}`);
                console.log(`⚠️ Generating placeholder waveform for: ${actualFileName}`);
                generateDemoWaveform(waveformCanvas, actualFileName);
                audioPlayer.removeEventListener('canplaythrough', onCanPlay);
                audioPlayer.removeEventListener('error', onError);
            };
            
            audioPlayer.addEventListener('canplaythrough', onCanPlay);
            audioPlayer.addEventListener('error', onError);
        }

        
        // Generate demo waveform placeholder

        
        // Load demo results - shows pre-processed results for selected demo file
        async function loadDemoResults() {
            const selector = document.getElementById('demo-selector');
            if (!selector || !selector.value) {
                alert('Please select a demo audio file first.');
                return;
            }
            
            const demoId = selector.value;
            console.log('🎯 Loading demo results for:', demoId);
            
            try {
                // Show loading state
                showProgress();
                const progressBar = document.querySelector('.progress-bar-fill');
                if (progressBar) progressBar.style.width = '50%';
                
                // Fetch demo results
                const response = await fetch(`/api/process-demo/${demoId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                console.log('πŸ“‹ Demo results received:', result);
                
                // Complete progress
                if (progressBar) progressBar.style.width = '100%';
                
                setTimeout(() => {
                    if (result.status === 'complete') {
                        showResults(result.results);
                    } else {
                        throw new Error('Demo processing failed: ' + (result.error || 'Unknown error'));
                    }
                }, 500); // Brief delay to show completion
                
            } catch (error) {
                console.error('❌ Demo results error:', error);
                alert('Error loading demo results: ' + error.message);
                
                // Hide progress on error
                const progressSection = document.getElementById('progress-section');
                if (progressSection) progressSection.classList.add('hidden');
            }
        }
        
        // Process audio (unified function for both demo and full modes)
        function processAudio() {
            console.log('🎯 Processing audio...');
            
            // Check if we're in demo mode and handle accordingly
            if (isDemoMode) {
                const selector = document.getElementById('demo-selector');
                if (!selector) {
                    alert('Demo selector not found');
                    return;
                }
                
                const selectedId = selector.value;
                const selectedOption = selector.options[selector.selectedIndex];
                const fileName = selectedOption.dataset.name;
                
                console.log('🎯 Processing demo file:', selectedId, fileName);
            }
            
            // Submit the form (this will trigger the existing form submission logic)
            const uploadForm = document.getElementById('upload-form');
            if (uploadForm) {
                uploadForm.dispatchEvent(new Event('submit'));
            } else {
                alert('Upload form not found');
            }
        }
            
            console.log('Demo files population completed');
        
        // Utility functions for demo file status
        function getStatusClass(status) {
            switch(status) {
                case 'ready': return 'bg-green-100 text-green-800';
                case 'processing': return 'bg-yellow-100 text-yellow-800';
                case 'downloading': return 'bg-blue-100 text-blue-800';
                case 'error': return 'bg-red-100 text-red-800';
                default: return 'bg-gray-100 text-gray-800';
            }
        }
        
        function getStatusText(status) {
            switch(status) {
                case 'ready': return 'βœ… Ready';
                case 'processing': return '⏳ Processing';
                case 'downloading': return '⬇️ Downloading';
                case 'error': return '❌ Error';
                default: return 'βšͺ Unknown';
            }
        }
        
        function getIconForLanguage(language) {
            const lang = language.toLowerCase();
            if (lang.includes('japanese') || lang.includes('ja')) return 'fas fa-flag';
            if (lang.includes('french') || lang.includes('fr')) return 'fas fa-flag';
            if (lang.includes('tamil') || lang.includes('ta')) return 'fas fa-flag';
            if (lang.includes('hindi') || lang.includes('hi')) return 'fas fa-flag';
            return 'fas fa-globe';
        }
        
        // Session management and cleanup
        function triggerCleanup() {
            // Send cleanup request (only for non-demo mode)
            if (isDemoMode) {
                console.log('🎯 Skipping cleanup in demo mode');
                return;
            }
            
            console.log('🧹 Triggering session cleanup...');
            fetch('/api/cleanup', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(response => {
                if (response.ok) {
                    console.log('βœ… Session cleanup completed');
                } else {
                    console.warn('⚠️ Session cleanup failed');
                }
            }).catch(error => {
                console.warn('⚠️ Session cleanup error:', error);
            });
        }
        
        // Auto-cleanup on page unload/refresh (only for non-demo mode)
        window.addEventListener('beforeunload', function(event) {
            // Only cleanup if we're not in demo mode and have actually uploaded files
            if (!isDemoMode && currentTaskId) {
                triggerCleanup();
            }
        });
        
        // Cleanup when results are fully displayed and user has had time to view them
        let cleanupScheduled = false;
        function scheduleDelayedCleanup() {
            if (cleanupScheduled) return;
            cleanupScheduled = true;
            
            // Wait 10 minutes after processing completes before cleanup
            setTimeout(function() {
                if (!isDemoMode) {
                    console.log('πŸ•’ Scheduled cleanup after results display');
                    triggerCleanup();
                }
                cleanupScheduled = false;
            }, 10 * 60 * 1000); // 10 minutes
        }
        
        // Periodic cleanup check (much less frequent)
        setInterval(function() {
            // Only check session info, don't auto-cleanup unless really necessary
            fetch('/api/session-info')
                .then(response => response.json())
                .then(data => {
                    console.log('πŸ“Š Session info:', data);
                    // Only auto-cleanup if session has been inactive for over 2 hours
                    const now = Date.now() / 1000;
                    if (data.last_activity && (now - data.last_activity) > 7200) { // 2 hours
                        console.log('πŸ•’ Auto-cleanup due to long inactivity');
                        triggerCleanup();
                    }
                })
                .catch(error => {
                    console.warn('⚠️ Failed to get session info:', error);
                });
        }, 60 * 60 * 1000); // Check every hour
        
        // Manual cleanup button (could be added to UI if needed)
        function manualCleanup() {
            triggerCleanup();
            alert('🧹 Session cleanup requested. Your uploaded files have been removed from the server.');
        }
        // Live waveform visualization setup
        function setupLiveWaveformVisualization() {
            console.log('🎯 Setting up live waveform visualization');
            
            // Setup for demo mode
            const demoAudioPlayer = document.getElementById('demo-audio-player');
            const demoCanvas = document.getElementById('demo-waveform-canvas');
            
            if (demoAudioPlayer && demoCanvas) {
                console.log('🎡 Setting up demo audio visualization');
                setupAudioVisualization(demoAudioPlayer, demoCanvas, 'demo');
            } else {
                console.log('⚠️ Demo audio elements not found');
            }
            
            // Setup for full processing mode (look for any audio elements)
            const audioElements = document.querySelectorAll('audio');
            const canvasElements = document.querySelectorAll('canvas[id*="waveform"]');
            
            audioElements.forEach((audio, index) => {
                if (audio.id !== 'demo-audio-player') {
                    const canvas = canvasElements[index] || document.getElementById('waveform-canvas');
                    if (canvas) {
                        console.log('🎡 Setting up full mode audio visualization');
                        setupAudioVisualization(audio, canvas, 'full');
                    }
                }
            });
        }
        
        function setupAudioVisualization(audioElement, canvas, mode) {
            console.log(`πŸ”§ Setting up audio visualization for ${mode} mode`);
            
            let animationId = null;
            let audioContext = null;
            let analyser = null;
            let dataArray = null;
            let source = null;
            
            // Clean up any existing listeners
            const existingListeners = audioElement._visualizationListeners;
            if (existingListeners) {
                audioElement.removeEventListener('play', existingListeners.play);
                audioElement.removeEventListener('pause', existingListeners.pause);
                audioElement.removeEventListener('ended', existingListeners.ended);
            }
            
            // Create new listeners
            const playListener = async () => {
                try {
                    console.log(`🎡 ${mode} audio started playing`);
                    
                    if (!audioContext) {
                        audioContext = new (window.AudioContext || window.webkitAudioContext)();
                        console.log('🎯 Created new AudioContext');
                    }
                    
                    if (!source) {
                        source = audioContext.createMediaElementSource(audioElement);
                        analyser = audioContext.createAnalyser();
                        analyser.fftSize = 256;
                        analyser.smoothingTimeConstant = 0.8;
                        
                        source.connect(analyser);
                        analyser.connect(audioContext.destination);
                        
                        const bufferLength = analyser.frequencyBinCount;
                        dataArray = new Uint8Array(bufferLength);
                        console.log('πŸ”— Connected audio source to analyser');
                    }
                    
                    if (audioContext.state === 'suspended') {
                        await audioContext.resume();
                        console.log('▢️ Resumed AudioContext');
                    }
                    
                    startLiveVisualization();
                    console.log(`βœ… Live visualization started for ${mode} mode`);
                } catch (error) {
                    console.warn('⚠️ Web Audio API not available for live visualization:', error);
                    // Fallback to static visualization
                    drawStaticWaveform();
                }
            };
            
            const pauseListener = () => {
                console.log(`⏸️ ${mode} audio paused`);
                stopLiveVisualization();
            };
            
            const endedListener = () => {
                console.log(`⏹️ ${mode} audio ended`);
                stopLiveVisualization();
                // Only draw static waveform for demo mode, not for full processing mode
                // if (mode === 'demo') {
                //     drawStaticWaveform();
                // }
            };
            
            // Add listeners
            audioElement.addEventListener('play', playListener);
            audioElement.addEventListener('pause', pauseListener);
            audioElement.addEventListener('ended', endedListener);
            
            // Store references for cleanup
            audioElement._visualizationListeners = {
                play: playListener,
                pause: pauseListener,
                ended: endedListener
            };
            
            // Draw initial static waveform
            drawStaticWaveform();
            
            function drawStaticWaveform() {
                if (!canvas) return;
                
                const ctx = canvas.getContext('2d');
                const canvasWidth = canvas.offsetWidth || 800;
                const canvasHeight = canvas.offsetHeight || 64;
                
                // Set canvas resolution
                canvas.width = canvasWidth * window.devicePixelRatio;
                canvas.height = canvasHeight * window.devicePixelRatio;
                ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
                
                // Clear canvas
                ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                
                // Draw static waveform (blue)
                const barCount = 100;
                const barWidth = canvasWidth / barCount;
                
                ctx.fillStyle = '#3B82F6'; // Blue color for static waveform
                
                for (let i = 0; i < barCount; i++) {
                    // Generate realistic static waveform pattern
                    const normalizedIndex = i / barCount;
                    const amplitude = Math.sin(normalizedIndex * Math.PI * 4) * 0.3 + 
                                    Math.sin(normalizedIndex * Math.PI * 8) * 0.2 + 
                                    Math.random() * 0.1;
                    const barHeight = Math.max(2, Math.abs(amplitude) * canvasHeight * 0.8);
                    
                    const x = i * barWidth;
                    const y = (canvasHeight - barHeight) / 2;
                    
                    ctx.fillRect(x, y, barWidth - 1, barHeight);
                }
                
                console.log(`πŸ“Š Drew static waveform on ${mode} canvas`);
            }
            
            function startLiveVisualization() {
                if (!analyser || !dataArray) {
                    console.warn('⚠️ Analyser or dataArray not available for live visualization');
                    return;
                }
                
                const ctx = canvas.getContext('2d');
                const canvasWidth = canvas.offsetWidth || 800;
                const canvasHeight = canvas.offsetHeight || 64;
                
                // Set canvas resolution
                canvas.width = canvasWidth * window.devicePixelRatio;
                canvas.height = canvasHeight * window.devicePixelRatio;
                ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
                
                console.log(`🎬 Starting live animation for ${mode} canvas (${canvasWidth}x${canvasHeight})`);
                
                function animate() {
                    if (!analyser || !dataArray) return;
                    
                    analyser.getByteFrequencyData(dataArray);
                    
                    // Clear canvas
                    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                    
                    // Draw live waveform (green)
                    const barCount = 100;
                    const barWidth = canvasWidth / barCount;
                    
                    ctx.fillStyle = '#10B981'; // Green color for live visualization
                    
                    for (let i = 0; i < barCount; i++) {
                        const dataIndex = Math.floor((i / barCount) * dataArray.length);
                        const barHeight = Math.max(2, (dataArray[dataIndex] / 255) * canvasHeight * 0.8);
                        
                        const x = i * barWidth;
                        const y = (canvasHeight - barHeight) / 2;
                        
                        ctx.fillRect(x, y, barWidth - 1, barHeight);
                    }
                    
                    animationId = requestAnimationFrame(animate);
                }
                
                animate();
            }
            
            function stopLiveVisualization() {
                if (animationId) {
                    cancelAnimationFrame(animationId);
                    animationId = null;
                    console.log(`⏹️ Stopped live visualization for ${mode} mode`);
                }
            }
        }

        // Initialize live visualization when page loads
        document.addEventListener('DOMContentLoaded', () => {
            console.log('πŸš€ DOM loaded, setting up waveform visualization');
            setupLiveWaveformVisualization();
            
            // Also setup when new audio elements are added dynamically
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    mutation.addedNodes.forEach((node) => {
                        if (node.nodeType === 1) { // Element node
                            const audioElements = node.querySelectorAll ? node.querySelectorAll('audio') : [];
                            const canvasElements = node.querySelectorAll ? node.querySelectorAll('canvas[id*="waveform"]') : [];
                            
                            if (node.tagName === 'AUDIO' || audioElements.length > 0 || canvasElements.length > 0) {
                                console.log('πŸ”„ New audio/canvas elements detected, reinitializing visualization');
                                setTimeout(setupLiveWaveformVisualization, 500);
                            }
                        }
                    });
                });
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        });

    </script>
</body>
</html>