File size: 36,368 Bytes
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
19933fe
 
 
 
 
 
 
1c7725b
19933fe
 
 
 
 
 
 
1c7725b
19933fe
 
 
1c7725b
 
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
 
 
1c7725b
 
19933fe
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
 
 
1c7725b
19933fe
 
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
 
19933fe
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
1c7725b
 
 
 
 
 
 
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
1c7725b
 
 
 
 
 
 
 
 
19933fe
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
 
1c7725b
19933fe
 
 
1c7725b
 
 
 
 
 
 
 
 
19933fe
1c7725b
19933fe
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
 
 
 
 
1c7725b
 
19933fe
 
 
 
 
 
 
1c7725b
 
 
 
19933fe
 
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
 
 
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
19933fe
 
1c7725b
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
19933fe
 
1c7725b
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
19933fe
1c7725b
 
 
19933fe
1c7725b
 
 
 
 
 
 
 
 
19933fe
 
 
 
 
 
 
 
1c7725b
19933fe
 
 
1c7725b
19933fe
 
 
1c7725b
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
 
 
 
19933fe
 
 
1c7725b
 
 
 
19933fe
1c7725b
19933fe
1c7725b
19933fe
 
 
 
 
 
1c7725b
19933fe
1c7725b
19933fe
 
 
 
 
 
1c7725b
 
 
19933fe
1c7725b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19933fe
1c7725b
 
 
 
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
19933fe
 
 
 
 
 
 
 
 
1c7725b
 
 
 
19933fe
1c7725b
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
 
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
19933fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
19933fe
 
 
1c7725b
 
 
 
 
 
 
 
19933fe
 
 
 
 
 
1c7725b
 
 
19933fe
 
 
 
 
 
 
 
 
 
 
1c7725b
 
 
 
 
 
 
 
 
19933fe
1c7725b
19933fe
 
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
/**
 * Talking Snake - Main Application Script
 * Handles file upload, URL submission, and audio streaming
 */

// DOM Elements
const dropZone = document.getElementById("dropZone");
const fileInput = document.getElementById("fileInput");
const urlInput = document.getElementById("urlInput");
const urlSubmit = document.getElementById("urlSubmit");
const textInput = document.getElementById("textInput");
const textSubmit = document.getElementById("textSubmit");
const status = document.getElementById("status");
const player = document.getElementById("player");
const audio = document.getElementById("audio");
const filename = document.getElementById("filename");
const tabs = document.querySelectorAll(".tab");
const tabContents = document.querySelectorAll(".tab-content");
const inputSection = document.getElementById("inputSection");
const processingSection = document.getElementById("processingSection");
const stopBtn = document.getElementById("stopBtn");
const pauseBtn = document.getElementById("pauseBtn");
const deviceInfo = document.getElementById("deviceInfo");
const docInfo = document.getElementById("docInfo");
const languageButtons = document.querySelectorAll("#languageButtons .style-btn");
const processingProgressBar = document.getElementById("processingProgressBar");
const streamPlayBtn = document.getElementById("streamPlayBtn");

// Custom player elements
const playerPlayBtn = document.getElementById("playerPlayBtn");
const progressBar = document.getElementById("progressBar");
const progressSlider = document.getElementById("progressSlider");
const timeDisplay = document.getElementById("timeDisplay");
const downloadBtn = document.getElementById("downloadBtn");
const deleteBtn = document.getElementById("deleteBtn");

// Constants
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB

// State
let currentAbortController = null;
let selectedLanguage = "english";
let selectedStyle = "technical";
let isPaused = false;
let estimatedDuration = 0; // Estimated total duration from server
let currentDocName = ""; // Store document name for download filename
let playbackStartTime = 0; // When playback started (for tracking real elapsed time)
let playbackElapsed = 0; // Total elapsed playback time

/**
 * Format time in seconds to MM:SS
 */
