Spaces:
Sleeping

File size: 37,778 Bytes
f9ccbb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ headline }} - TRON Voice News</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,700;1,400&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc;
        }
        .toi-header {
            font-family: 'Playfair Display', serif;
            letter-spacing: 0.05em;
        }
        .toi-body {
            font-family: Georgia, serif;
            line-height: 1.8;
            color: #1f2937;
        }
        /* Custom scrollbar for transcripts */
        .custom-scrollbar::-webkit-scrollbar {
            width: 5px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
            background: #020617;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #1e293b;
            border-radius: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #334155;
        }
    </style>
</head>
<body class="min-h-screen text-slate-800 flex flex-col justify-between">
    <!-- Configuration Injectors -->
    <script>
        // Global variables for backend connectivity and assistant configuration
        const BACKEND_URL = "{{ backend_url }}"; 
        const TRON_CONFIG = {{ tron_config | tojson }};
    </script>

    <!-- Header bar -->
    <header class="border-b border-slate-200 bg-white sticky top-0 z-30 shadow-sm">
        <div class="max-w-4xl mx-auto px-6 py-4 flex items-center justify-between">
            <div class="flex items-center space-x-3">
                <div class="w-8 h-8 rounded-lg bg-neutral-900 flex items-center justify-center">
                    <span class="text-lg font-bold text-white toi-header">T</span>
                </div>
                <div>
                    <h1 class="text-sm font-bold text-neutral-900">TRON</h1>
                    <p class="text-[10px] text-neutral-500 font-semibold tracking-wider uppercase">Voice-Activated Article</p>
                </div>
            </div>
            <a href="/" class="text-xs font-semibold text-indigo-600 hover:text-indigo-800 transition-colors flex items-center space-x-1">
                <span>← Back to Dashboard</span>
            </a>
        </div>
    </header>

    <!-- Article layout -->
    <main class="flex-1 max-w-4xl w-full mx-auto px-6 py-12">
        <article class="bg-white rounded-3xl p-8 md:p-12 border border-slate-200 shadow-xl space-y-8">
            <!-- TOI Masthead Replica -->
            <div class="text-center border-b-4 border-double border-neutral-900 pb-4">
                <div class="text-xs uppercase tracking-widest font-serif font-bold text-neutral-500 flex justify-between px-1">
                    <span>Established 1838</span>
                    <span>The Times of India</span>
                    <span>Daily Edition</span>
                </div>
                <h1 class="text-4xl md:text-5xl font-serif font-black tracking-normal toi-header my-3 text-neutral-950">THE TIMES OF INDIA</h1>
                <div class="text-xs border-t border-neutral-900 pt-2 flex justify-between font-serif italic text-neutral-700">
                    <span>Reg. No. Delhi-0912</span>
                    <span>{{ date }}</span>
                    <span>Price: ₹ 5.00</span>
                </div>
            </div>

            <!-- Headline -->
            <div class="space-y-4">
                <h1 class="text-2xl md:text-3.5xl font-bold font-serif leading-tight text-neutral-950 tracking-tight">{{ headline }}</h1>
                
                <!-- Metadata line -->
                <div class="text-xs text-neutral-600 border-b border-neutral-200 pb-3 font-serif flex items-center justify-between">
                    <span>By <strong class="text-neutral-900">{{ author }}</strong></span>
                    <span>{{ date }}</span>
                </div>
            </div>

            <!-- Columns layout -->
            <div class="toi-body text-base md:text-md text-justify space-y-4 columns-1 md:columns-2 gap-8">
                {% for para in body.split('\n') %}
                    {% if para.strip() %}
                        <p class="mb-4 indent-4">{{ para.strip() }}</p>
                    {% endif %}
                {% endfor %}
            </div>

            <!-- CTA Talk to Tron Button -->
            <div class="border-t border-neutral-200 pt-8 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div class="text-xs text-neutral-500 font-serif italic">
                    * This investigative report includes a voice-activated assistant grounded in local research.
                </div>
                <button id="btn-talk-to-tron" class="w-full sm:w-auto px-6 py-3.5 rounded-xl bg-gradient-to-r from-neutral-900 to-slate-800 hover:from-neutral-800 hover:to-slate-700 text-white font-semibold text-sm flex items-center justify-center space-x-3 transition-all shadow-lg shadow-neutral-900/10 active:scale-95">
                    <svg class="w-5 h-5 text-cyan-400 animate-pulse" fill="currentColor" viewBox="0 0 24 24"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>
                    <span>Talk to Tron</span>
                </button>
            </div>
        </article>
    </main>

    <!-- Side Drawer Popup overlay -->
    <div id="side-drawer" class="fixed inset-y-0 right-0 w-full sm:w-[420px] bg-slate-950 border-l border-slate-800 z-50 transform translate-x-full transition-transform duration-300 ease-out shadow-2xl flex flex-col justify-between text-slate-100 hidden">
        <!-- Drawer Header -->
        <div class="p-6 border-b border-slate-900 flex items-center justify-between bg-slate-950/80 backdrop-blur-md">
            <div class="flex items-center space-x-3">
                <span class="relative flex h-3 w-3">
                    <span id="status-pulse" class="animate-ping absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"></span>
                    <span id="status-dot" class="relative inline-flex rounded-full h-3 w-3 bg-cyan-500"></span>
                </span>
                <div>
                    <h3 class="font-bold text-sm tracking-wide">TRON ASSISTANT</h3>
                    <p id="connection-status" class="text-[10px] text-slate-400 font-semibold uppercase">Connecting...</p>
                </div>
            </div>
            <button id="btn-close-drawer" class="text-slate-500 hover:text-white transition-colors p-1.5 rounded-lg hover:bg-slate-900">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </div>

        <!-- Drawer Content -->
        <div class="flex-1 overflow-y-auto p-6 space-y-6 flex flex-col justify-between custom-scrollbar">
            <!-- Visualizer Container -->
            <div class="flex flex-col items-center justify-center py-6 bg-slate-900/30 border border-slate-900 rounded-2xl relative overflow-hidden">
                <canvas id="visualizer-canvas" class="w-full h-44"></canvas>
                <div id="orb-label" class="absolute bottom-4 text-[10px] text-slate-500 font-bold tracking-widest uppercase">Voice Orb Activator</div>
            </div>

            <!-- Notes Section (Dynamic) -->
            <div id="note-container" class="hidden animate-bounce mt-2">
                <a id="btn-download-note" href="#" target="_blank" class="w-full py-3.5 px-4 rounded-xl bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700 text-white font-bold text-xs uppercase tracking-wider flex items-center justify-center space-x-2 transition-all shadow-lg shadow-emerald-500/20 active:scale-95">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                    <span id="note-btn-label">Download Requested Note</span>
                </a>
            </div>

            <!-- Text Input Option -->
            <div class="space-y-2 mt-4">
                <label class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Type Your Question</label>
                <div class="flex gap-2">
                    <input id="input-chat" type="text" placeholder="Type a question or correction..." class="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-slate-100 placeholder-slate-500 focus:outline-none focus:border-cyan-500 transition-colors" />
                    <button id="btn-send-chat" class="px-4 py-2.5 rounded-xl bg-cyan-600 hover:bg-cyan-700 text-white font-bold text-xs transition-all active:scale-95 flex items-center justify-center">
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                    </button>
                </div>
            </div>

            <!-- Transcripts area -->
            <div class="space-y-2 flex-1 flex flex-col justify-end mt-4">
                <label class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Live Logs / Transcripts</label>
                <div id="transcript-box" class="h-48 overflow-y-auto bg-slate-950 border border-slate-900 rounded-xl p-4 text-xs font-mono text-slate-300 space-y-3 custom-scrollbar flex flex-col justify-start">
                    <div class="text-slate-600 italic">No dialogue yet. Click Activate to talk.</div>
                </div>
            </div>

            <!-- Dispute email notification banner -->
            <div id="dispute-banner" class="hidden bg-red-950/40 border border-red-900/60 rounded-xl p-3 text-[11px] text-red-300 flex items-start space-x-2">
                <svg class="w-4 h-4 text-red-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
                <div>
                    <span class="font-bold">Editorial Dispute Sent:</span> Alerts containing reader suggested corrections have been dispatched to the editorial desk.
                </div>
            </div>
        </div>

        <!-- Drawer Footer Controls -->
        <div class="p-6 border-t border-slate-900 bg-slate-950/80 backdrop-blur-md flex items-center justify-between gap-4">
            <!-- Mute/Unmute microphone button -->
            <button id="btn-toggle-mic" class="flex-1 py-3 px-4 rounded-xl bg-slate-900 border border-slate-800 text-slate-300 hover:text-white font-semibold text-xs flex items-center justify-center space-x-2 transition-all active:scale-95">
                <svg id="mic-icon-on" class="w-4 h-4 text-cyan-400" fill="currentColor" viewBox="0 0 24 24"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>
                <svg id="mic-icon-off" class="w-4 h-4 text-red-500 hidden" fill="currentColor" viewBox="0 0 24 24"><path d="M19 11h-1.7c0 .74-.16 1.43-.43 2.05l1.23 1.23c.56-.98.9-2.09.9-3.28zm-4.02.17l-1.98-1.98V5c0-1.66-1.34-3-3-3S7 3.34 7 5v.18L8.82 7h-.02v4c0 .32.07.62.17.9l-1.98-1.98c.56-.98.9-2.09.9-3.28zm-5.98 5.75c1.39.81 3.03 1.08 4.67.75l1.45 1.45c-2.31.75-4.83.43-6.92-.9L7 16.92zm11.97 3.05L5.12 5.12 3.88 6.38l4.47 4.47v.15c0 2.76 2.24 5 5 5 .59 0 1.15-.12 1.67-.31l3.52 3.52 1.24-1.24zM12 18c-3.31 0-6-2.69-6-6h2c0 2.21 1.79 4 4 4 .43 0 .83-.09 1.21-.24l1.52 1.52C13.88 17.76 13 18 12 18z"/></svg>
                <span id="mic-label">Listening</span>
            </button>

            <!-- Disconnect session -->
            <button id="btn-disconnect" class="py-3 px-5 rounded-xl bg-red-950/40 hover:bg-red-900 border border-red-900 text-red-300 hover:text-white font-semibold text-xs transition-all active:scale-95">
                Stop
            </button>
        </div>
    </div>

    <!-- Backdrop overlay -->
    <div id="drawer-backdrop" class="fixed inset-0 bg-slate-950/50 backdrop-blur-sm z-40 hidden"></div>

    <!-- Footer -->
    <footer class="border-t border-slate-200 py-6 text-center text-xs text-neutral-500 bg-white">
        <p>© 2026 TRON News Assistant Prototype. Powered by Gemini Multimodal Live API.</p>
    </footer>

    <!-- Interactive script for voice capture & WebSocket streaming -->
    <script>
        const btnTalkToTron = document.getElementById('btn-talk-to-tron');
        const sideDrawer = document.getElementById('side-drawer');
        const btnCloseDrawer = document.getElementById('btn-close-drawer');
        const btnDisconnect = document.getElementById('btn-disconnect');
        const drawerBackdrop = document.getElementById('drawer-backdrop');
        const connectionStatus = document.getElementById('connection-status');
        const statusPulse = document.getElementById('status-pulse');
        const statusDot = document.getElementById('status-dot');
        const transcriptBox = document.getElementById('transcript-box');
        const btnToggleMic = document.getElementById('btn-toggle-mic');
        const micIconOn = document.getElementById('mic-icon-on');
        const micIconOff = document.getElementById('mic-icon-off');
        const micLabel = document.getElementById('mic-label');
        const noteContainer = document.getElementById('note-container');
        const btnDownloadNote = document.getElementById('btn-download-note');
        const noteBtnLabel = document.getElementById('note-btn-label');
        const disputeBanner = document.getElementById('dispute-banner');
        const inputChat = document.getElementById('input-chat');
        const btnSendChat = document.getElementById('btn-send-chat');

        const canvas = document.getElementById('visualizer-canvas');
        const ctx = canvas.getContext('2d');

        let socket = null;
        let isListening = false;
        let mediaStream = null;
        let audioContext = null;
        let scriptProcessor = null;
        let animationFrameId = null;
        let nextPlayTime = 0;
        let activeSources = [];
        let averageVolume = 0; // shared variable for orb visualizer
        let isModelSpeaking = true;
        let analyser = null;
        let playbackAnalyser = null;
        let liveCaptionEl = null;

        // Resample Float32 array to 16000Hz and convert to Int16 PCM ArrayBuffer
        function resampleAndConvertToInt16(buffer, inputSampleRate) {
            const targetSampleRate = 16000;
            let resultBuffer = buffer;
            
            if (inputSampleRate !== targetSampleRate) {
                const ratio = inputSampleRate / targetSampleRate;
                const newLength = Math.round(buffer.length / ratio);
                const resampled = new Float32Array(newLength);
                for (let i = 0; i < newLength; i++) {
                    const index = Math.round(i * ratio);
                    resampled[i] = index < buffer.length ? buffer[index] : 0;
                }
                resultBuffer = resampled;
            }
            
            let l = resultBuffer.length;
            let buf = new Int16Array(l);
            while (l--) {
                // Apply a 4.0x software gain multiplier to boost quiet microphone inputs
                let s = Math.max(-1, Math.min(1, resultBuffer[l] * 4.0));
                buf[l] = Math.round(s < 0 ? s * 0x8000 : s * 0x7FFF);
            }
            return buf.buffer;
        }

        // Open drawer UI
        btnTalkToTron.addEventListener('click', () => {
            sideDrawer.classList.remove('hidden');
            drawerBackdrop.classList.remove('hidden');
            setTimeout(() => {
                sideDrawer.classList.remove('translate-x-full');
            }, 10);
            initSession();
            visualizeOrb();
        });

        // Close drawer UI
        function closeDrawer() {
            sideDrawer.classList.add('translate-x-full');
            drawerBackdrop.classList.add('hidden');
            setTimeout(() => {
                sideDrawer.classList.add('hidden');
            }, 300);
            disconnectSession();
            if (animationFrameId) {
                cancelAnimationFrame(animationFrameId);
                animationFrameId = null;
            }
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }

        btnCloseDrawer.addEventListener('click', closeDrawer);
        btnDisconnect.addEventListener('click', closeDrawer);
        drawerBackdrop.addEventListener('click', closeDrawer);

        // Mute/Unmute mic toggle
        btnToggleMic.addEventListener('click', () => {
            isListening = !isListening;
            if (isListening) {
                micIconOn.classList.remove('hidden');
                micIconOff.classList.add('hidden');
                micLabel.textContent = "Listening";
                btnToggleMic.className = "flex-1 py-3 px-4 rounded-xl bg-slate-900 border border-slate-800 text-slate-300 hover:text-white font-semibold text-xs flex items-center justify-center space-x-2 transition-all active:scale-95";
                setStatus("Listening...", "cyan");
            } else {
                micIconOn.classList.add('hidden');
                micIconOff.classList.remove('hidden');
                micLabel.textContent = "Muted";
                btnToggleMic.className = "flex-1 py-3 px-4 rounded-xl bg-red-950/40 border border-red-950 text-red-400 hover:text-white font-semibold text-xs flex items-center justify-center space-x-2 transition-all active:scale-95";
                setStatus("Muted", "red");
            }
        });

        // Send text query message
        async function sendChatMessage() {
            const text = inputChat.value.trim();
            if (!text) return;
            
            if (socket && socket.readyState === WebSocket.OPEN) {
                // Immediately commit text to transcripts visually
                updateLiveCaption('user', text, true);
                
                // Send text packet via WebSocket
                socket.send(JSON.stringify({
                    type: 'input_text',
                    text: text
                }));
                
                inputChat.value = '';
            } else {
                appendLog("Cannot send message: Not connected to TRON server.", true);
            }
        }

        btnSendChat.addEventListener('click', sendChatMessage);
        inputChat.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                sendChatMessage();
            }
        });

        function setStatus(text, color) {
            connectionStatus.textContent = text;
            if (color === 'cyan') {
                statusPulse.className = "animate-ping absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75";
                statusDot.className = "relative inline-flex rounded-full h-3 w-3 bg-cyan-500";
            } else if (color === 'indigo') {
                statusPulse.className = "animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75";
                statusDot.className = "relative inline-flex rounded-full h-3 w-3 bg-indigo-500";
            } else if (color === 'red') {
                statusPulse.className = "hidden";
                statusDot.className = "relative inline-flex rounded-full h-3 w-3 bg-red-500";
            }
        }

        function appendLog(text, isModel = false) {
            // Remove empty placeholder
            if (transcriptBox.innerHTML.includes('No dialogue yet')) {
                transcriptBox.innerHTML = '';
            }
            const wrapper = document.createElement('div');
            wrapper.className = isModel ? "text-cyan-400 font-semibold" : "text-slate-400";
            wrapper.innerHTML = `<span class="text-slate-600">[${isModel ? 'TRON' : 'YOU'}]</span> ${text}`;
            transcriptBox.appendChild(wrapper);
            transcriptBox.scrollTop = transcriptBox.scrollHeight;
        }

        function updateLiveCaption(role, text, isFinal) {
            if (transcriptBox.innerHTML.includes('No dialogue yet') || transcriptBox.innerHTML.includes('Tron is ready')) {
                transcriptBox.innerHTML = '';
            }

            if (!liveCaptionEl) {
                liveCaptionEl = document.createElement('div');
                liveCaptionEl.id = 'live-caption';
                transcriptBox.appendChild(liveCaptionEl);
            }

            const roleColor = role === 'user' ? 'text-cyan-400' : 'text-indigo-400';
            const roleName = role === 'user' ? 'You' : 'Tron';
            
            liveCaptionEl.className = `${roleColor} font-medium border-l-2 border-current pl-2 py-0.5 my-1 animate-pulse`;
            liveCaptionEl.innerHTML = `<span class="opacity-60 text-[10px] uppercase font-bold tracking-wider mr-1.5">${roleName}:</span> ${text}`;
            
            transcriptBox.scrollTop = transcriptBox.scrollHeight;

            if (isFinal) {
                liveCaptionEl.id = '';
                liveCaptionEl.className = 'text-slate-300 py-1 border-b border-slate-900/50';
                liveCaptionEl.innerHTML = `<span class="${role === 'user' ? 'text-cyan-500' : 'text-indigo-500'} font-semibold mr-1">${roleName}:</span> ${text}`;
                liveCaptionEl = null;
            }
        }

        // Initialize Session
        async function initSession() {
            setStatus("Connecting...", "cyan");
            transcriptBox.innerHTML = '<div class="text-slate-600 italic">Establishing connection to TRON server...</div>';
            noteContainer.classList.add('hidden');
            disputeBanner.classList.add('hidden');
            isListening = true;
            isModelSpeaking = true;
            micIconOn.classList.remove('hidden');
            micIconOff.classList.add('hidden');
            micLabel.textContent = "Listening";
            btnToggleMic.className = "flex-1 py-3 px-4 rounded-xl bg-slate-900 border border-slate-800 text-slate-300 hover:text-white font-semibold text-xs flex items-center justify-center space-x-2 transition-all active:scale-95";

            // Initialize/Resume AudioContexts inside the direct user-gesture handler to prevent browser suspension
            try {
                if (!audioContext) {
                    audioContext = new (window.AudioContext || window.webkitAudioContext)();
                }
                if (audioContext.state === 'suspended') {
                    await audioContext.resume();
                }
                if (!audioCtxPlayback) {
                    audioCtxPlayback = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 24000 });
                    nextPlayTime = audioCtxPlayback.currentTime;
                }
                if (audioCtxPlayback.state === 'suspended') {
                    await audioCtxPlayback.resume();
                }
            } catch (ae) {
                console.warn("Could not pre-initialize AudioContexts:", ae);
            }

            try {
                // Setup WebSocket connection
                socket = new WebSocket(BACKEND_URL);
                socket.binaryType = 'arraybuffer';

                socket.onopen = () => {
                    setStatus("Sending config...", "indigo");
                    // Send Setup configurations immediately
                    socket.send(JSON.stringify({
                        type: 'setup',
                        voice: TRON_CONFIG.voice,
                        system_instruction: TRON_CONFIG.system_instruction,
                        greeting: TRON_CONFIG.greeting,
                        document_context: TRON_CONFIG.document_context,
                        silence_duration_ms: TRON_CONFIG.silence_duration_ms || 1000
                    }));
                };

                socket.onmessage = async (event) => {
                    if (event.data instanceof ArrayBuffer) {
                        // Incoming 24kHz audio bytes from model
                        const int16Array = new Int16Array(event.data);
                        const float32Array = new Float32Array(int16Array.length);
                        for (let i = 0; i < int16Array.length; i++) {
                            float32Array[i] = int16Array[i] / 32768.0;
                        }
                        playAudioChunk(float32Array);
                        setStatus("Speaking...", "indigo");
                    } else {
                        // JSON text control messages
                        try {
                            const msg = JSON.parse(event.data);
                            if (msg.type === 'transcript') {
                                appendLog(msg.text, true);
                            } else if (msg.type === 'interim_input_transcription') {
                                updateLiveCaption('user', msg.text, false);
                            } else if (msg.type === 'input_transcription') {
                                updateLiveCaption('user', msg.text, true);
                            } else if (msg.type === 'output_transcription') {
                                updateLiveCaption('model', msg.text, msg.finished);
                            } else if (msg.type === 'interrupted') {
                                stopAllAudio();
                                appendLog("<em class='text-red-400'>[Interrupted]</em>", true);
                                setStatus("Listening...", "cyan");
                            } else if (msg.type === 'document_ready') {
                                noteBtnLabel.textContent = `Download: ${msg.subject}`;
                                btnDownloadNote.href = msg.download_url;
                                noteContainer.classList.remove('hidden');
                                appendLog(`<span class='text-emerald-400 font-bold'>✓ Word Document Generated!</span> Click download inside drawer.`, true);
                            } else if (msg.type === 'dispute_triggered') {
                                disputeBanner.classList.remove('hidden');
                                appendLog(`<span class='text-red-400 font-bold'>⚠️ dispute filed:</span> "${msg.suggested_correction}" (over "${msg.original_fact}"). Alert dispatched.`, true);
                            } else if (msg.type === 'model_speaking') {
                                if (msg.speaking) {
                                    isModelSpeaking = true;
                                    setStatus("Speaking...", "indigo");
                                } else {
                                    // Add a 500ms delay before unmuting microphone to avoid capturing self-echo
                                    setTimeout(() => {
                                        isModelSpeaking = false;
                                        if (isListening) {
                                            setStatus("Listening...", "cyan");
                                        }
                                    }, 500);
                                }
                            } else if (msg.type === 'ready') {
                                setStatus("Listening...", "cyan");
                                transcriptBox.innerHTML = '<div class="text-slate-500 italic">Tron is ready. Speak now.</div>';
                                startMicrophone();
                            }
                        } catch (err) {
                            console.error("Failed to parse JSON text WebSocket message:", err);
                        }
                    }
                };

                socket.onclose = () => {
                    setStatus("Offline", "red");
                    appendLog("Connection to server closed.");
                    stopMicrophone();
                    stopAllAudio();
                };

                socket.onerror = (err) => {
                    console.error("WebSocket Error:", err);
                    setStatus("Error", "red");
                    appendLog("A WebSocket connection error occurred.");
                };

            } catch (err) {
                console.error("Microphone or WebSocket initialization failed:", err);
                setStatus("Error", "red");
                appendLog("Error: " + err.message);
            }
        }

        // Disconnect Session
        function disconnectSession() {
            if (socket) {
                socket.close();
                socket = null;
            }
            stopMicrophone();
            stopAllAudio();
            if (audioContext) {
                audioContext.close().catch(()=>{});
                audioContext = null;
            }
            playbackAnalyser = null;
            liveCaptionEl = null;
        }

        // Audio Capturing
        async function startMicrophone() {
            try {
                mediaStream = await navigator.mediaDevices.getUserMedia({
                    audio: {
                        echoCancellation: true,
                        noiseSuppression: true,
                        autoGainControl: true
                    }
                });
                if (!audioContext) {
                    audioContext = new (window.AudioContext || window.webkitAudioContext)();
                }
                if (audioContext.state === 'suspended') {
                    await audioContext.resume();
                }
                
                const source = audioContext.createMediaStreamSource(mediaStream);
                
                // Analyser node for local orb visualization
                analyser = audioContext.createAnalyser();
                analyser.fftSize = 256;
                source.connect(analyser);
                
                scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1);
                source.connect(scriptProcessor);
                scriptProcessor.connect(audioContext.destination);
 
                scriptProcessor.onaudioprocess = (e) => {
                    if (socket && socket.readyState === WebSocket.OPEN && isListening && !isModelSpeaking) {
                        const inputData = e.inputBuffer.getChannelData(0);
                        const pcmBuffer = resampleAndConvertToInt16(inputData, audioContext.sampleRate);
                        socket.send(pcmBuffer);
                    }
                };
            } catch (err) {
                console.error("Failed to capture mic:", err);
                appendLog("Microphone Access Blocked or Not Found.");
            }
        }
 
        function stopMicrophone() {
            if (scriptProcessor) {
                scriptProcessor.disconnect();
                scriptProcessor = null;
            }
            if (mediaStream) {
                mediaStream.getTracks().forEach(track => track.stop());
                mediaStream = null;
            }
            analyser = null;
        };

        // Playback incoming audio chunks
        function playAudioChunk(float32Array) {
            if (!audioContext) {
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
                nextPlayTime = audioContext.currentTime;
            }

            if (audioContext.state === 'suspended') {
                audioContext.resume();
            }

            if (!playbackAnalyser) {
                playbackAnalyser = audioContext.createAnalyser();
                playbackAnalyser.fftSize = 256;
                playbackAnalyser.connect(audioContext.destination);
            }

            const buffer = audioContext.createBuffer(1, float32Array.length, 24000);
            buffer.copyToChannel(float32Array, 0);

            const source = audioContext.createBufferSource();
            source.buffer = buffer;
            source.connect(playbackAnalyser);

            activeSources.push(source);
            source.onended = () => {
                activeSources = activeSources.filter(s => s !== source);
                if (activeSources.length === 0 && isListening) {
                    setStatus("Listening...", "cyan");
                }
            };

            const currentTime = audioContext.currentTime;
            if (nextPlayTime < currentTime) {
                nextPlayTime = currentTime;
            }
            source.start(nextPlayTime);
            nextPlayTime += buffer.duration;
        }

        function stopAllAudio() {
            activeSources.forEach(source => {
                try {
                    source.stop();
                } catch (e) {}
            });
            activeSources = [];
            if (audioContext) {
                nextPlayTime = audioContext.currentTime;
            }
        }

        // Pulse Orb Visualizer logic
        function visualizeOrb() {
            const bufferLength = 128;
            const dataArray = new Uint8Array(bufferLength);

            function draw() {
                animationFrameId = requestAnimationFrame(draw);

                let activeAnalyser = null;
                if (activeSources.length > 0 && playbackAnalyser) {
                    activeAnalyser = playbackAnalyser;
                } else if (isListening && !isModelSpeaking && analyser) {
                    activeAnalyser = analyser;
                }

                if (activeAnalyser) {
                    activeAnalyser.getByteFrequencyData(dataArray);
                    let sum = 0;
                    for (let i = 0; i < bufferLength; i++) {
                        sum += dataArray[i];
                    }
                    const average = sum / bufferLength; // 0 to 255
                    averageVolume = averageVolume * 0.8 + average * 0.2;
                } else {
                    averageVolume = averageVolume * 0.95;
                }

                const width = canvas.width = canvas.clientWidth;
                const height = canvas.height = canvas.clientHeight;
                const centerX = width / 2;
                const centerY = height / 2;

                ctx.clearRect(0, 0, width, height);

                // Pulse factor
                let pulse = averageVolume * 0.55;
                if (pulse < 0.5) {
                    // Gentle breathing effect when quiet
                    pulse = (Math.sin(Date.now() / 400) + 1.0) * 1.5;
                }
                const baseRadius = 40 + pulse;

                // Outer neon aura glow
                const gradient = ctx.createRadialGradient(
                    centerX, centerY, baseRadius * 0.2, 
                    centerX, centerY, baseRadius * 1.5
                );
                
                if (isListening && activeSources.length === 0) {
                    // CYAN listening state
                    gradient.addColorStop(0, 'rgba(6, 182, 212, 0.9)');
                    gradient.addColorStop(0.3, 'rgba(6, 182, 212, 0.4)');
                    gradient.addColorStop(0.8, 'rgba(16, 185, 129, 0.1)');
                    gradient.addColorStop(1, 'rgba(0,0,0,0)');
                } else if (activeSources.length > 0) {
                    // INDIGO speaking state
                    gradient.addColorStop(0, 'rgba(99, 102, 241, 0.9)');
                    gradient.addColorStop(0.3, 'rgba(168, 85, 247, 0.4)');
                    gradient.addColorStop(0.8, 'rgba(236, 72, 153, 0.1)');
                    gradient.addColorStop(1, 'rgba(0,0,0,0)');
                } else {
                    // RED muted state
                    gradient.addColorStop(0, 'rgba(239, 68, 68, 0.7)');
                    gradient.addColorStop(0.4, 'rgba(239, 68, 68, 0.2)');
                    gradient.addColorStop(1, 'rgba(0,0,0,0)');
                }

                ctx.fillStyle = gradient;
                ctx.beginPath();
                ctx.arc(centerX, centerY, baseRadius * 1.5, 0, 2 * Math.PI);
                ctx.fill();

                // Inner core orb
                ctx.shadowBlur = 25;
                if (isListening && activeSources.length === 0) {
                    ctx.shadowColor = '#22d3ee'; // cyan-400
                    ctx.fillStyle = '#ffffff';
                } else if (activeSources.length > 0) {
                    ctx.shadowColor = '#a855f7'; // purple-500
                    ctx.fillStyle = '#f8fafc';
                } else {
                    ctx.shadowColor = '#ef4444'; // red-500
                    ctx.fillStyle = '#fca5a5';
                }

                ctx.beginPath();
                ctx.arc(centerX, centerY, baseRadius, 0, 2 * Math.PI);
                ctx.fill();
                ctx.shadowBlur = 0; // reset
            }

            draw();
        }
    </script>
</body>
</html>