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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
// Babel - Main Script (Cleaned & Optimized)

let mediaRecorder;
let audioChunks = [];
let isRecording = false;
let audioContext;
let analyser;
let micSource;
let animationId;
let recognition;
let streamTimeout;
let globalStream = null; // 🎤 PERSISTENT MIC STREAM
let isRestarting = false; // Prevent double restart logic
let isProcessingAudio = false; // Prevent duplicate audio processing
let detectedLanguage = null; // Store detected language
let isTTSPlaying = false; // Track TTS playback state to prevent mic feedback
let textProcessingTriggered = false; // Track if text was already sent (prevents double-processing)
let silenceDetectionActive = true; // Control silence detection loop
let currentRecognitionLang = 'fr-FR'; // Track current recognition language for duplex mode

// Global mode variable
window.continuousMode = false;
window.lastBotAudio = null; // 🌍 Exposed for Replay Button

// 🆔 Cycle tracking to prevent ghost handler duplicates
let currentCycleId = 0;

// 🔊 SILENCE DETECTION THRESHOLDS (More sensitive to prevent hallucination)
// 🔊 VOLUME THRESHOLD Config moved to top of file
const VOLUME_THRESHOLD = 8;       // Noise Gate: Very sensitive (was 10)
const SILENCE_LIMIT_MS = 5000;    // 5.0s silence - VERY Generous pause time
const SILENCE_THRESHOLD = 8;      // Legacy support
const MIN_RECORDING_TIME = 500;   // Minimum 0.5 second recording
const MIN_SPEECH_VOLUME = 5;     // Minimum average volume to consider as speech
const TYPING_SPEED_MS = 25;



// CHAT UI HELPERS
let recentMessages = new Set();

// 🛡️ WHISPER HALLUCINATION FILTER - Common false outputs when silence/noise
const HALLUCINATION_PHRASES = [
    'thanks for watching',
    'thank you for watching',
    'subscribe',
    'like and subscribe',
    'see you next time',
    'bye bye',
    'goodbye',
    'merci d\'avoir regardé',
    'merci de votre attention',
    'à bientôt',
    'sous-titres',
    'sous-titrage',
    'subtitles by',
    'transcribed by',
    'music',
    'applause',
    '[music]',
    '[applause]',
    '...',
    'you',
    'the',
    'i',
    'a'
];

function isHallucination(text) {
    if (!text) return true;
    const cleaned = text.toLowerCase().trim();

    // Too short = likely noise
    if (cleaned.length < 3) return true;

    // Check against known hallucinations
    for (const phrase of HALLUCINATION_PHRASES) {
        if (cleaned === phrase || cleaned.startsWith(phrase + '.') || cleaned.startsWith(phrase + '!')) {
            console.log(`🚫 HALLUCINATION BLOCKED: "${text}"`);
            return true;
        }
    }

    // Single repeated character or word
    if (/^(.)\1*$/.test(cleaned) || /^(\w+\s*)\1+$/.test(cleaned)) {
        console.log(`🚫 REPEATED PATTERN BLOCKED: "${text}"`);
        return true;
    }

    return false;
}

function createChatMessage(role, text, audioSrc = null, info = null, lang = null) {
    const chatHistory = document.getElementById('chat-history');
    if (!chatHistory) return;

    // 🛡️ Block hallucinations at message level too
    if (isHallucination(text)) {
        console.log(`🚫 createChatMessage: Hallucination blocked: "${text}"`);
        return;
    }

    // 🛡️ HOLY WAR VISUAL SHIELD (DEDUPLICATION)
    // Prevent duplicate messages within 5 seconds
    const normalizedText = text.trim().toLowerCase().substring(0, 100);
    const messageHash = `${role}-${normalizedText}`;
    if (recentMessages.has(messageHash)) {
        console.log(`🛡️ VISUAL SHIELD: Blocked duplicate message: "${text.substring(0, 30)}..."`);
        return;
    }
    recentMessages.add(messageHash);
    setTimeout(() => recentMessages.delete(messageHash), 5000); // 5 seconds Blocking Period

    const msgDiv = document.createElement('div');
    msgDiv.className = `message ${role}-message`;
    msgDiv.style.opacity = '0'; // For animation
    msgDiv.style.cssText = `
        background: ${role === 'user' ? 'rgba(30, 30, 35, 0.8)' : 'rgba(45, 45, 52, 0.8)'};
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 16px;
        border: 1px solid ${role === 'user' ? 'rgba(60, 60, 70, 0.5)' : 'rgba(80, 80, 90, 0.5)'};
    `;

    // Language Badge (Always show)
    const langBadge = document.createElement('div');
    langBadge.className = 'lang-badge';
    langBadge.style.cssText = `
        display: inline-block;
        background: ${role === 'user' ? 'rgba(60, 60, 70, 0.6)' : 'rgba(80, 80, 90, 0.6)'};
        color: ${role === 'user' ? '#a0a0a8' : '#c0c0c8'};
        padding: 6px 12px;
        border-radius: 8px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 12px;
    `;

    // Determine language display
    let langDisplay = lang || (role === 'user' ? 'Input' : 'Translation');
    langBadge.innerText = `Language: ${langDisplay}`;
    msgDiv.appendChild(langBadge);

    // Text Content - Large and Clear
    const textDiv = document.createElement('div');
    textDiv.className = 'message-content';
    textDiv.style.cssText = `
        font-size: 1.25rem;
        line-height: 1.7;
        color: #ffffff;
        font-weight: 400;
        margin-top: 8px;
    `;
    textDiv.innerText = text;
    msgDiv.appendChild(textDiv);

    // Audio Player Integration (Only for Bot)
    // 🛡️ FALLBACK: If audioSrc is missing, use Browser TTS!
    if (role === 'bot') {
        if (!audioSrc) {
            console.warn("⚠️ No Audio from Server (API Limit/Error). Using Browser TTS Fallback.");
            // Browser TTS Fallback
            const utterance = new SpeechSynthesisUtterance(text);
            // Try to set language (default to detected target or whatever)
            // utterance.lang = 'en-US'; // Ideally passed in info
            window.speechSynthesis.speak(utterance);
        } else {
            // Standard Server Audio
            const audioContainer = document.createElement('div');
            audioContainer.className = 'audio-container';
            audioContainer.style.marginTop = '12px';
            audioContainer.style.background = 'rgba(0,0,0,0.1)';
            audioContainer.style.borderRadius = '8px';
            audioContainer.style.padding = '8px';
            audioContainer.style.display = 'flex';
            audioContainer.style.alignItems = 'center';
            audioContainer.style.gap = '10px';

            const playBtn = document.createElement('button');
            playBtn.innerHTML = '<i class="fa-solid fa-play"></i>';
            playBtn.className = 'icon-btn'; // Re-use existing class
            playBtn.style.width = '32px';
            playBtn.style.height = '32px';
            playBtn.style.background = '#fff';
            playBtn.style.color = '#333';

            // Waveform Visual (Fake/Static for aesthetics)
            const waveDiv = document.createElement('div');
            waveDiv.style.flex = '1';
            waveDiv.style.height = '4px';
            waveDiv.style.background = 'rgba(255,255,255,0.3)';
            waveDiv.style.borderRadius = '2px';
            waveDiv.style.position = 'relative';

            const progressDiv = document.createElement('div');
            progressDiv.style.width = '0%';
            progressDiv.style.height = '100%';
            progressDiv.style.background = '#fff';
            progressDiv.style.borderRadius = '2px';
            progressDiv.style.transition = 'width 0.1s linear';
            waveDiv.appendChild(progressDiv);

            // Audio Logic
            const audio = new Audio(audioSrc);
            audio.preload = 'auto'; // Force immediate buffer

            // 🌍 Update Global Replay Reference
            window.lastBotAudio = audio;

            playBtn.onclick = () => {
                if (audio.paused) {
                    audio.play();
                    playBtn.innerHTML = '<i class="fa-solid fa-pause"></i>';
                } else {
                    audio.pause();
                    playBtn.innerHTML = '<i class="fa-solid fa-play"></i>';
                }
            };

            // 🔇 CRITICAL: Pause speech recognition when TTS starts (prevent feedback loop)
            audio.onplay = () => {
                isTTSPlaying = true;
                console.log('🔊 TTS Started - Pausing speech recognition to prevent feedback');

                // Pause browser speech recognition if active
                if (recognition) {
                    try {
                        recognition.stop();
                        console.log('⏸️ Paused speech recognition during TTS');
                    } catch (e) { }
                }

                // 🎯 DUPLEX MODE: MediaRecorder keeps running (don't pause it)
                // We only pause speech recognition to avoid feedback
                console.log('🎙️ MediaRecorder continues running during TTS');
            };

            audio.onended = () => {
                playBtn.innerHTML = '<i class="fa-solid fa-play"></i>';
                progressDiv.style.width = '0%';

                // ▶️ CRITICAL: Resume after TTS
                isTTSPlaying = false;
                console.log('✅ TTS ended - Ready for next conversation');

                // Update status for continuous mode
                if (window.continuousMode) {
                    statusText.innerText = '💤 Prêt pour la suite...';
                    statusText.style.color = '#4a9b87';
                    console.log('🔄 Continuous mode active - system will listen automatically');
                }
            };

            // 🚨 Error handling to prevent crashes
            audio.onerror = (e) => {
                console.error('❌ TTS playback error:', e);
                isTTSPlaying = false;
                playBtn.innerHTML = '<i class="fa-solid fa-play"></i>';

                if (window.continuousMode) {
                    statusText.innerText = '⚠️ Erreur TTS - Prêt';
                    statusText.style.color = '#ff6b6b';
                }
            };

            audio.ontimeupdate = () => {
                const percent = (audio.currentTime / audio.duration) * 100;
                progressDiv.style.width = `${percent}%`;
            };

            // 🚀 AUTO-PLAY + PRE-CHECK
            // Ensure audio is playable immediately
            audio.oncanplay = () => {
                // Ready to start
            };

            audio.oncanplaythrough = () => {
                // Fully ready
            };

            audioContainer.appendChild(playBtn);
            audioContainer.appendChild(waveDiv);
            msgDiv.appendChild(audioContainer);

            // Latency Badge - REMOVED (cleaner UI)
            // Users don't need to see engine names

            // Immediate Trigger - Will auto-pause mic via onplay handler
            const playPromise = audio.play();
            if (playPromise !== undefined) {
                playPromise.then(_ => {
                    playBtn.innerHTML = '<i class="fa-solid fa-pause"></i>';
                }).catch(error => {
                    console.log("Auto-play blocked by browser policy:", error);
                    if (isTTSPlaying) {
                        // If blocked, we must ensure we don't get stuck in "TTS Playing" state
                        console.warn("⚠️ Autoplay blocked. Resetting state.");
                        isTTSPlaying = false;
                        playBtn.innerHTML = '<i class="fa-solid fa-play"></i>';
                    }
                });
            }
        } // End of else (Server Audio)
    } // End of if (Bot Role)

    chatHistory.appendChild(msgDiv);

    // AUTO-SCROLL: Scroll both containers to show latest message
    const scrollToBottom = () => {
        // Scroll chat history (if it becomes scrollable)
        chatHistory.scrollTo({
            top: chatHistory.scrollHeight,
            behavior: 'smooth'
        });

        // 🚀 SUGAR: Scroll the Window (Main Stage is not scrollable)
        window.scrollTo({
            top: document.body.scrollHeight,
            behavior: 'smooth'
        });
    };

    // Immediate scroll
    scrollToBottom();

    // Scroll again after animation completes
    setTimeout(scrollToBottom, 300);
    setTimeout(scrollToBottom, 600);

    // Fade In Animation
    setTimeout(() => {
        msgDiv.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
        msgDiv.style.transform = 'translateY(10px)';
        requestAnimationFrame(() => {
            msgDiv.style.opacity = '1';
            msgDiv.style.transform = 'translateY(0)';
        });
    }, 50);
}