function formatTime(seconds) {
    if (!isFinite(seconds) || seconds < 0) {
        return "0:00";
    }
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, "0")}`;
}

/**
 * Format a number in human-readable form (1.2K, 3.4M, etc.)
 */
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1).replace(/\.0$/, "") + "M";
    }
    if (num >= 1000) {
        return (num / 1000).toFixed(1).replace(/\.0$/, "") + "K";
    }
    return num.toString();
}

/**
 * Get icon for document type
 */
function getDocTypeIcon(docType) {
    switch (docType) {
        case "pdf": return "fa-file-pdf";
        case "url": return "fa-link";
        case "text": return "fa-file-lines";
        default: return "fa-file";
    }
}

/**
 * Update the document info display
 */
function updateDocInfo(data) {
    const icon = getDocTypeIcon(data.doc_type);
    const docName = data.doc_name || "Document";
    const pageInfo = data.page_count ? `<span class="doc-pages"><i class="fa-solid fa-file"></i> ${data.page_count}p</span>` : "";
    const charInfo = data.total_chars ? `<span class="doc-chars"><i class="fa-solid fa-font"></i> ${formatNumber(data.total_chars)}</span>` : "";

    // Style icons mapping
    const styleIcons = {
        technical: "fa-microchip",
        narrative: "fa-book-open",
        child_narrative: "fa-child",
        news: "fa-newspaper",
        academic: "fa-graduation-cap"
    };

    // Language flags mapping
    const langFlags = {
        english: "πŸ‡¬πŸ‡§",
        chinese: "πŸ‡¨πŸ‡³",
        japanese: "πŸ‡―πŸ‡΅",
        korean: "πŸ‡°πŸ‡·"
    };

    const styleIcon = styleIcons[selectedStyle] || "fa-microchip";
    const langFlag = langFlags[selectedLanguage] || "πŸ‡¬πŸ‡§";

    docInfo.innerHTML = `
        <span class="doc-name" title="${docName}"><i class="fa-solid ${icon}"></i><span class="doc-name-text">${docName}</span></span>
        ${pageInfo}
        ${charInfo}
        <span class="doc-style" title="Style: ${selectedStyle}"><i class="fa-solid ${styleIcon}"></i></span>
        <span class="doc-lang" title="Language: ${selectedLanguage}">${langFlag}</span>
    `;
}

/**
 * Update the custom player progress bar and time display
 */
function updatePlayerProgress() {
    // For streaming WAV, browser's duration/currentTime are unreliable
    // Track real playback time ourselves
    let currentTime;
    if (playbackStartTime > 0 && !audio.paused) {
        currentTime = playbackElapsed + (Date.now() - playbackStartTime) / 1000;
    } else {
        currentTime = playbackElapsed;
    }

    // Use our estimated duration, update it if playback exceeds estimate
    let duration = estimatedDuration;
    if (currentTime > duration) {
        estimatedDuration = currentTime + 10; // Extend estimate
        duration = estimatedDuration;
    }

    // Ensure we have reasonable values
    if (duration <= 0) {
        duration = 60; // Fallback
    }

    const progress = duration > 0 ? (currentTime / duration) * 100 : 0;
    progressBar.style.width = `${Math.min(progress, 100)}%`;
    progressSlider.value = Math.min(progress, 100);
    timeDisplay.textContent = `${formatTime(currentTime)} / ${formatTime(duration)}`;
}

/**
 * Handle seeking via the progress slider
 */
function handleSeek(e) {
    const percent = parseFloat(e.target.value);
    const duration = estimatedDuration || 60;
    const seekTime = (percent / 100) * duration;

    // Set our playback tracker
    playbackElapsed = seekTime;
    playbackStartTime = audio.paused ? 0 : Date.now();

    // Try to seek the audio (may not work well with streaming)
    try {
        audio.currentTime = seekTime;
    } catch {
        // Seeking may fail with streaming audio
    }
    updatePlayerProgress();
}

/**
 * Toggle play/pause for custom player
 */
function togglePlayerPlay() {
    if (audio.paused) {
        audio.play().catch(() => {});
    } else {
        audio.pause();
    }
}

/**
 * Update play button icon
 */
function updatePlayButton() {
    const icon = playerPlayBtn.querySelector("i");
    if (audio.paused) {
        icon.className = "fa-solid fa-play";
    } else {
        icon.className = "fa-solid fa-pause";
    }
}

/**
 * Get HTML for model state indicator
 * @param {string} state - Model state: loaded, loading, unloaded, unloading
 * @returns {string} HTML string for the model state indicator
 */
function getModelStateHtml(state) {
    const stateConfig = {
        loaded: {
            icon: "fa-circle-check",
            class: "model-loaded",
            text: "Model loaded",
            tooltip: "TTS model is loaded in memory and ready for inference"
        },
        loading: {
            icon: "fa-spinner fa-spin",
            class: "model-loading",
            text: "Loading...",
            tooltip: "TTS model is being loaded into memory"
        },
        unloaded: {
            icon: "fa-circle-xmark",
            class: "model-unloaded",
            text: "Model unloaded",
            tooltip: "TTS model is not loaded (will load on first request)"
        },
        unloading: {
            icon: "fa-spinner fa-spin",
            class: "model-unloading",
            text: "Unloading...",
            tooltip: "TTS model is being unloaded from memory"
        }
    };
    const config = stateConfig[state] || stateConfig.unloaded;
    return `<span class="model-state ${config.class}" title="${config.tooltip}"><i class="fa-solid ${config.icon}"></i> ${config.text}</span>`;
}

/**
 * Update device info display from SSE data
 * @param {Object} info - Device info object
 */
function updateDeviceInfo(info) {
    const icon = info.device === "cuda" ? "fa-microchip" : "fa-server";
    const deviceTooltip = info.device === "cuda"
        ? "GPU accelerated inference for faster audio generation"
        : "CPU-based inference (slower than GPU)";
    const gpuMemoryInfo = info.device === "cuda"
        ? `<span class="device-memory" title="GPU memory used for model and inference"><i class="fa-solid fa-memory"></i> GPU: ${info.memory_used_gb}/${info.memory_total_gb}GB</span>`
        : "";
    const ramInfo = `<span class="device-memory" title="System RAM usage"><i class="fa-solid fa-memory"></i> RAM: ${info.ram_used_gb}/${info.ram_total_gb}GB</span>`;
    // Show timing stats if available
    const timingInfo = info.seconds_per_char !== undefined
        ? `<span class="device-timing" title="Average time to generate audio per character of text"><i class="fa-solid fa-stopwatch"></i> ${info.seconds_per_char.toFixed(4)}s/char</span>`
        : "";
    // Show model state
    const modelStateInfo = getModelStateHtml(info.model_state);
    deviceInfo.innerHTML = `
        <i class="fa-solid ${icon}" title="${deviceTooltip}"></i>
        <span title="${deviceTooltip}">${info.device_name}</span>
        ${modelStateInfo}
        ${gpuMemoryInfo}
        ${ramInfo}
        ${timingInfo}
        <span class="device-ephemeral" title="Your documents are processed in memory only. Nothing is saved to disk or stored after processing."><i class="fa-solid fa-shield-halved"></i> No files stored</span>
    `;
    deviceInfo.classList.add("visible");
}

/**
 * Initialize device info SSE stream
 */
function initDeviceInfoStream() {
    const eventSource = new EventSource("/api/device-info-stream");

    eventSource.onmessage = (event) => {
        try {
            const info = JSON.parse(event.data);
            updateDeviceInfo(info);
        } catch {
            // Silently fail - device info is optional
        }
    };

    eventSource.onerror = () => {
        // On error, close and try to reconnect after a delay
        eventSource.close();
        setTimeout(initDeviceInfoStream, 5000);
    };
}

// Start device info SSE stream
initDeviceInfoStream();

// Custom player event listeners
playerPlayBtn.addEventListener("click", togglePlayerPlay);
progressSlider.addEventListener("input", handleSeek);
audio.addEventListener("play", () => {
    // Start tracking real playback time
    playbackStartTime = Date.now();
    updatePlayButton();
});
audio.addEventListener("pause", () => {
    // Save elapsed time when pausing
    if (playbackStartTime > 0) {
        playbackElapsed += (Date.now() - playbackStartTime) / 1000;
        playbackStartTime = 0;
    }
    updatePlayButton();
});
audio.addEventListener("timeupdate", updatePlayerProgress);
audio.addEventListener("ended", () => {
    // Update elapsed to match duration on completion
    if (playbackStartTime > 0) {
        playbackElapsed += (Date.now() - playbackStartTime) / 1000;
        playbackStartTime = 0;
    }
    // Ensure we show completion
    if (estimatedDuration > 0 && playbackElapsed < estimatedDuration) {
        playbackElapsed = estimatedDuration;
    }
    updatePlayButton();
    progressBar.style.width = "100%";
    timeDisplay.textContent = `${formatTime(estimatedDuration)} / ${formatTime(estimatedDuration)}`;
});
// Update duration when metadata is available
audio.addEventListener("loadedmetadata", () => {
    // If browser has a valid duration, use it instead of estimate
    if (isFinite(audio.duration) && audio.duration > 0 && audio.duration < 36000) {
        estimatedDuration = audio.duration;
    }
    updatePlayerProgress();
});
// Also check duration changes (for streaming audio)
audio.addEventListener("durationchange", () => {
    if (isFinite(audio.duration) && audio.duration > 0 && audio.duration < 36000) {
        estimatedDuration = audio.duration;
    }
    updatePlayerProgress();
});
// Log audio errors for debugging
audio.addEventListener("error", () => {
    console.error("Audio error:", audio.error?.message || "Unknown error");
});
// Show pause button when audio actually starts playing
audio.addEventListener("playing", () => {
    streamPlayBtn.classList.add("hidden");
    pauseBtn.classList.remove("hidden");
});

// Show stream play button when audio has enough data to start playing
audio.addEventListener("canplay", () => {
    // Only show if processing is still in progress (player not visible yet)
    // and audio is paused (not already playing) and pause button isn't showing
    if (!player.classList.contains("visible") && audio.paused && pauseBtn.classList.contains("hidden")) {
        streamPlayBtn.classList.remove("hidden");
    }
});

/**
 * Start streaming audio playback and enable download from cache
 * @param {string} jobId - The job ID for the audio
 */
async function startAudioStream(jobId) {
    const audioUrl = `/api/audio/${jobId}`;

    // Reset playback tracking for new stream
    playbackStartTime = 0;
    playbackElapsed = 0;

    // Set up audio source for streaming (user can click play)
    audio.src = audioUrl;
    audio.load();

    // Store job ID for download - will fetch from cache
    audio.dataset.jobId = jobId;

    // Play button will be shown by the canplay event handler
}

/**
 * Download the current audio as a WAV file
 */
function downloadAudio() {
    const jobId = audio.dataset.jobId;
    if (!jobId) {
        return;
    }

    // Create filename from document name
    let filename = currentDocName || "audio";
    filename = filename.replace(/\.[^.]+$/, "") + ".wav";

    // Use download endpoint which returns proper WAV file
    const a = document.createElement("a");
    a.href = `/api/download/${jobId}?filename=${encodeURIComponent(filename)}`;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

/**
 * Delete the current audio and reset the player
 */
function deleteAudio() {
    // Stop audio immediately
    audio.pause();

    // Add deleting animation
    player.classList.add("deleting");

    // Wait for animation to complete
    setTimeout(() => {
        // Reset audio
        audio.src = "";
        audio.currentTime = 0;

        // Clear state
        currentDocName = "";
        estimatedDuration = 0;

        // Hide player and buttons
        player.classList.remove("visible", "deleting");
        downloadBtn.classList.add("hidden");
        deleteBtn.classList.add("hidden");

        // Reset progress
        progressBar.style.width = "0%";
        progressSlider.value = 0;
        timeDisplay.textContent = "0:00 / 0:00";
        updatePlayButton();

        // Show input section again
        inputSection.classList.remove("hidden");
    }, 300);
}

/**
 * Get the currently selected language
 * @returns {string} The selected language name
 */
function getSelectedLanguage() {
    return selectedLanguage;
}

/**
 * Detect language from text based on character scripts.
 * @param {string} text - The text to analyze
 * @returns {string|null} Detected language or null if mostly ASCII/Latin
 */
function detectLanguage(text) {
    if (!text || text.length < 5) {
        return null;
    }

    let chinese = 0;
    let japanese = 0; // Hiragana + Katakana
    let korean = 0;
    let latin = 0;

    for (const char of text) {
        const code = char.charCodeAt(0);
        // CJK Unified Ideographs (shared by Chinese/Japanese)
        if (code >= 0x4e00 && code <= 0x9fff) {
            chinese++;
        }
        // Hiragana
        else if (code >= 0x3040 && code <= 0x309f) {
            japanese++;
        }
        // Katakana
        else if (code >= 0x30a0 && code <= 0x30ff) {
            japanese++;
        }
        // Hangul Syllables
        else if (code >= 0xac00 && code <= 0xd7af) {
            korean++;
        }
        // Hangul Jamo
        else if (code >= 0x1100 && code <= 0x11ff) {
            korean++;
        }
        // Basic Latin letters
        else if (
            (code >= 0x41 && code <= 0x5a) ||
            (code >= 0x61 && code <= 0x7a)
        ) {
            latin++;
        }
    }

    const total = chinese + japanese + korean + latin;
    if (total === 0) {
        return null;
    }

    // Japanese uses kanji (chinese chars) + kana, so check for kana first
    if (japanese > 0 && (japanese + chinese) / total > 0.3) {
        return "japanese";
    }
    // Korean
    if (korean / total > 0.3) {
        return "korean";
    }
    // Chinese (CJK without kana)
    if (chinese / total > 0.3) {
        return "chinese";
    }
    // Default to English for Latin text
    if (latin / total > 0.5) {
        return "english";
    }
    return null;
}

/**
 * Set the selected language, optionally marking it as auto-detected.
 * @param {string} lang - Language to select
 * @param {boolean} isAuto - Whether this was auto-detected
 */
function setLanguage(lang, isAuto = false) {
    const btn = document.querySelector(
        `#languageButtons .style-btn[data-language="${lang}"]`
    );
    if (!btn || selectedLanguage === lang) {
        return;
    }

    // Update selection state
    languageButtons.forEach((b) => {
        b.classList.remove("active", "auto-detected");
    });
    btn.classList.add("active");
    selectedLanguage = lang;

    // Visual feedback for auto-detection
    if (isAuto) {
        btn.classList.add("auto-detected");
        // Remove animation class after it completes
        setTimeout(() => btn.classList.remove("auto-detected"), 1500);
    }
}