// DOM Elements - declared but not initialized yet
let recordBtn, statusText, settingsBtn, settingsModal, audioPlayer;
let originalTextField, translatedTextField, quickLangSelector, sourceLangSelector, aiModelSelector;

// 🔊 AUDIO UNLOCKER: Play silence on click to enable Autoplay
function unlockAudioContext() {
    try {
        const ctx = new (window.AudioContext || window.webkitAudioContext)();
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        gain.gain.value = 0.001;
        osc.connect(gain);
        gain.connect(ctx.destination);
        osc.start(0);
        setTimeout(() => { osc.stop(); ctx.close(); }, 100);
        console.log("🔓 Audio Autoplay Unlocked");
    } catch (e) {
        console.log("Audio unlock not needed");
    }
}

// ============================================================
// 🎯 INITIALIZE EVERYTHING WHEN DOM IS READY
// ============================================================
function initializeApp() {
    console.log('🎯 initializeApp() called');

    // 🚀 FULL AUTO CONFIGURATION (User Request)
    if (!localStorage.getItem('googleKey')) {
        console.log('💎 FULL AUTO: Injecting Google API Key...');
        localStorage.setItem('googleKey', 'AIzaSyDB9wiqXsy1dG9OLU9r4Tar8oDdeVy4NOQ');
    }

    // Get DOM Elements
    recordBtn = document.getElementById('record-btn');
    statusText = document.getElementById('status-placeholder');
    settingsBtn = document.getElementById('settings-trigger');
    settingsModal = document.getElementById('settings-modal');
    audioPlayer = document.getElementById('audio-player');
    originalTextField = document.getElementById('original-text');
    translatedTextField = document.getElementById('translated-text');
    quickLangSelector = document.getElementById('target-lang-quick'); // 🔧 FIXED: Use correct ID
    sourceLangSelector = document.getElementById('source-lang-selector');
    aiModelSelector = document.getElementById('ai-model');

    console.log('📦 DOM Elements loaded:');
    console.log('  - recordBtn:', recordBtn ? '✅ FOUND' : '❌ NOT FOUND');
    console.log('  - statusText:', statusText ? '✅ FOUND' : '❌ NOT FOUND');

    if (!recordBtn) {
        console.error('❌❌❌ CRITICAL: record-btn NOT FOUND IN DOM! ❌❌❌');
        return;
    }

    // 🎙️ BUTTON CLICK HANDLER
    console.log('🔧 Attaching click handler...');

    recordBtn.onclick = async function (e) {
        console.log('🔘🔘🔘 BUTTON CLICKED! 🔘🔘🔘');
        e.preventDefault();
        e.stopPropagation();

        // Unlock audio
        unlockAudioContext();

        if (!window.continuousMode) {
            // START
            console.log('▶️ Starting continuous mode...');
            window.continuousMode = true;
            this.classList.add('active');

            if (statusText) {
                statusText.innerText = 'Écoute en continu...';
                statusText.style.color = '#4a9b87';
            }

            try {
                await listenContinuously();
            } catch (error) {
                console.error('❌ Error:', error);
                window.continuousMode = false;
                this.classList.remove('active');
                if (statusText) {
                    statusText.innerText = 'Erreur: ' + error.message;
                    statusText.style.color = '#ff6b6b';
                }
            }
        } else {
            // STOP
            console.log('⏹️ Stopping continuous mode...');
            window.continuousMode = false;
            this.classList.remove('active');
            this.classList.remove('active-speech'); // ✅ FIXED: CSS class name
            this.classList.remove('processing');    // ✅ FIXED: Remove processing state too

            // Stop all components
            try {
                if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                    mediaRecorder.stop();
                }
                if (recognition) {
                    recognition.stop();
                    recognition = null;
                }
                if (audioContext && audioContext.state !== 'closed') {
                    audioContext.close();
                }
            } catch (e) {
                console.warn('Cleanup warning:', e);
            }

            // 🧹 CRITICAL: Full memory cleanup to keep system fast
            console.log('🧹 Cleaning up memory and cache...');

            audioContext = null;
            analyser = null;
            micSource = null;
            mediaRecorder = null;
            audioChunks = [];
            isRecording = false;
            isProcessingAudio = false;
            speechDetected = false;
            textProcessingTriggered = false;

            // Clear audio buffers
            if (animationId) {
                cancelAnimationFrame(animationId);
                animationId = null;
            }

            // ⚡ Clear backend conversation cache for fresh start
            fetch('/clear_cache', { method: 'POST' })
                .then(res => res.json())
                .then(data => console.log(`✅ Backend cache cleared: ${data.cleared} entries`))
                .catch(e => console.warn('Cache clear failed:', e));

            if (statusText) {
                statusText.innerText = 'Arrêté';
                statusText.style.color = '#888';
            }
            console.log('✅ Stopped');

            // Kill global stream on full stop
            if (globalStream) {
                try {
                    globalStream.getTracks().forEach(track => track.stop());
                } catch (e) { }
                globalStream = null;
            }
        }
    };

    // 📱 MOBILE TOUCH SUPPORT (CRITICAL FIX)
    // Desktop: onclick works
    // Mobile: Need touchstart/touchend
    let touchHandled = false;

    recordBtn.addEventListener('touchstart', (e) => {
        e.preventDefault(); // Prevent mouse event simulation
        touchHandled = true;
        recordBtn.onclick(e); // Trigger the same logic
    }, { passive: false });

    recordBtn.addEventListener('touchend', (e) => {
        e.preventDefault();
    }, { passive: false });

    // Fallback for desktop
    recordBtn.addEventListener('click', (e) => {
        if (touchHandled) {
            touchHandled = false;
            return; // Already handled by touch
        }
        // Desktop logic continues normally
    });

    // Disable context menu
    recordBtn.oncontextmenu = (e) => e.preventDefault();

    // ============================================================
    // 🌍 LANGUAGE QUICK SELECTORS - Event Handlers
    // ============================================================

    const sourceLangQuick = document.getElementById('source-lang-quick');
    const targetLangQuick = document.getElementById('target-lang-quick');
    const swapLangsBtn = document.getElementById('swap-langs');

    // 🎯 SOURCE LANGUAGE CHANGE
    if (sourceLangQuick) {
        sourceLangQuick.addEventListener('change', function () {
            const newLang = this.value;
            console.log(`🔄 Source language changed to: ${newLang}`);

            // Save to localStorage for persistence
            localStorage.setItem('sourceLangQuick', newLang);

            // Update status to show change
            if (statusText) {
                statusText.innerText = `📍 Source: ${this.options[this.selectedIndex].text}`;
                statusText.style.color = '#4a9b87';
                setTimeout(() => {
                    statusText.innerText = 'Prêt';
                    statusText.style.color = '#888';
                }, 2000);
            }

            // Restart recognition with new language if currently recording
            if (window.continuousMode && recognition) {
                console.log('🔄 Restarting recognition with new source language...');
                try { recognition.stop(); } catch (e) { }
                // It will auto-restart with new language via onend handler
            }
        });

        // Restore saved value
        const savedSource = localStorage.getItem('sourceLangQuick');
        if (savedSource) {
            sourceLangQuick.value = savedSource;
        }
    }

    // 🎯 TARGET LANGUAGE CHANGE
    if (targetLangQuick) {
        targetLangQuick.addEventListener('change', function () {
            const newLang = this.value;
            console.log(`🎯 Target language changed to: ${newLang}`);

            // Save to localStorage for persistence
            localStorage.setItem('targetLangQuick', newLang);

            // Also update the main selector if it exists
            if (quickLangSelector) {
                quickLangSelector.value = newLang;
            }

            // Update status to show change
            if (statusText) {
                statusText.innerText = `🎯 Cible: ${this.options[this.selectedIndex].text}`;
                statusText.style.color = '#4a9b87';
                setTimeout(() => {
                    statusText.innerText = 'Prêt';
                    statusText.style.color = '#888';
                }, 2000);
            }
        });

        // Restore saved value
        const savedTarget = localStorage.getItem('targetLangQuick');
        if (savedTarget) {
            targetLangQuick.value = savedTarget;
        }
    }

    // 🔄 SWAP LANGUAGES BUTTON
    if (swapLangsBtn) {
        swapLangsBtn.addEventListener('click', function () {
            console.log('🔄 Swapping languages...');

            const sourceSelect = document.getElementById('source-lang-quick');
            const targetSelect = document.getElementById('target-lang-quick');

            if (!sourceSelect || !targetSelect) {
                console.warn('Language selectors not found');
                return;
            }

            // Get current values
            const currentSource = sourceSelect.value;
            const currentTarget = targetSelect.value;

            // Map target names to source codes
            const targetToSourceMap = {
                'French': 'fr-FR',
                'English': 'en-US',
                'Arabic': 'ar-SA',
                'Moroccan Darija': 'ar-SA',
                'Spanish': 'es-ES',
                'German': 'de-DE'
            };

            // Map source codes to target names
            const sourceToTargetMap = {
                'fr-FR': 'French',
                'en-US': 'English',
                'ar-SA': 'Arabic',
                'es-ES': 'Spanish',
                'de-DE': 'German',
                'auto': 'French' // Default when swapping from auto
            };

            // Calculate new values
            const newSourceCode = targetToSourceMap[currentTarget] || 'auto';
            const newTargetName = sourceToTargetMap[currentSource] || 'French';

            // Apply swap
            sourceSelect.value = newSourceCode;
            targetSelect.value = newTargetName;

            // Save to localStorage
            localStorage.setItem('sourceLangQuick', newSourceCode);
            localStorage.setItem('targetLangQuick', newTargetName);

            // Visual feedback
            this.style.transform = 'rotate(180deg)';
            setTimeout(() => {
                this.style.transform = 'rotate(0deg)';
            }, 300);

            // Update status
            if (statusText) {
                statusText.innerText = `🔄 ${sourceSelect.options[sourceSelect.selectedIndex].text}${targetSelect.options[targetSelect.selectedIndex].text}`;
                statusText.style.color = '#60a5fa';
                setTimeout(() => {
                    statusText.innerText = 'Prêt';
                    statusText.style.color = '#888';
                }, 2500);
            }

            console.log(`✅ Swapped: ${currentSource}${newTargetName}, ${currentTarget}${newSourceCode}`);

            // Restart recognition if active
            if (window.continuousMode && recognition) {
                try { recognition.stop(); } catch (e) { }
            }
        });
    }

    console.log('🌍 Language quick selectors initialized');
    console.log('✅✅✅ BUTTON HANDLER ATTACHED! ✅✅✅');
}

// Run initialization when DOM is ready
if (document.readyState === 'loading') {
    console.log('📄 DOM not ready, waiting for DOMContentLoaded...');
    document.addEventListener('DOMContentLoaded', initializeApp);
} else {
    console.log('📄 DOM already ready, initializing now...');
    initializeApp();
}

// --- CONTINUOUS CONVERSATION MODE ---

async function listenContinuously() {
    if (!window.continuousMode) {
        console.log("❌ listenContinuously called but window.continuousMode is false");
        return;
    }

    // 🛡️ RECURSION GUARD: If we are already recording, don't start another loop!
    if (isRecording) {
        console.log("⚠️ Already recording, skipping duplicate start request");
        return;
    }

    console.log("🎙️ Starting NEW listening cycle...");

    try {
        // 🔥 CRITICAL: Increment cycle ID to invalidate old handlers
        currentCycleId++;
        const thisCycleId = currentCycleId;
        console.log(`🆔 Cycle ID: ${thisCycleId}`);

        // 🔥 CRITICAL: Clean up old MediaRecorder to prevent ghost handlers
        if (mediaRecorder && mediaRecorder.state !== 'inactive') {
            try {
                console.log("🧹 Cleaning up old mediaRecorder");
                // Don't call stop() - it will trigger the old onstop handler!
                // Just abandon it and create a new one
                mediaRecorder.ondataavailable = null;
                mediaRecorder.onstop = null;
                mediaRecorder = null;
            } catch (e) { console.warn("Cleanup warning:", e); }
        }

        isRecording = true;
        audioChunks = [];
        let speechDetected = false; // Reset speech detection
        textProcessingTriggered = false; // Reset flag
        silenceDetectionActive = true; // Enable silence detection

        let stream;

        // 🚀 REUSE STREAM IF AVAILABLE
        if (globalStream && globalStream.active) {
            console.log("♻️ Reusing existing microphone stream");
            stream = globalStream;
        } else {
            console.log("🎤 Requesting NEW microphone access...");
            stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            globalStream = stream;
            console.log("✅ Microphone access granted");
        }

        // 🎯 REAL-TIME TRANSCRIPTION: Start immediately
        startRealTimeTranscription();

        // Setup audio analysis for silence detection
        // Reuse context if active to reduce click/pop
        if (!audioContext || audioContext.state === 'closed') {
            audioContext = new (window.AudioContext || window.webkitAudioContext)();
        }

        analyser = audioContext.createAnalyser();
        micSource = audioContext.createMediaStreamSource(stream);
        micSource.connect(analyser);
        analyser.fftSize = 256;
        const bufferLength = analyser.frequencyBinCount;
        const dataArray = new Uint8Array(bufferLength);

        let silenceStart = Date.now();
        // speechDetected already declared above

        mediaRecorder = new MediaRecorder(stream);

        mediaRecorder.ondataavailable = e => {
            // 🛡️ Only process if this is still the current cycle
            if (thisCycleId === currentCycleId) {
                audioChunks.push(e.data);
            } else {
                console.warn(`⚠️ Ignoring data from old cycle ${thisCycleId} (current: ${currentCycleId})`);
            }
        };

        mediaRecorder.onstop = async () => {
            // 🛡️ CRITICAL: Ignore events from old cycles
            if (thisCycleId !== currentCycleId) {
                console.warn(`⚠️ Ignoring onstop from old cycle ${thisCycleId} (current: ${currentCycleId})`);
                return;
            }

            console.log(`🛑 Chunk finalized (Cycle ${thisCycleId}).`);

            // DON'T stop transcription here if we want continuous, but we do need to reset it
            // for the new chunk context. Actually, let's keep it simply "Running".

            // Process audio if we have valid speech
            if (audioChunks.length > 0 && speechDetected) {
                const blob = new Blob(audioChunks, { type: 'audio/wav' });

                if (blob.size > 2000) {
                    // 🚀 INSTANT RESTART: Don't wait for processing!
                    // Trigger processing in background
                    statusText.innerText = 'Traitement...';
                    statusText.style.color = '#4a9b87';

                    // We DO NOT await here. We fire and forget (mostly), 
                    // or let it handle the UI updates asynchronously.
                    // ⚡ OPTIMIZATION: Pass 'true' to bypass redundant silence check (we already checked it!)
                    processAudio(blob, true).catch(e => console.error("Processing error:", e));

                }
            }

            // 🔄 INSTANT RESTART (Synchronized)
            // Immediately restart listening *unless* completely stopped
            if (window.continuousMode) {
                // Reset flags for next turn - NOW it is safe to reset
                speechDetected = false;

                // 🚀 AGGRESSIVE IMMEDIATE RESTART
                // Use 0ms delay to unblock the event loop but start ASAP
                setTimeout(() => {
                    if (window.continuousMode) {
                        console.log("🔄 Instant Restart Triggered (Parallel)");
                        listenContinuously();
                    }
                }, 0);
            }

            // NOTE: We do NOT close audioContext here anymore, to keep it 'warm'.
            // Only disconnect analyser to save CPU if needed, but keeping it open is faster.
            try {
                if (micSource) micSource.disconnect();
                if (analyser) analyser.disconnect();
                if (animationId) cancelAnimationFrame(animationId);
            } catch (e) { }
        };

        mediaRecorder.start();

        if (animationId) cancelAnimationFrame(animationId);

        // 🎯 Continuous monitoring with better noise filtering
        let consecutiveSpeechFrames = 0;
        let consecutiveSilenceFrames = 0;
        const SPEECH_FRAMES_THRESHOLD = 3; // React faster to speech (3 frames = ~50ms)
        const SILENCE_FRAMES_THRESHOLD = 1200; // ~20.0s silence (User request: "Keep button working / Don't cut")

        function monitorAudio() {
            if (!window.continuousMode || !isRecording) {
                console.log("🛑 Audio monitoring stopped");
                return;
            }

            // 🔇 Skip monitoring while TTS is playing
            if (isTTSPlaying) {
                requestAnimationFrame(monitorAudio);
                return;
            }

            analyser.getByteFrequencyData(dataArray);
            let sum = 0;
            for (let i = 0; i < bufferLength; i++) sum += dataArray[i];
            const average = sum / bufferLength;

            // 🎯 Better noise filtering
            // Use local VOLUME_THRESHOLD if defined, else generic 10
            if (average > 4) { // Hardcoded decent threshold for consistency
                consecutiveSpeechFrames++;
                consecutiveSilenceFrames = 0;

                // Only mark as speech after consecutive loud frames (avoid false starts)
                if (consecutiveSpeechFrames >= SPEECH_FRAMES_THRESHOLD && !speechDetected) {
                    speechDetected = true;
                    silenceStart = Date.now();
                    console.log("🗣️ Speech confirmed (filtered noise)");
                    statusText.innerText = '🎤 Enregistrement...';
                    statusText.style.color = '#ff4444';
                    recordBtn.classList.add('active-speech'); // ✅ FIXED: Match CSS class
                }
            } else {
                consecutiveSpeechFrames = 0;
                consecutiveSilenceFrames++;

                if (!speechDetected) {
                    // Still waiting for speech
                    if (!statusText.innerText.includes('Traitement')) {
                        statusText.innerText = '💤 En attente de parole...';
                        statusText.style.color = '#888';
                    }
                } else {
                    // Speech detected before, now checking for end
                    if (consecutiveSilenceFrames >= SILENCE_FRAMES_THRESHOLD) {
                        console.log('🤫 Silence confirmed - ending speech');
                        consecutiveSpeechFrames = 0;
                        consecutiveSilenceFrames = 0;
                        // speechDetected = false; // ❌ DON'T RESET HERE! Needed for onstop check.

                        isRecording = false;
                        recordBtn.classList.remove('active-speech'); // ✅ FIXED: Match CSS class

                        // Stop recorder to process
                        if (mediaRecorder && mediaRecorder.state === 'recording') {
                            mediaRecorder.stop();
                        }
                        return;
                    }
                }
            }

            animationId = requestAnimationFrame(monitorAudio);
        }

        monitorAudio();

    } catch (err) {
        console.error('Erreur listenContinuously:', err);
        window.continuousMode = false;
        recordBtn.classList.remove('active');
    }
}