/**
 * Get the currently selected style
 * @returns {string} The selected style ID
 */
function getSelectedStyle() {
    return selectedStyle;
}

/**
 * Show the input section and hide processing section
 */
function showInputSection() {
    inputSection.classList.remove("hidden");
    processingSection.classList.remove("visible");
}

/**
 * Show the processing section and hide input section
 */
function showProcessingSection() {
    inputSection.classList.add("hidden");
    processingSection.classList.add("visible");
    // Reset progress bar and hide buttons
    processingProgressBar.style.width = "0%";
    pauseBtn.classList.add("hidden");
    streamPlayBtn.classList.add("hidden");
}

/**
 * Show a status message to the user
 * @param {string} message - HTML message to display
 * @param {string} type - Status type: 'loading', 'error', or 'success'
 */
function showStatus(message, type) {
    status.innerHTML = message;
    status.className = `status visible ${type}`;
}

/**
 * Stop the current generation and audio playback
 */
function stopGeneration() {
    // Stop the fetch request
    if (currentAbortController) {
        currentAbortController.abort();
        currentAbortController = null;
    }

    // Stop audio playback and clear source
    audio.pause();
    audio.currentTime = 0;
    audio.src = "";
    audio.load(); // Force release of audio resources

    // Reset pause state
    isPaused = false;
    updatePauseButton();

    // Hide download button, pause button, and stream play button
    downloadBtn.classList.add("hidden");
    pauseBtn.classList.add("hidden");
    streamPlayBtn.classList.add("hidden");

    // Reset progress bar
    processingProgressBar.style.width = "0%";

    showStatus('<i class="fa-solid fa-ban"></i> Generation stopped', "error");
    showInputSection();
}