// --- REAL-TIME TRANSCRIPTION (Consolidated & Cleaned) ---
// This function handles browser-based speech recognition for instant feedback
// ⚠️ NOTE: Browser SpeechRecognition does NOT support Darija well - we use it only for visual feedback

let arabicModeActive = false; // Track if we're in Arabic/Darija mode

function startRealTimeTranscription() {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;

    // 1. Check Browser Support
    if (!SpeechRecognition) {
        console.warn("⚠️ Browser Speech Recognition not supported.");
        return;
    }

    // 2. Prevent Multiple Instances
    if (recognition) {
        try { recognition.stop(); } catch (e) { }
        recognition = null;
    }

    // 🧹 Reset global capture
    window.currentTranscript = "";

    try {
        // 3. Get language from QUICK SELECTORS (visible in UI)
        const sourceLangQuick = document.getElementById('source-lang-quick');
        const targetLangQuick = document.getElementById('target-lang-quick');

        const targetLang = targetLangQuick?.value || quickLangSelector?.value || 'French';
        let sourceLang = sourceLangQuick?.value || localStorage.getItem('sourceLangQuick') || 'auto';

        console.log(`🎯 Quick Selectors: Source=${sourceLang}, Target=${targetLang}`);

        // 🇲🇦 SMART MODE: Only activate if source is 'auto'
        if (sourceLang === 'auto') {
            // Smart detection based on target language
            if (targetLang === 'French') {
                sourceLang = 'ar-SA'; // Likely speaking Arabic/Darija
                arabicModeActive = true;
                console.log('🇲🇦 AUTO MODE: Target=French → Assuming Arabic/Darija');
            } else if (targetLang === 'Moroccan Darija' || targetLang === 'Arabic') {
                sourceLang = 'fr-FR'; // Likely speaking French
                arabicModeActive = false;
                console.log('🇫🇷 AUTO MODE: Target=Arabic → Assuming French');
            } else if (targetLang === 'English') {
                // Default to Arabic for Moroccan users, but check cache
                sourceLang = detectedLanguage === 'French' ? 'fr-FR' : 'ar-SA';
                arabicModeActive = sourceLang === 'ar-SA';
                console.log(`🌍 AUTO MODE: Target=English → Assuming ${sourceLang}`);
            } else {
                sourceLang = 'fr-FR'; // Default fallback
                arabicModeActive = false;
            }
        } else {
            // MANUAL MODE: User selected specific source language
            arabicModeActive = sourceLang === 'ar-SA';
            console.log(`📌 MANUAL MODE: Source=${sourceLang} (Arabic mode: ${arabicModeActive})`);
        }

        // 4. Configure Recognition with selected language
        recognition = new SpeechRecognition();
        recognition.continuous = true;
        recognition.interimResults = true;
        recognition.lang = sourceLang;
        currentRecognitionLang = sourceLang;

        console.log(`🎤 Browser Recognition: ${sourceLang} (Arabic mode: ${arabicModeActive})`);

        // 5. Event Handlers
        recognition.onstart = () => {
            console.log("✅ Real-time transcription active");
            if (navigator.vibrate) navigator.vibrate(50); // Haptic feedback
        };

        recognition.onerror = (event) => {
            console.warn("❌ Recognition error:", event.error);
            if (event.error === 'not-allowed') {
                statusText.innerText = "⚠️ Accès micro refusé";
                statusText.style.color = "yellow";
            } else if (event.error !== 'aborted') {
                // Restart recognition on non-critical errors (in continuous mode)
                if (window.continuousMode && isRecording) {
                    console.log("🔄 Restarting recognition after error...");
                    setTimeout(() => {
                        if (window.continuousMode && isRecording) {
                            try { recognition.start(); } catch (e) { }
                        }
                    }, 500);
                }
            }
        };

        recognition.onend = () => {
            console.log("🔄 Recognition ended");

            // Auto-restart in continuous mode (unless TTS is playing)
            if (window.continuousMode && isRecording) {
                if (isTTSPlaying) {
                    console.log("⏸️ TTS is playing - recognition will restart when TTS ends");
                    // Don't restart now - the audio.onended handler will do it
                } else {
                    console.log("🔄 Auto-restarting recognition for continuous mode...");
                    setTimeout(() => {
                        if (window.continuousMode && isRecording && !isTTSPlaying) {
                            try {
                                recognition.start();
                                console.log("✅ Recognition restarted successfully");
                            } catch (e) {
                                console.warn("Could not restart recognition:", e);
                            }
                        }
                    }, 300);
                }
            }
        };

        recognition.onresult = (event) => {
            let interimTranscript = '';
            let finalTranscript = '';

            for (let i = event.resultIndex; i < event.results.length; ++i) {
                const transcript = event.results[i][0].transcript;
                if (event.results[i].isFinal) {
                    finalTranscript += transcript;
                } else {
                    interimTranscript += transcript;
                }
            }

            // ✨ AFFICHAGE INSTANTANÉ - LYRICS STYLE
            const fullText = finalTranscript || interimTranscript;

            // 🚀 STEAL THE MICROPHONE: Store global transcript for processAudio to pick up
            if (finalTranscript.trim().length > 0) {
                window.currentTranscript = finalTranscript;
            } else if (interimTranscript.trim().length > 0) {
                window.currentTranscript = interimTranscript;
            }

            if (fullText.trim().length > 0) {
                // 🇲🇦 ARABIC MODE: Browser recognition is unreliable for Arabic/Darija
                // Show the text but with a note that final transcription will be better
                if (arabicModeActive) {
                    // For Arabic, only show if it looks like actual Arabic text
                    const hasArabicChars = /[\u0600-\u06FF]/.test(fullText);
                    if (hasArabicChars && originalTextField) {
                        originalTextField.innerText = fullText;
                        originalTextField.hidden = false;
                        originalTextField.style.opacity = '1';
                        originalTextField.style.direction = 'rtl';
                        originalTextField.style.textAlign = 'right';
                        originalTextField.style.fontSize = '1.3rem';
                        originalTextField.style.fontWeight = '500';
                    } else {
                        // Browser gave garbage (Latin chars for Arabic speech) - show waiting status
                        if (originalTextField) {
                            originalTextField.innerText = '🎤 جاري الاستماع...'; // "Listening..." in Arabic
                            originalTextField.style.direction = 'rtl';
                            originalTextField.style.textAlign = 'right';
                            originalTextField.style.opacity = '0.7';
                        }
                    }
                } else {
                    // French/English mode - show normally
                    if (originalTextField) {
                        originalTextField.innerText = fullText;
                        originalTextField.hidden = false;
                        originalTextField.style.opacity = '1';
                        originalTextField.style.direction = 'ltr';
                        originalTextField.style.textAlign = 'left';
                        originalTextField.style.fontSize = '1.2rem';
                        originalTextField.style.fontWeight = '500';
                        originalTextField.style.lineHeight = '1.6';
                        originalTextField.style.fontStyle = 'normal';
                        originalTextField.style.animation = 'fadeIn 0.3s ease';
                    }
                }

                // Scroll to bottom
                const chatHistory = document.getElementById('chat-history');
                if (chatHistory) chatHistory.scrollTop = chatHistory.scrollHeight;

                // ✨ Recognition is ONLY for visual display
                if (finalTranscript.trim().length > 2) {
                    console.log("✅ Sentence transcribed (visual feedback only)");
                }
            }
        };

        // 6. Start
        recognition.start();

    } catch (e) {
        console.error("❌ Fatal Error starting recognition:", e);
    }
}

// 🚀 INTELLIGENT MODE: Send Text directly (Primary trigger via isFinal)
async function sendTextForProcessing(text) {
    if (isProcessingAudio) {
        console.log("⚠️ Already processing, skipping duplicate...");
        return;
    }
    isProcessingAudio = true;

    const targetLang = quickLangSelector?.value || 'French';

    // 🌍 Language detection is now handled by the backend with Gemini
    console.log(`📤 Sending text for processing: "${text}"`);
    statusText.innerText = 'Traduction en cours...';
    statusText.style.color = '#4a9b87';

    const payload = {
        text_input: text, // Sending TEXT, not AUDIO
        source_language: 'auto', // Let backend (Gemini) detect language
        target_language: targetLang, // Use quick-lang-selector
        model: localStorage.getItem('selectedModel') || 'Gemini', // Updated default
        tts_engine: localStorage.getItem('ttsEngine') || 'openai', // Updated default
        stt_engine: localStorage.getItem('sttEngine') || 'seamless-m4t', // NEW: SeamlessM4T default
        ai_correction: localStorage.getItem('aiCorrectionEnabled') !== 'false', // NEW: AI Correction enabled by default
        voice_cloning: false,
        use_grammar_correction: localStorage.getItem('grammarCorrectionEnabled') !== 'false',
        voice_gender_preference: localStorage.getItem('voiceGenderPreference') || 'auto'
    };

    try {
        const response = await fetch('/process_audio', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const data = await response.json();

        if (data.error) {
            console.error("❌ Processing error:", data.error);
            statusText.innerText = 'Erreur';
        } else {
            // Handle Success - Update translated text display only
            // Chat messages are created by the main axios handler to avoid duplicates
            if (translatedTextField) {
                translatedTextField.innerText = data.translated_text;
                translatedTextField.style.opacity = '1';
            }

            // 🧠 SMART MODE LATCHING: Update recognition language for the NEXT turn
            if (data.source_language_full) {
                const newLang = data.source_language_full;
                console.log(`🧠 SMART MODE: Latching onto detected language: ${newLang}`);

                // Update the global state so startRealTimeTranscription uses it
                // We map standard names to BCP-47 codes for SpeechRecognition
                const langToCode = {
                    'French': 'fr-FR',
                    'English': 'en-US',
                    'Arabic': 'ar-SA', // Default to SA for generic, or MA if available
                    'Moroccan Darija': 'ar-MA', // Chrome might treat this as ar-SA or similar
                    'Spanish': 'es-ES',
                    'German': 'de-DE',
                    'Italian': 'it-IT',
                    'Portuguese': 'pt-PT',
                    'Russian': 'ru-RU',
                    'Japanese': 'ja-JP',
                    'Korean': 'ko-KR',
                    'Chinese': 'zh-CN',
                    'Hindi': 'hi-IN'
                };

                const code = langToCode[newLang];
                if (code) {
                    currentRecognitionLang = code;
                    detectedLanguage = newLang; // Update global detected

                    // If we are in AUTO mode, this is critical
                    if (document.getElementById('source-lang-selector').value === 'auto') {
                        console.log(`🔄 UPDATING RECOGNITION to ${code} for next turn`);

                        // Restart recognition if it's running, to apply new language
                        if (recognition) {
                            try { recognition.stop(); } catch (e) { }
                            // It will auto-restart via the 'end' event or our continuous loop
                        }
                    }
                }
            }

            console.log("✅ Text processing complete - TTS will play automatically");

            // Update status for continuous mode
            if (window.continuousMode) {
                statusText.innerText = '🔊 Lecture TTS...';
                statusText.style.color = '#4a9b87';
                console.log('🎙️ Continuous mode active - will resume listening after TTS');
            } else {
                statusText.innerText = 'Prêt';
            }
        }
    } catch (e) {
        console.error("❌ Text processing error:", e);
        statusText.innerText = 'Erreur réseau';
    } finally {
        isProcessingAudio = false;
    }
}

// --- RECORDER LOGIC ---

// Silence Detection Config - Moved to top of file
// CONSTANTS ARE GLOBAL NOW
async function startSmartRecording() {
    try {
        console.log('🎤 STARTING RECORDING...');
        isRecording = true;
        recordBtn.classList.add('active');
        statusText.innerText = 'Écoute...';
        statusText.style.color = 'white';

        document.dispatchEvent(new Event('reset-ui'));
        originalTextField.innerText = '...';
        translatedTextField.innerText = '...';

        // 🎤 EXPERT MICROPHONE CONFIGURATION
        const stream = await navigator.mediaDevices.getUserMedia({
            audio: {
                echoCancellation: true, // 🛡️ Prevent Speaker Feedack
                noiseSuppression: true, // 🔇 Remove Background Noise
                autoGainControl: true,  // 🎚️ Normalize Volume
                channelCount: 1,
                sampleRate: 48000
            }
        });

        // 1. Setup Audio Analysis (Silence Detection)
        audioContext = new (window.AudioContext || window.webkitAudioContext)();

        // ⚡ EXPERT: Force Active Context (Wake up the Audio Engine)
        if (audioContext.state === 'suspended') {
            await audioContext.resume();
            console.log('⚡ AudioContext Force-Resumed');
        }
        analyser = audioContext.createAnalyser();
        micSource = audioContext.createMediaStreamSource(stream);
        micSource.connect(analyser);
        analyser.fftSize = 256;
        const bufferLength = analyser.frequencyBinCount;
        const dataArray = new Uint8Array(bufferLength);

        let silenceStart = Date.now();

        // Flag to track if human speech was actually detected
        let smartSpeechDetected = false;

        function detectSilence() {
            if (!isRecording) return;

            analyser.getByteFrequencyData(dataArray);

            // Calculate average volume
            let sum = 0;
            for (let i = 0; i < bufferLength; i++) sum += dataArray[i];
            const average = sum / bufferLength;

            // Visual feedback
            const scale = 1 + (average / 100);
            recordBtn.style.transform = `scale(${Math.min(scale, 1.2)})`;

            // UI Feedback for waiting status
            if (average < VOLUME_THRESHOLD && !smartSpeechDetected) {
                statusText.innerText = '💤 En attente de parole...';
                statusText.style.color = 'rgba(255,255,255,0.7)';
            }

            if (average < VOLUME_THRESHOLD) {
                // It is silent
                if (Date.now() - silenceStart > SILENCE_LIMIT_MS) {
                    // Silence limit reached! Stop!
                    console.log("🤫 Silence limit reached.");
                    stopSmartRecording();
                    return;
                }
            } else {
                // Sound detected!
                silenceStart = Date.now();
                if (!smartSpeechDetected) {
                    smartSpeechDetected = true; // ✅ Valid speech detected
                    console.log("🗣️ Speech detected!");
                    statusText.innerText = '🎤 Je vous écoute...';
                    statusText.style.color = '#fff';
                    recordBtn.classList.add('active-speech');
                }
            }

            animationId = requestAnimationFrame(detectSilence);
        }

        detectSilence(); // Start monitoring

        // 2. Start Speech Recognition (Instant Mode)
        try { startRealTimeTranscription(); } catch (e) { }

        // 3. Start MediaRecorder
        mediaRecorder = new MediaRecorder(stream);
        audioChunks = [];
        mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
        mediaRecorder.onstop = async () => {
            console.log("🛑 Recorder stopped. Processing audio...");

            // Clean up
            if (recognition) { try { recognition.stop(); } catch (e) { } }
            if (animationId) cancelAnimationFrame(animationId);
            if (micSource) micSource.disconnect();
            if (audioContext) audioContext.close();

            if (audioChunks.length > 0) {
                const blob = new Blob(audioChunks, { type: 'audio/wav' });
                console.log(`📦 Audio Data: ${blob.size} bytes`);

                // FORCE PROCESSING - UI Feedback
                statusText.innerText = 'Traitement...';
                statusText.style.color = '#4a9b87';

                try {
                    await processAudio(blob);
                } catch (e) {
                    console.error("Error in processAudio", e);
                    statusText.innerText = 'Erreur';
                }
            } else {
                console.error("❌ Audio was empty!");
                statusText.innerText = 'Audio Vide';
            }

            // 🔄 AUTO-RESTART LOOP (Crucial for Continuous Conversation)
            if (window.continuousMode) {
                // 🛑 CRITICAL FIX: DO NOT RESTART IF TTS IS PLAYING!
                if (isTTSPlaying && window.lastBotAudio) {
                    console.log("⏸️ TTS Playing - Waiting for audio to finish before restarting...");

                    // Chain the restart to the onended event
                    const originalEnded = window.lastBotAudio.onended;
                    window.lastBotAudio.onended = () => {
                        if (originalEnded) originalEnded();
                        console.log("✅ TTS Finished - Restarting conversation loop");
                        // Small delay to ensure clean state
                        setTimeout(() => {
                            if (window.continuousMode) listenContinuously();
                        }, 100);
                    };
                    return;
                } else {
                    // No audio playing, restart immediately
                    console.log("🔄 Auto-restarting conversation loop (No TTS active)...");
                    setTimeout(() => {
                        if (window.continuousMode) listenContinuously();
                    }, 100);
                }
            } else {
                statusText.innerText = 'Prêt';
            }
        };
        mediaRecorder.start();
        console.log("🎤 Recording started (with Auto-Stop)...");

    } catch (err) {
        console.error(err);
        statusText.innerText = "Erreur Micro";
        isRecording = false;
        recordBtn.classList.remove('active');
    }
}

function stopSmartRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') mediaRecorder.stop();
    if (recognition) { try { recognition.stop(); } catch (e) { } }
    isRecording = false;
    recordBtn.classList.remove('active');
    statusText.innerText = 'Réflexion...';
}