// Stop audio when page is closed or navigated away
window.addEventListener("beforeunload", () => {
    audio.pause();
    audio.src = "";
});

// Also handle page hide (works better on mobile and for navigation)
window.addEventListener("pagehide", () => {
    audio.pause();
    audio.src = "";
});

/**
 * Toggle pause/play state
 */
function togglePause() {
    if (audio.paused) {
        audio.play().catch(() => {});
        isPaused = false;
    } else {
        audio.pause();
        isPaused = true;
    }
    updatePauseButton();
}

/**
 * Update pause button icon based on state
 */
function updatePauseButton() {
    const icon = pauseBtn.querySelector("i");
    if (isPaused || audio.paused) {
        icon.className = "fa-solid fa-play";
        pauseBtn.title = "Resume";
    } else {
        icon.className = "fa-solid fa-pause";
        pauseBtn.title = "Pause";
    }
}



/**
 * Get icon class for source type
 * @param {string} sourceType - The source type ("pdf", "url", "text")
 * @returns {string} Font Awesome icon class
 */
function getSourceIcon(sourceType) {
    switch (sourceType) {
        case "pdf":
            return "fa-file-pdf";
        case "url":
            return "fa-link";
        case "text":
        default:
            return "fa-keyboard";
    }
}

/**
 * Process SSE stream for progress updates
 * Sets up audio stream once job_id is received
 * @param {Response} response - Fetch response with SSE stream
 * @param {string} docName - Document name for display
 * @param {string} sourceType - Source type ("pdf", "url", "text")
 * @returns {Promise<void>}
 * @throws {Error} If stream contains an error event or fails
 */
async function processStream(response, docName, sourceType = "text") {
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let lastStatus = "";
    let audioJobId = null;

    // Reset estimated duration
    estimatedDuration = 0;

    try {
        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                break;
            }

            const text = decoder.decode(value, { stream: true });
            const lines = text.split("\n");

            for (const line of lines) {
                if (line.startsWith("data: ")) {
                    try {
                        const data = JSON.parse(line.slice(6));

                        if (data.type === "error") {
                            throw new Error(data.message || "TTS generation failed");
                        } else if (data.type === "start" && data.job_id) {
                            // Got job ID - start audio stream immediately
                            const jobId = data.job_id;
                            // Estimate audio duration from character count
                            // Typical speech is ~14 chars/sec (150 wpm, 5 chars/word)
                            if (data.total_chars) {
                                estimatedDuration = data.total_chars / 14;
                            }
                            // Display document info
                            updateDocInfo(data);
                            if (!audioJobId) {
                                audioJobId = jobId;
                                // Start streaming playback immediately
                                startAudioStream(jobId);
                            }
                            // Show generating status
                            showStatus(
                                '<span class="spinner"></span> Generating...',
                                "loading"
                            );
                            // Update progress bar
                            processingProgressBar.style.width = "5%";
                        } else if (data.type === "progress") {
                            lastStatus = data.status;
                            // Show progress percentage
                            showStatus(
                                `<span class="spinner"></span> ${data.percent}%`,
                                "loading"
                            );
                            // Update progress bar
                            processingProgressBar.style.width = `${data.percent}%`;
                        } else if (data.type === "complete") {
                            // Generation complete - show player
                            // Use actual audio duration from server if available
                            if (data.audio_duration && data.audio_duration > 0) {
                                estimatedDuration = data.audio_duration;
                            }
                            // Build filename with style and language indicators
                            const styleIcons = {
                                technical: "fa-microchip",
                                conversational: "fa-comments",
                                storytelling: "fa-book-open",
                                child_narrative: "fa-child",
                                news: "fa-newspaper",
                                academic: "fa-graduation-cap"
                            };
                            const langFlags = {
                                english: "πŸ‡¬πŸ‡§",
                                chinese: "πŸ‡¨πŸ‡³",
                                japanese: "πŸ‡―πŸ‡΅",
                                korean: "πŸ‡°πŸ‡·"
                            };
                            const usedStyle = getSelectedStyle();
                            const usedLang = getSelectedLanguage();
                            const styleIcon = styleIcons[usedStyle] || "fa-microchip";
                            const langFlag = langFlags[usedLang] || "πŸ‡¬πŸ‡§";
                            filename.innerHTML = `<i class="fa-solid ${getSourceIcon(sourceType)}"></i> ${docName} <span class="filename-meta"><i class="fa-solid ${styleIcon}" title="Style: ${usedStyle}"></i><span title="Language: ${usedLang}">${langFlag}</span></span>`;
                            currentDocName = docName;
                            // Hide stream buttons, show full player with download
                            streamPlayBtn.classList.add("hidden");
                            downloadBtn.classList.remove("hidden");
                            deleteBtn.classList.remove("hidden");
                            player.classList.add("visible");
                            // Set progress to 100%
                            processingProgressBar.style.width = "100%";
                            showInputSection();
                            showStatus(
                                `<i class="fa-solid fa-circle-check"></i> Done in ${data.total_time}s`,
                                "success"
                            );
                            updatePlayerProgress();
                        }
                    } catch (parseError) {
                        // Check if it's our thrown error or a JSON parse error
                        if (parseError.message && !parseError.message.includes("JSON")) {
                            throw parseError;
                        }
                        // Ignore JSON parse errors for partial data
                    }
                }
            }
        }
    } catch (streamError) {
        // Re-throw with more context and preserve the original cause
        const context = lastStatus ? ` (during: ${lastStatus})` : "";
        throw new Error(`Stream error${context}: ${streamError.message}`, { cause: streamError });
    }
}