// [Function setupRealTimeTranscription removed - Consolidated into startRealTimeTranscription]

function debouncedStreamTranslation(text) {
    if (streamTimeout) clearTimeout(streamTimeout);
    streamTimeout = setTimeout(() => performStreamTranslation(text), 200);
}

async function performStreamTranslation(text) {
    try {
        const res = await axios.post('/stream_text', {
            text: text,
            target_lang: quickLangSelector?.value || 'English'
        });
        if (res.data.translation) {
            translatedTextField.innerText = res.data.translation;

            // ✨ SHOW TRANSLATION CARD - Make it visible!
            if (res.data.translation.trim().length > 0) {
                translatedTextField.style.opacity = '1';
                console.log('🌍 Real-time translation:', res.data.translation);
            }
        }
    } catch (e) { console.error("Stream Error", e); }
}

// Helper function to analyze audio energy and detect silence
function analyzeAudioEnergy(blob) {
    return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsArrayBuffer(blob);
        reader.onloadend = async () => {
            try {
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const audioBuffer = await audioContext.decodeAudioData(reader.result);

                // Get audio samples
                const channelData = audioBuffer.getChannelData(0);

                // Calculate RMS (Root Mean Square) energy
                let sum = 0;
                for (let i = 0; i < channelData.length; i++) {
                    sum += channelData[i] * channelData[i];
                }
                const rms = Math.sqrt(sum / channelData.length);

                // Calculate peak amplitude
                let peak = 0;
                for (let i = 0; i < channelData.length; i++) {
                    const abs = Math.abs(channelData[i]);
                    if (abs > peak) peak = abs;
                }

                // Duration in seconds
                const duration = audioBuffer.duration;

                console.log(`🔊 Audio Analysis: RMS=${rms.toFixed(4)}, Peak=${peak.toFixed(4)}, Duration=${duration.toFixed(2)}s`);

                // 🛡️ WAR MODE SENSITIVITY: Pick up even whispers (0.002)
                // Was 0.01 - Lowered to prevent cutting out during "Chaos"
                resolve({ rms, peak, duration, isSilent: rms < 0.002 && peak < 0.01 });
            } catch (e) {
                console.error('⚠️ Audio analysis failed:', e);
                resolve({ rms: 0, peak: 0, duration: 0, isSilent: true });
            }
        };
    });
}