/**
 * Handle file upload and TTS conversion
 * @param {File} file - The uploaded file
 */
async function handleFile(file) {
    // Validate file type
    if (!file.name.toLowerCase().endsWith(".pdf")) {
        showStatus('<i class="fa-solid fa-triangle-exclamation"></i> Please select a PDF file', "error");
        return;
    }

    // Validate file size
    if (file.size > MAX_FILE_SIZE) {
        showStatus('<i class="fa-solid fa-triangle-exclamation"></i> File too large. Maximum size is 50MB.', "error");
        return;
    }

    showProcessingSection();
    showStatus('<span class="spinner"></span> Extracting text...', "loading");
    player.classList.remove("visible");
    downloadBtn.classList.add("hidden");

    const formData = new FormData();
    formData.append("file", file);
    formData.append("language", getSelectedLanguage());
    formData.append("style", getSelectedStyle());

    // Create abort controller for this request
    currentAbortController = new AbortController();

    try {
        const response = await fetch("/api/read-stream", {
            method: "POST",
            body: formData,
            signal: currentAbortController.signal,
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.detail || "Failed to process document");
        }

        // Process stream handles both progress SSE and starting audio playback
        await processStream(response, file.name, "pdf");
    } catch (error) {
        if (error.name === "AbortError") {
            // User cancelled - already handled in stopGeneration
            return;
        }
        showStatus(`<i class="fa-solid fa-circle-exclamation"></i> ${error.message}`, "error");
        showInputSection();
    } finally {
        currentAbortController = null;
    }
}

/**
 * Handle URL submission and TTS conversion
 * @param {string} url - The URL to process
 */
async function handleUrl(url) {
    url = url.trim();

    if (!url) {
        showStatus('<i class="fa-solid fa-triangle-exclamation"></i> Please enter a URL', "error");
        return;
    }

    // Validate URL format
    try {
        new URL(url);
    } catch {
        showStatus('<i class="fa-solid fa-triangle-exclamation"></i> Please enter a valid URL', "error");
        return;
    }

    showProcessingSection();
    showStatus('<span class="spinner"></span> Fetching content...', "loading");
    player.classList.remove("visible");
    downloadBtn.classList.add("hidden");
    urlSubmit.disabled = true;

    // Create abort controller for this request
    currentAbortController = new AbortController();

    try {
        const response = await fetch("/api/read-url-stream", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                url,
                language: getSelectedLanguage(),
                style: getSelectedStyle()
            }),
            signal: currentAbortController.signal,
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.detail || "Failed to process document");
        }

        // Extract filename from URL
        const urlPath = new URL(url).pathname;
        const docName = urlPath.split("/").pop() || "document";

        // Process stream handles both progress SSE and starting audio playback
        await processStream(response, docName, "url");
    } catch (error) {
        if (error.name === "AbortError") {
            // User cancelled - already handled in stopGeneration
            return;
        }
        showStatus(`<i class="fa-solid fa-circle-exclamation"></i> ${error.message}`, "error");
        showInputSection();
    } finally {
        urlSubmit.disabled = false;
        currentAbortController = null;
    }
}

/**
 * Handle text submission and TTS conversion
 * @param {string} text - The text to process
 */