async function processAudio(blob, bypassSilenceCheck = false) {
    // 🚀 PREVENT DUPLICATE PROCESSING
    if (isProcessingAudio) {
        console.log('⚠️ Audio already being processed, skipping...');
        return;
    }

    isProcessingAudio = true;
    recordBtn.classList.add('processing'); // 🔵 Visual Feedback: Blue Spinner
    recordBtn.classList.remove('active');   // Stop Red pulse
    recordBtn.classList.remove('active-speech'); // Stop Green pulse

    // 🔊 CRITICAL: SILENCE DETECTION - Prevent hallucination
    // ⚡ OPTIMIZATION: If we already confirmed speech in monitorAudio, skip this heavy decoding!
    if (!bypassSilenceCheck) {
        const audioAnalysis = await analyzeAudioEnergy(blob);

        // Reject if audio is too quiet (silence/background noise)
        if (audioAnalysis.isSilent) {
            console.warn('🔇 SILENCE DETECTED (Threshold check failed) - Skipping processing');
            console.log(`📊 Analysis: RMS=${audioAnalysis.rms}, Peak=${audioAnalysis.peak}`);
            statusText.innerText = 'Trop silencieux';
            isProcessingAudio = false;

            // Reset UI
            // ⚡ WAR MODE: Restart INSTANTLY (100ms) insead of 1s
            setTimeout(() => {
                statusText.innerText = 'Prêt';
                // Force restart if in continuous mode!
                if (window.continuousMode) listenContinuously();
            }, 100);
            return;
        }

        // Reject if audio is too short (likely just a click)
        if (audioAnalysis.duration < 0.5) {
            console.log(`⏱️ Audio too short (${audioAnalysis.duration.toFixed(2)}s) - Skipping`);
            statusText.innerText = 'Audio trop court';
            isProcessingAudio = false;

            setTimeout(() => {
                statusText.innerText = 'Prêt';
                if (window.continuousMode) listenContinuously();
            }, 800);
            return;
        }
    } else {
        console.log("⚡ SPEED: Bypassing secondary silence check (Speech already confirmed)");
    }

    console.log('✅ Audio validation passed - Processing...');

    const startTime = Date.now();
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = async () => {
        const base64 = reader.result.split(',')[1];
        try {
            // 🚀 STEAL THE MICROPHONE (Client-Side STT Injection)
            // Use the global variable captured by Web Speech API directly!
            // This is cleaner than reading DOM.
            let textInput = (window.currentTranscript || originalTextField.innerText || "").trim();

            // Clean up placeholders
            textInput = textInput.replace('...', '').replace('🎤', '').trim();

            // Filter out placeholder indicators
            if (textInput.includes('Écoute') || textInput.length < 2) {
                textInput = ''; // Empty = backend will use Whisper/Gemini transcription
                console.log('🎯 Using backend STT only (no client text available)');
            } else {
                console.log(`🎤 Client-Side STT Injected: "${textInput}" (Skipping Server STT)`);
            }

            // Get languages from quick selectors
            const targetLangQuick = document.getElementById('target-lang-quick');
            const sourceLangQuick = document.getElementById('source-lang-quick');
            const selectedTarget = targetLangQuick?.value || quickLangSelector?.value || 'French';
            const selectedSource = sourceLangQuick?.value || 'auto';

            const settings = {
                audio: base64,
                text_input: textInput,  // Only send real transcribed text, not placeholders
                target_language: selectedTarget,
                source_language: selectedSource === 'auto' ? 'auto' : selectedSource, // Pass manual selection to backend
                stt_engine: localStorage.getItem('sttEngine') || 'openai-whisper', // ⚡ WHISPER (Requested by User)
                model: localStorage.getItem('aiModel') || 'gpt-4o-mini',  // ✅ CHATGPT (Requested by User)
                tts_engine: localStorage.getItem('ttsEngine') || 'seamless', // 🔊 SEAMLESS TTS (Kaggle GPU - FREE!)
                openai_api_key: localStorage.getItem('openaiKey'),
                google_api_key: localStorage.getItem('googleKey'),  // ✅ For Gemini STT
                openai_voice: localStorage.getItem('openaiVoice') || 'nova',
                elevenlabs_key: localStorage.getItem('elevenlabsKey'),  // Fixed: elevenlabs_key not elevenlabs_api_key
                use_grammar_correction: localStorage.getItem('grammarCorrectionEnabled') !== 'false',  // Default: enabled
                voice_gender_preference: localStorage.getItem('voiceGenderPreference') || 'auto'  // 🎙️ Voice gender: auto/male/female
            };

            console.log(`📝 Grammar Correction: ${settings.use_grammar_correction ? 'ENABLED (GPT)' : 'DISABLED (Direct Translation)'}`);
            console.log(`🎙️ Voice Gender Preference: ${settings.voice_gender_preference.toUpperCase()}`);


            // VOICE CLONING LOGIC - Check if enabled via toggle
            // 🚀 SPEED FIRST: Default is DISABLED for instant translations
            const voiceCloneEnabled = localStorage.getItem('voiceCloneEnabled') === 'true'; // Default: DISABLED
            const ttsEngine = settings.tts_engine;

            console.log(`🎭 Voice Cloning Status: ${voiceCloneEnabled ? 'ENABLED' : 'DISABLED'}`);

            // Send voice cloning data if enabled
            if (voiceCloneEnabled) {
                console.log('🎤 Voice Cloning ENABLED → Sending audio sample to server');
                settings.voice_audio = `data:audio/wav;base64,${base64}`;
                settings.voice_cloning = true;
            } else {
                console.log('🔇 Voice Cloning DISABLED → Using gender-matched fallback voices');
                settings.voice_cloning = false;
            }

            const res = await axios.post('/process_audio', settings);

            if (res.data.translated_text) {
                const translation = res.data.translated_text;
                const userText = settings.text_input;

                console.log('✅ Response received:', {
                    original: userText?.substring(0, 50),
                    translation: translation?.substring(0, 50),
                    hasAudio: !!res.data.tts_audio
                });

                // 🔊 FORCE DISPLAY RESULT (Fallback)
                const resultDisplay = document.getElementById('result-display');
                const originalDisplay = document.getElementById('original-display');
                const translationDisplay = document.getElementById('translation-display');
                const pronunciationDisplay = document.getElementById('pronunciation-display');
                const greeting = document.getElementById('greeting');

                if (resultDisplay && translationDisplay) {
                    if (greeting) greeting.style.display = 'none';
                    resultDisplay.style.display = 'block';
                    if (originalDisplay) originalDisplay.innerText = userText || 'Audio input';

                    // Pronunciation
                    if (pronunciationDisplay) {
                        const pronunciation = res.data.pronunciation;
                        if (pronunciation && pronunciation !== translation) {
                            pronunciationDisplay.innerText = pronunciation;
                            pronunciationDisplay.style.display = 'block';
                        } else {
                            pronunciationDisplay.style.display = 'none';
                        }
                    }

                    translationDisplay.innerText = translation;
                    console.log('📺 Result displayed on screen');
                }

                // 🔊 FORCE PLAY AUDIO
                if (res.data.tts_audio) {
                    const audioSrc = `data:audio/mp3;base64,${res.data.tts_audio}`;
                    const audio = new Audio(audioSrc);
                    audio.play().then(() => {
                        console.log('🔊 Audio playing!');
                    }).catch(err => {
                        console.log('❌ Auto-play blocked:', err);
                        // Show play button
                        if (translationDisplay) {
                            translationDisplay.innerHTML += ' <button onclick="this.previousSibling.click()" style="background:#4CAF50;color:white;border:none;padding:5px 10px;border-radius:5px;cursor:pointer;">▶️ Play</button>';
                        }
                    });
                    window.lastAudio = audio;
                }

                // 🛡️ HALLUCINATION CHECK - Block fake Whisper outputs
                // userText already defined above
                if (isHallucination(userText) || isHallucination(translation)) {
                    console.log(`🚫 HALLUCINATION DETECTED - Skipping message creation`);
                    console.log(`   User: "${userText}" | Translation: "${translation}"`);
                    statusText.innerText = 'Prêt';
                    isProcessingAudio = false;
                    recordBtn.classList.remove('processing');
                    return;
                }

                // AUTOMATIC LANGUAGE DETECTION - Update UI
                if (res.data.source_language_full && sourceLangSelector) {
                    const detectedLang = res.data.source_language_full;

                    // Store detected language for potential future auto-selection
                    detectedLanguage = detectedLang;
                    console.log(`🌍 Language auto-detected: ${detectedLang}`);

                    // Update real-time transcription language for next recording
                    if (recognition) {
                        const langMap = {
                            'English': 'en-US', 'French': 'fr-FR', 'Spanish': 'es-ES',
                            'German': 'de-DE', 'Italian': 'it-IT', 'Portuguese': 'pt-PT',
                            'Russian': 'ru-RU', 'Japanese': 'ja-JP', 'Korean': 'ko-KR',
                            'Chinese': 'zh-CN', 'Arabic': 'ar-SA', 'Hindi': 'hi-IN',
                            'Dutch': 'nl-NL', 'Polish': 'pl-PL', 'Turkish': 'tr-TR',
                            'Indonesian': 'id-ID', 'Malay': 'ms-MY', 'Thai': 'th-TH',
                            'Vietnamese': 'vi-VN', 'Bengali': 'bn-IN', 'Urdu': 'ur-PK',
                            'Swahili': 'sw-KE', 'Hebrew': 'he-IL', 'Persian': 'fa-IR',
                            'Ukrainian': 'uk-UA', 'Swedish': 'sv-SE', 'Greek': 'el-GR',
                            'Czech': 'cs-CZ', 'Romanian': 'ro-RO', 'Hungarian': 'hu-HU',
                            'Danish': 'da-DK', 'Finnish': 'fi-FI', 'Norwegian': 'no-NO',
                            'Slovak': 'sk-SK', 'Filipino': 'fil-PH', 'Amharic': 'am-ET'
                        };

                        const speechLang = langMap[detectedLang] || navigator.language || 'en-US';
                        console.log(`🎤 Speech recognition updated to: ${speechLang}`);
                    }
                }

                // Hide greeting
                const greetingEl = document.getElementById('greeting');
                if (greetingEl) greetingEl.style.display = 'none';

                // 2. Add User Message to Chat (with source language)
                // userText already defined above for hallucination check
                const sourceLang = res.data.source_language_full || 'Auto';
                const targetLang = res.data.target_language || 'Translation';
                createChatMessage('user', userText, null, null, sourceLang);

                // 3. Create NEW audio for this message
                let messageAudioSrc = null;
                if (res.data.tts_audio) {
                    messageAudioSrc = `data:audio/mp3;base64,${res.data.tts_audio}`;
                    // Play on global player
                    audioPlayer.src = messageAudioSrc;
                    audioPlayer.play().catch(err => {
                        console.log('Auto-play blocked:', err);
                    });
                }

                // 4. Add Bot Message with its OWN Audio Player (with target language)
                const info = {
                    latency: ((Date.now() - startTime) / 1000).toFixed(2),
                    stt: res.data.stt_engine,
                    translation: res.data.translation_engine,
                    tts: res.data.tts_engine
                };
                createChatMessage('bot', translation, messageAudioSrc, info, targetLang);

                // 🎙️ IMPORTANT: Update status based on mode
                if (window.continuousMode) {
                    // Keep button active in continuous mode
                    statusText.innerText = 'Écoute en continu...';
                    console.log('✅ TTS généré - En attente de la prochaine phrase');
                } else {
                    // Normal mode: reset button
                    isRecording = false;
                    recordBtn.classList.remove('active');
                    recordBtn.disabled = false;
                    statusText.innerText = 'Prêt';
                    console.log('✅ TTS généré - Bouton prêt');
                }
            }
        } catch (e) {
            console.error("Erreur de traitement:", e);
            statusText.innerText = "Erreur de connexion";

            // Re-enable button even on error
            isRecording = false;
            recordBtn.classList.remove('active');
            recordBtn.disabled = false;
        }
        finally {
            // Ensure button is always ready
            recordBtn.disabled = false;
            recordBtn.classList.remove('processing'); // 🔵 Stop Blue Spinner
            isProcessingAudio = false; // 🚀 Reset processing flag

            // If NOT continuous mode, ensure text says Ready
            if (!window.continuousMode) {
                statusText.innerText = 'Prêt';
            }
        }
    };
}

// Logic de sauvegarde/chargement des paramètres
window.loadModalSettings = () => {
    document.getElementById('stt-engine').value = localStorage.getItem('sttEngine') || 'openai-whisper';
    document.getElementById('openai-key').value = localStorage.getItem('openaiKey') || '';
    if (localStorage.getItem('sourceLang')) document.getElementById('source-lang-selector').value = localStorage.getItem('sourceLang');

    // 🎯 Set default target language for bidirectional translation
    const savedTargetLang = localStorage.getItem('targetLang');
    if (savedTargetLang && quickLangSelector) {
        quickLangSelector.value = savedTargetLang;
    } else if (quickLangSelector) {
        // Default to French for Arabic ↔ French bidirectional translation
        quickLangSelector.value = 'French';
        console.log('🌍 Default target language set to French for bidirectional translation');
    }
};

window.saveModalSettings = () => {
    localStorage.setItem('sttEngine', document.getElementById('stt-engine').value);
    localStorage.setItem('openaiKey', document.getElementById('openai-key').value);
    localStorage.setItem('targetLang', quickLangSelector.value);
    localStorage.setItem('sourceLang', document.getElementById('source-lang-selector').value);
};

// Removed: replay-trigger button (deleted from HTML)
// Functionality removed as button no longer exists

// ===================================
// 🛠️ BUTTON TOGGLE LOGIC (FIXED)
// ===================================

function setupToggle(id, storageKey, defaultValue, onToggle) {
    const btn = document.getElementById(id);
    if (!btn) return;

    // Load initial state
    const saved = localStorage.getItem(storageKey);
    const isActive = saved === null ? defaultValue : saved === 'true';

    if (isActive) btn.classList.add('active');
    else btn.classList.remove('active');

    btn.addEventListener('click', (e) => {
        e.stopPropagation(); // Prevent bubbling
        const currentlyActive = btn.classList.contains('active');
        const newState = !currentlyActive;

        // Toggle visual
        if (newState) btn.classList.add('active');
        else btn.classList.remove('active');

        // Save state
        localStorage.setItem(storageKey, newState);

        // Optional callback
        if (onToggle) onToggle(newState);

        console.log(`🔘 Toggle ${id}: ${newState ? 'ON' : 'OFF'}`);
    });
}

function setupCycle(id, storageKey, values, onCycle) {
    const btn = document.getElementById(id);
    if (!btn) return;

    // Load initial state
    let currentVal = localStorage.getItem(storageKey) || values[0];
    if (!values.includes(currentVal)) currentVal = values[0]; // Fallback

    const updateVisual = (val) => {
        // Remove all active classes first if needed, or just set generic active
        // For gender, we might want different icons? 
        // For now, simple active state if not default
        if (val !== values[0]) btn.classList.add('active');
        else btn.classList.remove('active');

        // Tooltip feedback
        btn.title = `Mode: ${val.toUpperCase()}`;
    };

    updateVisual(currentVal);

    btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const currentIndex = values.indexOf(currentVal);
        const nextIndex = (currentIndex + 1) % values.length;
        currentVal = values[nextIndex];

        localStorage.setItem(storageKey, currentVal);
        updateVisual(currentVal);

        if (onCycle) onCycle(currentVal);
        console.log(`🔄 Cycle ${id}: ${currentVal}`);

        // Visual text feedback (Toast)
        statusText.innerText = `Mode: ${currentVal.toUpperCase()}`;
        setTimeout(() => statusText.innerText = 'Prêt', 1500);
    });
}

// 🎯 Initialize Toggles when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    // 1. Magic/Grammar Toggle
    setupToggle('grammar-toggle', 'grammarCorrectionEnabled', true, (state) => {
        statusText.innerText = state ? '✨ Correction: ON' : '📝 Correction: OFF';
        setTimeout(() => statusText.innerText = 'Prêt', 1500);
    });

    // 2. Voice Gender Toggle (Auto -> Male -> Female)
    setupCycle('voice-gender-toggle', 'voiceGenderPreference', ['auto', 'male', 'female']);

    // 3. Smart Mode Toggle (Brain)
    setupToggle('smart-mode-toggle', 'smartModeEnabled', true, (state) => {
        statusText.innerText = state ? '🧠 Mode Smart: ON' : '🧠 Mode Smart: OFF';
        setTimeout(() => statusText.innerText = 'Prêt', 1500);
    });
});

// ⚙️ SETTINGS MODAL LOGIC (Fixing the "Broken Button")
document.addEventListener('DOMContentLoaded', () => {
    const settingsBtn = document.getElementById('settings-trigger'); // Found ID
    const closeSettingsBtn = document.getElementById('close-settings');
    const settingsModal = document.getElementById('settings-modal');

    // Open
    if (settingsBtn && settingsModal) {
        settingsBtn.addEventListener('click', () => {
            settingsModal.style.display = 'flex'; // Or remove hidden class
            // settingsModal.classList.remove('hidden'); // If using classes
            console.log('⚙️ Settings Opened');
        });
    } else {
        console.error('❌ Settings Trigger or Modal NOT FOUND');
    }

    // Close Button
    if (closeSettingsBtn && settingsModal) {
        closeSettingsBtn.addEventListener('click', () => {
            settingsModal.style.display = 'none';
        });
    }

    // Close on Outside Click
    window.addEventListener('click', (e) => {
        if (e.target === settingsModal) {
            settingsModal.style.display = 'none';
        }
    });

    // 💾 SAVE & LOAD LOGIC
    const saveBtn = document.getElementById('save-settings');
    const aiSelector = document.getElementById('ai-model-selector');
    const ttsSelector = document.getElementById('tts-selector');

    // Load Initial Values
    if (aiSelector) aiSelector.value = localStorage.getItem('aiModel') || 'gpt-4o-mini';
    if (ttsSelector) ttsSelector.value = localStorage.getItem('ttsEngine') || 'openai';

    // Save Handler
    if (saveBtn) {
        saveBtn.addEventListener('click', () => {
            if (aiSelector) {
                localStorage.setItem('aiModel', aiSelector.value);
                console.log(`🧠 AI Model set to: ${aiSelector.value}`);
            }
            if (ttsSelector) {
                localStorage.setItem('ttsEngine', ttsSelector.value);
                console.log(`🗣️ TTS Engine set to: ${ttsSelector.value}`);
            }

            // Close Modal
            if (settingsModal) settingsModal.style.display = 'none';

            // Feedback
            if (statusText) {
                statusText.innerText = '✅ Sauvegardé!';
                setTimeout(() => statusText.innerText = 'Prêt', 2000);
            }
        });
    }
});


// 🎯 Initialize language settings on page load
document.addEventListener('DOMContentLoaded', () => {
    // Set default target language for bidirectional translation
    if (quickLangSelector) {
        const savedTargetLang = localStorage.getItem('targetLang');
        if (savedTargetLang) {
            quickLangSelector.value = savedTargetLang;
            console.log(`🌍 Loaded saved target language: ${savedTargetLang}`);
        } else {
            quickLangSelector.value = 'French';
            console.log('🌍 Default target language set to French for Arabic ↔ French bidirectional translation');
        }
    }

    // Set source to auto for automatic detection
    const sourceLangSelector = document.getElementById('source-lang-selector');
    if (sourceLangSelector) {
        sourceLangSelector.value = 'auto';
        console.log('🎯 Source language set to AUTO for automatic detection');

        // 🔄 HARD SYNC: If user changes Source, clear "Smart History" to prevent confusion
        sourceLangSelector.addEventListener('change', function () {
            console.log('🔄 Source Language Changed -> Clearing Smart History...');
            localStorage.setItem('sourceLang', this.value);
            fetch('/clear_cache', { method: 'POST' });
        });
    }

    // 🔄 HARD SYNC: If user changes Target, clear "Smart History" to prevent confusion
    if (quickLangSelector) {
        quickLangSelector.addEventListener('change', function () {
            console.log('🔄 Target Language Changed -> Clearing Smart History...');
            localStorage.setItem('targetLang', this.value);
            fetch('/clear_cache', { method: 'POST' });
        });
    }

    // ===================================
    // 🎭 VOICE CLONING TOGGLE
    // ===================================
    let voiceCloneEnabled = localStorage.getItem('voiceCloneEnabled') !== 'false'; // Default: ON

    const voiceCloneToggle = document.getElementById('voice-clone-toggle');
    if (voiceCloneToggle) {
        // Set initial state
        if (voiceCloneEnabled) {
            voiceCloneToggle.classList.add('active');
        } else {
            voiceCloneToggle.classList.remove('active');
        }

        // Toggle on click
        voiceCloneToggle.addEventListener('click', function () {
            voiceCloneEnabled = !voiceCloneEnabled;
            localStorage.setItem('voiceCloneEnabled', voiceCloneEnabled);

            if (voiceCloneEnabled) {
                this.classList.add('active');
                console.log('🎭 Voice Cloning: ON');
            } else {
                this.classList.remove('active');
                console.log('🎭 Voice Cloning: OFF');
            }
        });
    }

});