async function handleText(text) {
    text = text.trim();

    if (!text) {
        showStatus('<i class="fa-solid fa-triangle-exclamation"></i> Please enter some text', "error");
        return;
    }

    if (text.length > 500000) {
        showStatus('<i class="fa-solid fa-triangle-exclamation"></i> Text too long (max 500,000 characters)', "error");
        return;
    }

    showProcessingSection();
    showStatus('<span class="spinner"></span> Processing text...', "loading");
    player.classList.remove("visible");
    downloadBtn.classList.add("hidden");
    textSubmit.disabled = true;

    // Create abort controller for this request
    currentAbortController = new AbortController();

    try {
        const response = await fetch("/api/read-text-stream", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                text,
                language: getSelectedLanguage(),
                style: getSelectedStyle()
            }),
            signal: currentAbortController.signal,
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.detail || "Failed to process text");
        }

        // Generate document name from first few words
        const words = text.trim().split(/\s+/).slice(0, 5).join(" ");
        const docName = words.length > 30 ? words.slice(0, 30) + "..." : words;

        // Process stream handles both progress SSE and starting audio playback
        await processStream(response, docName, "text");
    } catch (error) {
        if (error.name === "AbortError") {
            // User cancelled - already handled in stopGeneration
            return;
        }
        showStatus(`<i class="fa-solid fa-circle-exclamation"></i> ${error.message}`, "error");
        showInputSection();
    } finally {
        textSubmit.disabled = false;
        currentAbortController = null;
    }
}

// Tab switching
tabs.forEach((tab) => {
    tab.addEventListener("click", () => {
        const isAlreadyActive = tab.classList.contains("active");
        const isUploadTab = tab.dataset.tab === "upload";

        // If clicking on already-active upload tab, open file picker
        if (isAlreadyActive && isUploadTab) {
            fileInput.click();
            return;
        }

        tabs.forEach((t) => t.classList.remove("active"));
        tabContents.forEach((tc) => tc.classList.remove("active"));
        tab.classList.add("active");
        document.getElementById(`${tab.dataset.tab}-tab`).classList.add("active");
    });
});

// Drag and drop handlers
dropZone.addEventListener("dragover", (e) => {
    e.preventDefault();
    dropZone.classList.add("dragover");
});

dropZone.addEventListener("dragleave", () => {
    dropZone.classList.remove("dragover");
});

dropZone.addEventListener("drop", (e) => {
    e.preventDefault();
    dropZone.classList.remove("dragover");

    const files = e.dataTransfer.files;
    if (files.length > 0) {
        handleFile(files[0]);
    }
});

// Click to select file
dropZone.addEventListener("click", (e) => {
    if (e.target !== fileInput) {
        fileInput.click();
    }
});

fileInput.addEventListener("change", () => {
    if (fileInput.files.length > 0) {
        handleFile(fileInput.files[0]);
    }
});

// URL submission
urlSubmit.addEventListener("click", () => {
    handleUrl(urlInput.value);
});

urlInput.addEventListener("keypress", (e) => {
    if (e.key === "Enter") {
        handleUrl(urlInput.value);
    }
});

// Text submission
textSubmit.addEventListener("click", () => {
    handleText(textInput.value);
});

// Allow Ctrl+Enter to submit text
textInput.addEventListener("keydown", (e) => {
    if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
        handleText(textInput.value);
    }
});

// Auto-detect language from text input
textInput.addEventListener("input", () => {
    const detected = detectLanguage(textInput.value);
    if (detected) {
        setLanguage(detected, true);
    }
});

// Stop button
stopBtn.addEventListener("click", stopGeneration);

// Stream play button (during processing)
streamPlayBtn.addEventListener("click", () => {
    audio.play().catch(() => {});
    // Hide stream play button and show pause button
    streamPlayBtn.classList.add("hidden");
    pauseBtn.classList.remove("hidden");
});

// Pause button
pauseBtn.addEventListener("click", togglePause);

// Download button
downloadBtn.addEventListener("click", downloadAudio);

// Delete button
deleteBtn.addEventListener("click", deleteAudio);

// Update pause button when audio state changes
audio.addEventListener("play", updatePauseButton);
audio.addEventListener("pause", updatePauseButton);
audio.addEventListener("ended", () => {
    isPaused = false;
    updatePauseButton();
});

// Language selection
languageButtons.forEach((btn) => {
    btn.addEventListener("click", () => {
        setLanguage(btn.dataset.language, false);
    });
});

// Style selection
const styleButtons = document.querySelectorAll("#styleButtons .style-btn");
styleButtons.forEach((btn) => {
    btn.addEventListener("click", () => {
        styleButtons.forEach((b) => b.classList.remove("active"));
        btn.classList.add("active");
        selectedStyle = btn.dataset.style;
    });
});