File size: 40,247 Bytes
67f8074
 
 
 
 
 
 
f366e55
67f8074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30838e
67f8074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84e1dd3
67f8074
 
 
 
 
 
 
 
 
 
 
 
 
f1684dd
c30838e
 
 
f1684dd
f366e55
67f8074
 
 
f366e55
 
 
 
 
 
 
67f8074
 
 
 
594c79f
 
 
67f8074
 
 
 
 
 
 
 
 
 
f366e55
 
c30838e
f366e55
 
f1684dd
 
 
 
 
f366e55
 
f1684dd
f366e55
f1684dd
f366e55
 
 
 
 
 
f1684dd
f366e55
 
 
 
 
 
 
 
f1684dd
f366e55
 
 
67f8074
 
 
f366e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67f8074
 
 
 
 
 
 
 
 
 
f366e55
67f8074
 
 
f366e55
 
 
 
 
 
 
 
 
 
 
 
67f8074
 
f366e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67f8074
f366e55
 
 
 
 
 
 
 
 
 
 
 
67f8074
 
f366e55
 
 
 
 
 
 
 
 
 
 
 
 
 
67f8074
 
f366e55
 
 
 
 
 
 
 
 
 
 
 
 
67f8074
 
 
 
 
 
 
 
 
f366e55
 
 
 
 
 
 
 
 
 
 
67f8074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594c79f
67f8074
594c79f
 
67f8074
 
 
 
 
 
 
 
594c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67f8074
 
 
c30838e
67f8074
 
 
 
 
594c79f
 
 
 
 
 
 
67f8074
594c79f
 
 
67f8074
 
 
 
 
 
 
 
 
594c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67f8074
 
 
594c79f
67f8074
 
c30838e
67f8074
594c79f
67f8074
 
594c79f
 
67f8074
 
 
 
 
 
 
 
 
c30838e
67f8074
594c79f
67f8074
 
 
 
 
 
594c79f
67f8074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f366e55
67f8074
 
f366e55
67f8074
 
 
 
 
 
 
 
 
 
f366e55
67f8074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f366e55
67f8074
 
 
 
 
 
 
f366e55
 
 
 
 
f1684dd
f366e55
c30838e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f366e55
c30838e
 
f366e55
 
67f8074
84e1dd3
67f8074
d9afb8a
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Gemini Live</title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@300;400;500&family=Sora:wght@300;500&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
<style>
:root{--c1:#5ef2d6;--c2:#8b7bff;--ink:#eef1ff;--dim:#8d96c4;--lv:0}
*{box-sizing:border-box;margin:0;-webkit-tap-highlight-color:transparent}
html,body{height:100%;background:#000;color:var(--ink);font-family:Sora,'Noto Sans Devanagari',system-ui,sans-serif;overflow:hidden}
body::before{content:"";position:fixed;inset:0;z-index:0;background:linear-gradient(180deg,#000 0%,#000 36%,#0a1030 70%,#16206b 100%)}
button{font:inherit;color:inherit;border:0;background:none;cursor:pointer}
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--c1);outline-offset:2px}
svg.i{width:24px;height:24px;stroke:currentColor;fill:none;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
#fx{position:fixed;inset:0;width:100%;height:100%;z-index:1;pointer-events:none}
#app{position:relative;z-index:2;max-width:520px;height:100dvh;margin:0 auto;display:grid;grid-template-rows:auto 1fr auto;padding:env(safe-area-inset-top) 0 env(safe-area-inset-bottom);transition:opacity .45s,transform .45s}
body.camopen #app{opacity:0;pointer-events:none;transform:scale(.95)}
header{display:flex;justify-content:space-between;align-items:center;padding:16px 18px}
.ib{width:44px;height:44px;border-radius:50%;display:grid;place-items:center;transition:background .3s,transform .2s}
.ib:hover{background:#ffffff14}.ib:active{transform:scale(.9)}
#chip{display:flex;gap:8px;align-items:center;font-size:12px;color:var(--dim);padding:8px 14px;border-radius:20px;background:#ffffff0d;border:1px solid #ffffff12}
#dot{width:8px;height:8px;border-radius:50%;background:#555b7a;transition:.4s}
body.live #dot{background:var(--c1);box-shadow:0 0 12px var(--c1)}
#stage{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;padding:0 24px;text-align:center;min-height:0}
#ucap,#camucap{font-size:15px;color:var(--dim);min-height:1.3em;max-width:92%}
#cap,#camcap{font-size:clamp(26px,7vw,38px);font-weight:300;line-height:1.38;max-height:46vh;overflow-y:auto;scrollbar-width:none;color:#e9ecfb}
body:not(.live) #cap{background:linear-gradient(90deg,#8d96c4,#fff,#8d96c4);background-size:220% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shim 4.5s linear infinite}
@keyframes shim{to{background-position:-220% 0}}
#cap.status,#camcap.status{animation:breathe 2.4s ease-in-out infinite}
body.live #cap.status{color:#c9cff0}
@keyframes breathe{50%{opacity:.55}}
.w{display:inline-block;white-space:pre;animation:in .6s cubic-bezier(.2,.8,.2,1) both,glow 1.6s ease-out both}
@keyframes in{from{opacity:0;transform:translateY(10px);filter:blur(7px)}to{opacity:1;transform:none;filter:none}}
@keyframes glow{from{text-shadow:0 0 22px var(--c1)}to{text-shadow:none}}
#bar{display:flex;align-items:center;gap:10px;padding:12px 14px 22px}
.rb{flex:none;border-radius:50%;display:grid;place-items:center;border:1px solid #ffffff14;background:rgba(28,32,56,.72);backdrop-filter:blur(12px);transition:transform .18s,background .3s,box-shadow .3s,opacity .3s}
.rb:hover{box-shadow:0 0 20px color-mix(in srgb,var(--c1) 45%,transparent)}.rb:active{transform:scale(.88)}
.rb.big{width:58px;height:58px}.rb.sm{width:46px;height:46px}
.mutebtn.muted{background:#ff4d6d30;color:#ff8fa3;border-color:#ff4d6d70;animation:pulsered 1.6s ease-in-out infinite}
@keyframes pulsered{50%{box-shadow:0 0 22px #ff4d6d77}}
.mutebtn .ic-off,.mutebtn.muted .ic-mic{display:none}.mutebtn.muted .ic-off{display:block}
#bend{opacity:.45}#bend.on{opacity:1;background:rgba(80,30,50,.8)}
#pill{flex:1;min-width:0;height:62px;border-radius:34px;position:relative;overflow:hidden;color:var(--dim);font-size:13px;border:1px solid color-mix(in srgb,var(--c1) 35%,#ffffff10);
 background:radial-gradient(120% 150% at 50% 140%,color-mix(in srgb,var(--c2) 55%,#0a1a4a),#04060f 70%);
 box-shadow:0 0 calc(10px + var(--lv)*52px) color-mix(in srgb,var(--c1) 50%,transparent),inset 0 -10px 24px color-mix(in srgb,var(--c2) 30%,transparent);transition:border-color .6s}
#pill::after{content:"";position:absolute;inset:0;background:linear-gradient(110deg,transparent 30%,#ffffff20 50%,transparent 70%);transform:translateX(-100%);animation:sweep 3.6s ease-in-out infinite}
@keyframes sweep{60%,100%{transform:translateX(100%)}}
#bars{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;gap:5px;opacity:0;transition:opacity .4s}
#bars i{width:5px;height:6px;border-radius:5px;background:linear-gradient(var(--c1),var(--c2))}
#pl{position:relative;z-index:1;transition:opacity .3s}
body.live #bars{opacity:1}body.live #pl{opacity:0}
#camview{position:fixed;inset:0;z-index:50;background:#000;opacity:0;pointer-events:none;transform:scale(1.05);transition:opacity .45s,transform .45s}
#camview.on{opacity:1;pointer-events:auto;transform:none}
#camv{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
#camglow{position:absolute;inset:0;pointer-events:none;box-shadow:inset 0 0 calc(30px + var(--lv)*100px) color-mix(in srgb,var(--c1) 60%,transparent)}
#camtop{position:absolute;top:0;left:0;right:0;padding:calc(16px + env(safe-area-inset-top)) 16px 40px;background:linear-gradient(#000a,transparent)}
#live{display:inline-flex;gap:8px;align-items:center;padding:7px 14px;border-radius:20px;font-size:12px;background:#0007;backdrop-filter:blur(8px)}
#live::before{content:"";width:8px;height:8px;border-radius:50%;background:#ff4d6d;animation:blink 1s steps(2) infinite}
@keyframes blink{50%{opacity:.2}}
#cambot{position:absolute;left:0;right:0;bottom:0;padding:70px 18px calc(22px + env(safe-area-inset-bottom));background:linear-gradient(transparent,#000d);text-align:center}
#camcap{font-size:clamp(20px,5.4vw,28px);max-height:24vh;margin-bottom:16px;text-shadow:0 2px 12px #000}
#camucap{margin-bottom:6px;color:#cdd3f5}
#camctl{display:flex;justify-content:center;align-items:center;gap:18px}
.cb{width:54px;height:54px;border-radius:50%;display:grid;place-items:center;background:#ffffff1f;backdrop-filter:blur(14px);border:1px solid #ffffff2a;transition:transform .2s,background .3s}
.cb:active{transform:scale(.88)}.cb.on{background:#ffd54a;color:#1a1400}
#coff{width:68px;height:68px;background:linear-gradient(135deg,#ff4d6d,#c2185b);border:0;box-shadow:0 0 26px #ff4d6d77}
#textview{position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;background:linear-gradient(180deg,#02040c,#0b1238 82%,#16206b);transform:translateY(102%);transition:transform .5s cubic-bezier(.2,.8,.2,1)}
#textview.on{transform:none}
#thead{display:flex;align-items:center;padding:calc(14px + env(safe-area-inset-top)) 70px 8px 18px;width:min(680px,100%);margin:0 auto}
#thead b{font-weight:500;font-size:18px}
#chat{flex:1;overflow-y:auto;width:min(680px,100%);margin:0 auto;padding:6px 18px;scrollbar-width:none}
#chat:empty::before{content:attr(data-empty);display:block;text-align:center;color:var(--dim);margin-top:30vh;font-size:15px}
.msg{margin:12px 0;max-width:88%;animation:pop .5s cubic-bezier(.2,.8,.2,1) both}
@keyframes pop{from{opacity:0;transform:translateY(12px) scale(.96)}to{opacity:1;transform:none}}
.you{margin-left:auto;text-align:right}
.you .txt{display:inline-block;padding:10px 15px;border-radius:18px 18px 4px 18px;background:linear-gradient(135deg,#2b3a8f,#4b3ba8);font-size:16px;text-align:left}
.bot .txt{font-size:18px;line-height:1.6;font-weight:300}
.who{font-size:11px;color:var(--dim);margin-bottom:3px}
.cursor .txt::after{content:"";display:inline-block;width:2px;height:1em;background:var(--c1);margin-left:3px;vertical-align:-3px;animation:blink 1s steps(2) infinite}
.dots i{display:inline-block;width:9px;height:9px;margin:6px 4px;border-radius:50%;background:var(--c1);animation:bn 1s ease-in-out infinite}
.dots i:nth-child(2){animation-delay:.15s;background:var(--c2)}.dots i:nth-child(3){animation-delay:.3s}
@keyframes bn{0%,100%{transform:translateY(0);opacity:.4}50%{transform:translateY(-8px);opacity:1}}
#tbar{display:flex;gap:10px;width:min(680px,100%);margin:0 auto;padding:10px 14px calc(18px + env(safe-area-inset-bottom))}
#typed{flex:1;min-width:0;padding:14px 18px;border-radius:28px;border:1px solid #ffffff22;background:#ffffff0f;color:var(--ink);font:inherit;font-size:16px;transition:border-color .3s,box-shadow .3s}
#typed:focus{border-color:var(--c1);box-shadow:0 0 20px color-mix(in srgb,var(--c1) 30%,transparent)}
#tsend{width:52px;height:52px;border-radius:50%;display:grid;place-items:center;background:linear-gradient(135deg,var(--c1),var(--c2));color:#06101a;transition:transform .2s}
#tsend:active{transform:scale(.88)}
#tclose{position:absolute;top:calc(12px + env(safe-area-inset-top));right:14px}
#menu{position:fixed;top:68px;left:12px;z-index:70;width:min(330px,calc(100vw - 24px));padding:16px;border-radius:22px;background:rgba(12,16,38,.93);backdrop-filter:blur(18px);border:1px solid #ffffff1c;opacity:0;transform:translateY(-10px) scale(.96);pointer-events:none;transition:.28s}
#menu.on{opacity:1;transform:none;pointer-events:auto}
#menu h4{font-size:12px;font-weight:400;color:var(--dim);margin:12px 0 6px}#menu h4:first-child{margin-top:0}
.seg{display:flex;gap:6px}.seg button{flex:1;padding:9px;border-radius:12px;background:#ffffff0d;border:1px solid #ffffff14;font-size:14px;transition:.25s}
.seg button.on{background:linear-gradient(135deg,var(--c1),var(--c2));color:#06101a;border-color:transparent}
#mics{width:100%;padding:9px;border-radius:12px;background:#101733;color:var(--ink);border:1px solid #ffffff1a;font:inherit;font-size:13px}
#meter{height:4px;border-radius:4px;background:#ffffff14;overflow:hidden;margin-top:8px}
#meter i{display:block;height:100%;background:linear-gradient(90deg,var(--c1),var(--c2));transform-origin:left;transform:scaleX(0);transition:transform .07s}
#diag{font-size:11px;color:var(--dim);margin-top:6px}
#toast{position:fixed;bottom:112px;left:50%;transform:translate(-50%,20px);z-index:90;padding:11px 18px;border-radius:16px;background:#1b2147ee;border:1px solid #ffffff1c;font-size:14px;max-width:88vw;text-align:center;opacity:0;pointer-events:none;transition:.35s}
#toast.on{opacity:1;transform:translate(-50%,0)}
@media(prefers-reduced-motion:reduce){*{animation:none!important}}
</style>
</head>
<body data-st="idle">
<canvas id="fx"></canvas>

<div id="app">
  <header>
    <button class="ib" id="bmenu" aria-label="Settings"><svg class="i" viewBox="0 0 24 24"><path d="M4 9h16M4 15h10"/></svg></button>
    <div id="chip"><span id="dot"></span><span id="st">offline</span></div>
  </header>
  <section id="stage">
    <div id="ucap"></div>
    <div id="cap" class="status"></div>
  </section>
  <nav id="bar">
    <button class="rb big" id="bcam" aria-label="Open camera"><svg class="i" viewBox="0 0 24 24"><path d="m16 13 5.22 3.48a.5.5 0 0 0 .78-.42V7.94a.5.5 0 0 0-.78-.42L16 11"/><rect x="2" y="6" width="14" height="12" rx="2"/></svg></button>
    <button class="rb sm" id="btext" aria-label="Type a message"><svg class="i" viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><path d="M8 9h8M8 13h5"/></svg></button>
    <button id="pill" aria-label="Start conversation"><span id="pl" data-t="tap"></span><span id="bars"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></span></button>
    <button class="rb sm mutebtn" id="bmute" aria-label="Mute microphone"><svg class="i ic-mic" viewBox="0 0 24 24"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"/></svg><svg class="i ic-off" viewBox="0 0 24 24"><path d="m2 2 20 20"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.9-.77"/><path d="M19 10v2a7 7 0 0 1-.78 3.22M5 10v2a7 7 0 0 0 11.12 5.66M12 19v3"/></svg></button>
    <button class="rb big" id="bend" aria-label="End conversation"><svg class="i" viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
  </nav>
</div>

<div id="camview">
  <video id="camv" muted playsinline autoplay></video><div id="camglow"></div>
  <div id="camtop"><span id="live" data-t="live"></span></div>
  <div id="cambot"><div id="camucap"></div><div id="camcap" class="status"></div>
    <div id="camctl">
      <button class="cb" id="cflash" aria-label="Flashlight"><svg class="i" viewBox="0 0 24 24"><path d="M18 6c0 2-2 2-2 4v10a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4V2h12z"/><path d="M6 6h12M12 12v2"/></svg></button>
      <button class="cb" id="cflip" aria-label="Switch camera"><svg class="i" viewBox="0 0 24 24"><path d="M11 19H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5M13 5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5"/><circle cx="12" cy="12" r="3"/><path d="m18 22-3-3 3-3M6 2l3 3-3 3"/></svg></button>
      <button class="cb" id="coff" aria-label="Turn camera off"><svg class="i" viewBox="0 0 24 24"><path d="M10.66 6H14a2 2 0 0 1 2 2v2.5l5.25-3.5a.5.5 0 0 1 .75.43v9.14M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h1"/><path d="m2 2 20 20"/></svg></button>
      <button class="cb mutebtn" id="cmute" aria-label="Mute microphone"><svg class="i ic-mic" viewBox="0 0 24 24"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"/></svg><svg class="i ic-off" viewBox="0 0 24 24"><path d="m2 2 20 20"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.9-.77"/><path d="M19 10v2a7 7 0 0 1-.78 3.22M5 10v2a7 7 0 0 0 11.12 5.66M12 19v3"/></svg></button>
    </div>
  </div>
</div>

<div id="textview">
  <div id="thead"><b data-t="title"></b></div>
  <button class="ib" id="tclose" aria-label="Close"><svg class="i" viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
  <div id="chat"></div>
  <div id="tbar"><input id="typed" autocomplete="off" data-ph="ph"><button id="tsend" aria-label="Send"><svg class="i" viewBox="0 0 24 24"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/></svg></button></div>
</div>

<div id="menu">
  <h4>Pages</h4><div class="seg"><button onclick="apsToggleSidebar()">☰ All pages</button></div>
  <h4 data-t="lang"></h4><div class="seg" id="langseg"><button data-l="hi">Hindi</button><button data-l="en">English</button></div>
  <h4 data-t="mode" id="modeh"></h4><div class="seg" id="modeseg"><button data-m="stt" data-t="brow"></button><button data-m="native" data-t="nat"></button></div>
  <h4 data-t="mic"></h4><select id="mics"><option>Microphone</option></select><div id="meter"><i id="mi"></i></div><div id="diag"></div>
</div>
<div id="toast"></div>

<script>
const $=id=>document.getElementById(id);
const TXT={idle:'Start a conversation anytime',listening:'Listening…',thinking:'Thinking…',speaking:'Speaking…',muted:'Mic is muted',
 tap:'Tap to start',ph:'Type your question…',live:'LIVE · Gemini can see you',title:'Conversation',empty:'Your conversation will appear here',
 nofl:'This camera has no flashlight. Try the back camera.',nocam:'Could not start the camera. Check permission.',
 nomic:'No sound from your mic. Pick the right one in Settings.',mutedT:'Mic muted',unmutedT:'Mic on',
 lang:'AI speaks',mode:'Voice input',mic:'Microphone',brow:'Browser',nat:'Native',err:'Connecting… send again in a moment'};

if (typeof localforage !== 'undefined') {
    localforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' });
}

let LANG='hi'; 
try{LANG=localStorage.getItem('ailang')||'hi'}catch{}
const T=k=>TXT[k]||'';
const SR=window.SpeechRecognition||window.webkitSpeechRecognition;

let MODE='native'; 

let liveSessionId = Date.now().toString();
let currentInteractions = [];
let interactionCount = 0;

const STATES={idle:{c:['#5ef2d6','#8b7bff','#4285f4']},listening:{c:['#5ef2d6','#4aa8ff','#8b7bff']},thinking:{c:['#ffc46b','#ff7ab8','#8b7bff']},speaking:{c:['#8b7bff','#ff7ab8','#5ef2d6']}};
const rgb=h=>[1,3,5].map(i=>parseInt(h.substr(i,2),16));
const cur=STATES.idle.c.map(rgb);
let state='',ws,micCtx,outCtx,stream,node,analyser,micAn,active=false,starting=false,muted=false,chunks=0,heard=0,rst='-',maxLevel=0;
// Voice gate: decides when the mic carries a real voice (not fan/AC/room noise) and lets you interrupt the AI.
const V={openMs:0,open:false,voiced:0,quiet:0,ring:[],RING:22,buckets:[],floor:.002,bAcc:0,bN:0,bMs:0,echo:0,aiHold:0,aiSince:0,wasAi:false,drop:false,dtm:0,tt:0};
let micLevel=0,nextT=0,sources=[],rec=null,liveUser=null,botEl=null,userEl=null,typing=null,botActive=false,userBuf='';

function toast(m,ms){const e=$('toast');e.textContent=m;e.classList.add('on');clearTimeout(window.tt);window.tt=setTimeout(()=>e.classList.remove('on'),ms||3500)}
function applyLang(){
  document.querySelectorAll('[data-t]').forEach(e=>e.textContent=T(e.dataset.t));
  document.querySelectorAll('[data-ph]').forEach(e=>e.placeholder=T(e.dataset.ph));
  $('chat').dataset.empty=T('empty');
  document.querySelectorAll('#langseg button').forEach(b=>b.classList.toggle('on',b.dataset.l===LANG));
  document.querySelectorAll('#modeseg button').forEach(b=>b.classList.toggle('on',b.dataset.m===MODE));
  $('modeh').style.display=$('modeseg').style.display=SR?'':'none';refreshStatus();
}

async function saveToHistory() {
    if (interactionCount < 2 || typeof localforage === 'undefined') return;
    try {
        let history = await localforage.getItem('aiHistory') || [];
        
        let lsHistory = [];
        try { lsHistory = JSON.parse(localStorage.getItem('aiHistory') || '[]'); } catch(e){}
        if (lsHistory.length > history.length) history = lsHistory;

        let existingIdx = history.findIndex(h => String(h.id) === String(liveSessionId));
        
        let title = "Live Voice Session";
        if (currentInteractions.length > 0 && currentInteractions[0].question) {
            title = "🎙️ " + currentInteractions[0].question.substring(0, 50);
        }
        
        let sessionObj = {
            id: liveSessionId,
            type: 'live',
            title: title,
            interactions: JSON.parse(JSON.stringify(currentInteractions)),
            timestamp: Date.now()
        };
        if (existingIdx >= 0) {
            history[existingIdx] = sessionObj;
        } else {
            history.unshift(sessionObj);
        }
        await localforage.setItem('aiHistory', history);
        try { localStorage.setItem('aiHistory', JSON.stringify(history)); } catch(e) {}
    } catch (e) { console.error("History save error", e); }
}

const caps=()=>[$('cap'),$('camcap')];
function statusText(){if(!active)return T('idle');if(muted&&(state==='listening'||state==='idle'))return T('muted');return T(state)||''}
function capSet(text,cls){caps().forEach(e=>{e.className=cls;e.textContent=text})}
function capAdd(text){
  caps().forEach(e=>{
    if(e.className!=='bot'){e.className='bot';e.textContent=''}
    text.split(/(\s+)/).filter(Boolean).forEach(w=>{
      const s=document.createElement('span');
      s.className='w';
      s.textContent=w;
      e.appendChild(s);
    });
    while(e.childNodes.length > 60) {
        e.removeChild(e.firstChild);
    }
    e.scrollTop=1e9;
  });
}
function refreshStatus(){if(!botActive)capSet(statusText(),'status')}
function ucapSet(t){$('ucap').textContent=t;$('camucap').textContent=t}
function newUserTurn(){botActive=false;refreshStatus()}
function setState(s){
  if(s===state)return;state=s;const r=document.documentElement.style,c=STATES[s].c;
  r.setProperty('--c1',c[0]);r.setProperty('--c2',c[1]);document.body.dataset.st=s;
  if(s==='thinking'&&active)showTyping();else hideTyping();
  refreshStatus();
  if(MODE==='stt'&&active){if(s==='speaking')stopRec();else if(s==='listening')startRec()}
}

const chat=$('chat');
function newLine(cls){const m=document.createElement('div');m.className='msg '+cls;
  m.innerHTML='<div class="who">'+(cls==='you'?'You':'Gemini')+'</div><div class="txt"></div>';chat.appendChild(m);chat.scrollTop=1e9;return m}
function addWords(m,text){
  m.classList.remove('cursor');
  const box=m.lastChild;
  text.split(/(\s+)/).filter(Boolean).forEach(w=>{
    const s=document.createElement('span');
    s.className='w';
    s.textContent=w;
    box.appendChild(s);
  });
  m.classList.add('cursor');
  chat.scrollTop=1e9;
}
function showTyping(){if(typing||botEl)return;typing=newLine('bot');typing.lastChild.innerHTML='<span class="dots"><i></i><i></i><i></i></span>'}
function hideTyping(){if(typing){typing.remove();typing=null}}

function endTurn(){
  if(botEl){
    botEl.classList.remove('cursor');
    if(botEl.lastChild) botEl.lastChild.innerHTML = botEl.lastChild.textContent; 
  }
  botEl=null;
  if(interactionCount >= 2) saveToHistory();
}
function closeUserEl(){
  if(userEl){
    userEl.classList.remove('cursor');
    if(userEl.lastChild) userEl.lastChild.innerHTML = userEl.lastChild.textContent;
    userEl=null;
  }
}

function addUser(text){
  hideTyping();
  endTurn();
  closeUserEl();
  const m=newLine('you');
  m.lastChild.textContent=text;
  userBuf='';
  ucapSet(text);
  
  currentInteractions.push({ question: text, answer: '', timestamp: Date.now() });
  interactionCount++;
  
  newUserTurn();
}
function onUserText(t){
  hideTyping();
  endTurn();
  if(!userEl) {
    userEl=newLine('you');
    currentInteractions.push({ question: '', answer: '', timestamp: Date.now() });
    interactionCount++;
  }
  addWords(userEl,t);
  userBuf+=t;
  ucapSet(userBuf);
  
  if(currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].question += t;
  
  newUserTurn();
}
function onBotText(t){
  hideTyping();
  closeUserEl();
  userBuf='';
  if(state==='listening'||state==='idle')setState('thinking');
  hideTyping();
  if(!botEl){botEl=newLine('bot');capSet('','bot')}
  addWords(botEl,t);
  botActive=true;
  capAdd(t);
  
  if(currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].answer += t;
}
function sendText(text){if(ws&&ws.readyState===1){sendFrame();ws.send(JSON.stringify({t:'text',text}));setState('thinking')}}

function startRec(){
  if(MODE!=='stt'||!SR||!active||rec||muted)return;
  const r=new SR();rec=r;r.lang=LANG==='hi'?'hi-IN':'en-IN';r.continuous=true;r.interimResults=true;
  r.onresult=e=>{
    let interim='',fin='';
    for(let i=e.resultIndex;i<e.results.length;i++){const x=e.results[i];if(x.isFinal)fin+=x[0].transcript;else interim+=x[0].transcript}
    const txt=(fin||interim).trim();if(!txt)return;rst='heard you';
    if(state!=='speaking')setState('listening');
    hideTyping();endTurn();
    if(!liveUser) {
        liveUser=newLine('you');
        currentInteractions.push({ question: '', answer: '', timestamp: Date.now() });
        interactionCount++;
    }
    liveUser.lastChild.textContent=txt;
    chat.scrollTop=1e9;ucapSet(txt);newUserTurn();
    
    if (currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].question = txt;

    if(fin.trim()){liveUser=null;heard++;sendText(fin.trim())}
  };
  r.onstart=()=>{rst='recognizer on'};r.onsoundstart=()=>{rst='sound detected'};r.onspeechstart=()=>{rst='speech detected'};
  r.onerror=e=>{rst='error: '+e.error;
    if(['not-allowed','service-not-allowed','audio-capture','network'].includes(e.error))toast('Speech: '+e.error+' · you can type instead')};
  r.onend=()=>{if(rec===r)rec=null;if(active&&MODE==='stt'&&state!=='speaking'&&!muted)setTimeout(startRec,150)};
  try{r.start()}catch{rec=null}
}
function stopRec(){if(rec){const r=rec;rec=null;r.onend=null;try{r.abort()}catch{}}}

function playPcm(buf){
  if(!outCtx)return;
  const i16=new Int16Array(buf),f=new Float32Array(i16.length);
  for(let i=0;i<i16.length;i++)f[i]=i16[i]/32768;
  const ab=outCtx.createBuffer(1,f.length,24000);ab.copyToChannel(f,0);
  const src=outCtx.createBufferSource();src.buffer=ab;src.connect(analyser);
  nextT=Math.max(nextT,outCtx.currentTime+.04);src.start(nextT);nextT+=ab.duration;
  sources.push(src);src.onended=()=>{sources=sources.filter(s=>s!==src)};
  chunks++;setState('speaking');
}
function stopPlayback(){sources.forEach(s=>{try{s.stop()}catch{}});sources=[];nextT=0}

let micId='';try{micId=localStorage.getItem('micId')||''}catch{}
const AUDIO_FX={echoCancellation:true,noiseSuppression:true,autoGainControl:true,channelCount:1};
async function openMic(){
  try{return await navigator.mediaDevices.getUserMedia({audio:micId?{...AUDIO_FX,deviceId:{exact:micId}}:AUDIO_FX})}
  catch(e){if(micId){micId='';return await navigator.mediaDevices.getUserMedia({audio:AUDIO_FX})}throw e}
}
async function fillMics(){
  try{const list=(await navigator.mediaDevices.enumerateDevices()).filter(d=>d.kind==='audioinput'),sel=$('mics');sel.innerHTML='';
    list.forEach((d,i)=>{const o=document.createElement('option');o.value=d.deviceId;o.textContent=d.label||('Microphone '+(i+1));sel.appendChild(o)});
    const c=stream&&stream.getAudioTracks()[0]&&stream.getAudioTracks()[0].getSettings().deviceId;if(c)sel.value=c}catch{}
}
$('mics').onchange=e=>{micId=e.target.value;try{localStorage.setItem('micId',micId)}catch{}restart()};

// Returns 'open' when a real voice starts, 'close' when it has ended, '' otherwise. Works on the 300-3400 Hz voice band only.
function vadStep(band,dt){
  const now=performance.now();
  if(state==='speaking')V.aiHold=now+500;           // AI audio (and its echo tail) is playing
  const ai=now<V.aiHold;
  if(ai&&!V.wasAi)V.aiSince=now;V.wasAi=ai;
  // Noise floor = quietest 100 ms slice of the last 3 s, so fans / AC / traffic are learned and ignored.
  V.openMs=V.open?V.openMs+dt:0;
  if(!ai&&(!V.open||V.openMs>2000)){V.bAcc+=band;V.bN++;V.bMs+=dt;  // while a voice is active the floor is frozen, but not forever (a fan that just got louder must not hold the gate open)
    if(V.bMs>=100){V.buckets.push(V.bAcc/V.bN);if(V.buckets.length>30)V.buckets.shift();V.bAcc=V.bN=V.bMs=0;V.floor=Math.min(...V.buckets)}}
  const learning=ai&&now-V.aiSince<700;              // first 0.7 s of AI speech: just measure the speaker echo
  const thr=ai?Math.max(.02,V.floor*5,V.echo*2.2):Math.max(.007,V.floor*3.5);
  const hot=!learning&&band>thr;
  if(ai){ // echo envelope: learns fast at the start, afterwards it can only creep up slowly so YOUR voice is never learned as echo
    const dec=V.echo*Math.exp(-dt/1500);
    if(learning)V.echo=Math.max(band,dec);
    else if(!V.open&&!hot)V.echo=Math.max(dec,Math.min(band,V.echo*(1+dt/1000)+1e-4));
  }else V.echo*=Math.exp(-dt/300);
  if(hot){V.voiced+=dt;V.quiet=0}else{V.voiced=Math.max(0,V.voiced-dt*2);V.quiet+=dt}  // a clap or door slam never lasts long enough
  if(!V.open)return V.voiced>=(ai?260:100)?'open':'';
  return V.quiet>=700?'close':'';
}
async function start(){if(active||starting)return;try{await startInner()}catch(e){console.error(e);toast('Start failed: '+(e&&e.message||e),10000);stop()}}
async function startInner(){
  starting=true;
  $('st').textContent = 'Connecting...';$('pl').textContent = 'Connecting...';
  if(!navigator.mediaDevices||!window.AudioWorklet){starting=false;toast('The microphone only works on http://localhost or https. Open the page that way.',10000);return}
  try{stream=await openMic()}catch(e){starting=false;toast('Microphone error: '+(e.name||e.message)+'. Allow the microphone and try again.',10000);return}
  stream.getAudioTracks().forEach(t=>t.enabled=!muted);
  micCtx=new AudioContext();outCtx=new AudioContext();await micCtx.resume();await outCtx.resume();
  analyser=outCtx.createAnalyser();analyser.fftSize=256;analyser.connect(outCtx.destination);
  const code=`class P extends AudioWorkletProcessor{constructor(){super();this.r=sampleRate/16000;this.p=0;this.a=0;this.n=0;this.o=[];
    const w=2*Math.PI;this.ha=1-Math.exp(-w*300/sampleRate);this.la=1-Math.exp(-w*3400/sampleRate);this.x1=0;this.x2=0;this.y1=0;this.y2=0}
    process(i){const c=i[0][0];if(!c)return true;let s=0,b=0;
      for(let k=0;k<c.length;k++){const v=c[k];s+=v*v;
        this.x1+=this.ha*(v-this.x1);const h1=v-this.x1;this.x2+=this.ha*(h1-this.x2);const h2=h1-this.x2;
        this.y1+=this.la*(h2-this.y1);this.y2+=this.la*(this.y1-this.y2);b+=this.y2*this.y2;
        this.a+=v;this.n++;this.p+=1;
        if(this.p>=this.r){this.p-=this.r;this.o.push(Math.max(-1,Math.min(1,this.a/this.n))*32767);this.a=0;this.n=0}}
      const rms=Math.sqrt(s/c.length),band=Math.sqrt(b/c.length),dt=c.length/sampleRate*1000;
      if(this.o.length>=320){const x=Int16Array.from(this.o);this.o=[];this.port.postMessage({pcm:x.buffer,rms,band,dt},[x.buffer])}
      else this.port.postMessage({rms,band,dt});return true}}registerProcessor('p',P)`;
  await micCtx.audioWorklet.addModule(URL.createObjectURL(new Blob([code],{type:'application/javascript'})));
  node=new AudioWorkletNode(micCtx,'p');const msrc=micCtx.createMediaStreamSource(stream);msrc.connect(node);
  const mute=micCtx.createGain();mute.gain.value=0;node.connect(mute);mute.connect(micCtx.destination);
  micAn=micCtx.createAnalyser();micAn.fftSize=128;msrc.connect(micAn);
  maxLevel=0;fillMics();clearTimeout(window.silent);
  window.silent=setTimeout(()=>{if(active&&!muted&&maxLevel<.004)toast(T('nomic'))},6000);
  ws=new WebSocket(`${location.protocol==='https:'?'wss':'ws'}://${location.host}/live-ws?lang=${LANG}`);ws.binaryType='arraybuffer';
  node.port.onmessage=e=>{
    const d=e.data;micLevel=muted?0:d.rms;maxLevel=Math.max(maxLevel,micLevel);
    if(muted){V.open=false;V.voiced=0;return}
    const ev=vadStep(d.band||0,d.dt||3);
    if(ev==='open'){
      V.open=true;V.quiet=0;
      if(state==='speaking'){ // you started talking over the AI: stop it and ignore its leftover audio
        V.drop=true;clearTimeout(V.dtm);V.dtm=setTimeout(()=>{V.drop=false},6000);stopPlayback();endTurn();
      }
      if(state!=='listening'){setState('listening');newUserTurn()}
      if(MODE==='native'&&ws&&ws.readyState===1)V.ring.forEach(b=>ws.send(b)); // send the first syllables that came before detection
      V.ring=[];
    }else if(ev==='close'){
      V.open=false;V.voiced=0;
      if(state!=='speaking')setState('thinking');
      if(MODE==='native'&&ws&&ws.readyState===1)ws.send(JSON.stringify({t:'end'}));
      clearTimeout(V.tt);V.tt=setTimeout(()=>{if(active&&state==='thinking'&&!botEl&&!sources.length)setState('listening')},7000); // false alarm: go back to listening
    }
    if(MODE==='native'&&d.pcm&&ws&&ws.readyState===1){
      if(V.open)ws.send(d.pcm); // real voice
      else{V.ring.push(d.pcm);if(V.ring.length>V.RING)V.ring.shift();ws.send(new ArrayBuffer(d.pcm.byteLength))} // silence instead of fan noise
    }
  };
  ws.onmessage=e=>{
    if(typeof e.data!=='string'){if(!V.drop)playPcm(e.data);return}
    const d=JSON.parse(e.data);
    if(d.t==='ready'){active=true;starting=false;document.body.classList.add('live');$('bend').classList.add('on');$('st').textContent=d.model;
      $('pl').textContent=T('tap');
      state='';setState('thinking');chunks=0;heard=0;if(MODE==='stt')startRec();
      clearInterval(window.dbg);window.dbg=setInterval(()=>{$('diag').textContent=(MODE==='stt'?'phrases '+heard+' · '+rst:'native')+' · '+(V.open?'voice':'quiet')+' · audio '+chunks},600)}
    else if(d.t==='user')onUserText(d.text);
    else if(d.t==='bot')onBotText(d.text);
    else if(d.t==='interrupted'){stopPlayback();endTurn();V.drop=false;clearTimeout(V.dtm);setState('listening')}
    else if(d.t==='done'){endTurn();V.drop=false}
    else if(d.t==='error'){toast(d.text,12000);stop()}
  };
  ws.onerror=()=>toast('Cannot reach the voice socket (/live-ws) on this server.',10000);
  ws.onclose=()=>{if(active||starting)stop()};
}
function stop(){
  active=false;starting=false;stopRec();closeCam();clearTimeout(window.silent);clearInterval(window.dbg);liveUser=null;micAn=null;
  try{ws.close()}catch{}stream&&stream.getTracks().forEach(t=>t.stop());
  micCtx&&micCtx.close();outCtx&&outCtx.close();stopPlayback();hideTyping();endTurn();
  document.body.classList.remove('live');$('bend').classList.remove('on');$('st').textContent='offline';$('pl').textContent=T('tap');
  botActive=false;ucapSet('');state='';setState('idle');
  Object.assign(V,{open:false,voiced:0,quiet:0,ring:[],buckets:[],floor:.002,bAcc:0,bN:0,bMs:0,echo:0,aiHold:0,wasAi:false,drop:false});clearTimeout(V.dtm);clearTimeout(V.tt);
}
function restart(){if(active){stop();setTimeout(start,400)}}

function toggleMute(){
  muted=!muted;if(stream)stream.getAudioTracks().forEach(t=>t.enabled=!muted);
  document.querySelectorAll('.mutebtn').forEach(b=>b.classList.toggle('muted',muted));
  if(muted){stopRec();V.open=false;V.voiced=0}else if(active&&MODE==='stt'&&state!=='speaking')startRec();
  refreshStatus();toast(T(muted?'mutedT':'unmutedT'));
}

let camStream=null,camTimer=null,facing='user',torchOn=false;const cc=document.createElement('canvas');
async function startCamStream(){
  if(camStream)camStream.getTracks().forEach(t=>t.stop());
  try{camStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:facing},width:{ideal:1280},height:{ideal:720}},audio:false})}
  catch(e){camStream=null;toast(T('nocam'));return false}
  const v=$('camv');v.srcObject=camStream;v.style.transform=facing==='user'?'scaleX(-1)':'none';try{await v.play()}catch{}
  torchOn=false;$('cflash').classList.remove('on');clearInterval(camTimer);camTimer=setInterval(sendFrame,1000);return true;
}
async function openCam(){
  if(!active)start();
  if(await startCamStream())document.body.classList.add('camopen'),$('camview').classList.add('on');
}
function closeCam(){
  clearInterval(camTimer);if(camStream)camStream.getTracks().forEach(t=>t.stop());camStream=null;
  $('camview').classList.remove('on');document.body.classList.remove('camopen');
}
async function toggleTorch(){
  const tr=camStream&&camStream.getVideoTracks()[0];if(!tr)return;
  const caps=tr.getCapabilities?tr.getCapabilities():{};if(!caps.torch){toast(T('nofl'));return}
  try{await tr.applyConstraints({advanced:[{torch:!torchOn}]});torchOn=!torchOn;$('cflash').classList.toggle('on',torchOn)}catch{toast(T('nofl'))}
}
function sendFrame(){
  const v=$('camv');if(!camStream||!v.videoWidth||!ws||ws.readyState!==1)return;
  const w=Math.min(640,v.videoWidth),h=Math.round(w*v.videoHeight/v.videoWidth);cc.width=w;cc.height=h;
  cc.getContext('2d').drawImage(v,0,0,w,h);ws.send(JSON.stringify({t:'video',data:cc.toDataURL('image/jpeg',.6).split(',')[1]}));
}

$('pill').onclick=()=>{if(!active)start();else if(state==='speaking'){stopPlayback();setState('listening')}};$('bend').onclick=()=>{if(active)stop()};
$('bmute').onclick=$('cmute').onclick=toggleMute;
$('bcam').onclick=openCam;$('coff').onclick=closeCam;$('cflip').onclick=async()=>{facing=facing==='user'?'environment':'user';await startCamStream()};$('cflash').onclick=toggleTorch;
$('btext').onclick=()=>{$('textview').classList.add('on');if(!active&&!$('textview').dataset.restored)start();setTimeout(()=>$('typed').focus(),450)};
$('tclose').onclick=()=>$('textview').classList.remove('on');
function submitText(){const v=$('typed').value.trim();if(!v)return;if(!active){toast(T('err'));start();return}$('typed').value='';addUser(v);sendText(v)}
$('tsend').onclick=submitText;$('typed').addEventListener('keydown',e=>{if(e.key==='Enter')submitText()});
$('bmenu').onclick=e=>{e.stopPropagation();$('menu').classList.toggle('on')};
document.addEventListener('click',e=>{if(!$('menu').contains(e.target))$('menu').classList.remove('on')});
document.querySelectorAll('#langseg button').forEach(b=>b.onclick=()=>{LANG=b.dataset.l;try{localStorage.setItem('ailang',LANG)}catch{}applyLang();restart()});
document.querySelectorAll('#modeseg button').forEach(b=>b.onclick=()=>{MODE=b.dataset.m;applyLang();restart()});
applyLang();

const fx=$('fx'),f=fx.getContext('2d'),BARS=[...document.querySelectorAll('#bars i')];
let FW,FH,t=0,smooth=0,ripples=[],lastState='';
const buf=new Uint8Array(128),micBuf=new Uint8Array(64),DPR=()=>devicePixelRatio||1,avg=a=>a.reduce((x,y)=>x+y,0)/a.length;
function fit(){const d=DPR();FW=fx.width=innerWidth*d;FH=fx.height=innerHeight*d}addEventListener('resize',fit);fit();
const PT=Array.from({length:70},()=>({x:Math.random(),y:Math.random(),s:.2+Math.random(),z:Math.random()}));
const rgba=(c,a)=>`rgba(${c.map(Math.round)},${a})`;
function frame(){
  t+=.012;const d=DPR();
  if(state==='speaking'&&outCtx&&!sources.length&&outCtx.currentTime>nextT+.3)setState('listening');
  if(state!==lastState){ripples.push({r:0,a:.8});lastState=state}
  let spec=null,lvl=0;
  if(state==='speaking'&&analyser){analyser.getByteFrequencyData(buf);spec=buf;lvl=avg(buf)/80}
  else if(state==='thinking')lvl=.3+.15*Math.sin(t*8);
  else if(micAn&&active&&!muted){micAn.getByteFrequencyData(micBuf);spec=micBuf;lvl=Math.min(1,Math.max(micLevel*10,avg(micBuf)/70))}
  if(!active)lvl=.06+.03*Math.sin(t*2);
  lvl=Math.min(1,lvl);smooth+=(lvl-smooth)*.18;
  if(smooth>.3&&Math.random()<.04+smooth*.06)ripples.push({r:0,a:.5*smooth});
  const S=STATES[state||'idle'];
  for(let j=0;j<3;j++){const tg=rgb(S.c[j]);for(let i=0;i<3;i++)cur[j][i]+=(tg[i]-cur[j][i])*.05}
  document.body.style.setProperty('--lv',smooth.toFixed(3));
  BARS.forEach((b,i)=>{const k=Math.abs(i-4),v=spec?Math.min(1,spec[2+k*4]/190):.5+.5*Math.sin(t*3+i);b.style.height=(6+v*(active?40:5))+'px'});
  $('mi').style.transform='scaleX('+Math.min(1,micLevel*12)+')';
  f.clearRect(0,0,FW,FH);f.globalCompositeOperation='lighter';
  for(let j=0;j<3;j++){
    const x=FW*(.15+.35*j+.08*Math.sin(t*.8+j*2)),y=FH*(1.02+.02*Math.sin(t+j)),r=FW*.75*(1+smooth*.35);
    const g=f.createRadialGradient(x,y,0,x,y,Math.max(r,FH*.45));g.addColorStop(0,rgba(cur[j],.26+smooth*.28));g.addColorStop(1,rgba(cur[j],0));
    f.fillStyle=g;f.fillRect(0,0,FW,FH);
  }
  PT.forEach((p,i)=>{p.y-=p.s*.0004*(1+smooth*4);if(p.y<0){p.y=1;p.x=Math.random()}
    f.fillStyle=rgba(cur[i%3],.1+.45*p.z*(.3+smooth));f.beginPath();f.arc(p.x*FW+Math.sin(t+i)*12*d,p.y*FH,(1+p.z*2.2)*d,0,7);f.fill()});
  if(!document.body.classList.contains('camopen')){
    const rc=$('pill').getBoundingClientRect(),ox=(rc.left+rc.width/2)*d,oy=(rc.top+rc.height/2)*d;
    ripples.forEach(q=>{q.r+=.011;f.beginPath();f.arc(ox,oy,(40+q.r*260)*d,0,7);f.lineWidth=2*d;f.strokeStyle=rgba(cur[0],q.a*(1-q.r));f.stroke()});
  }
  ripples=ripples.filter(q=>q.r<1);
  requestAnimationFrame(frame);
}
frame();

document.addEventListener("DOMContentLoaded", () => {
    const urlParams = new URLSearchParams(window.location.search);
    const restoreId = urlParams.get('restore');
    if (restoreId) {
        $('textview').classList.add('on');$('textview').dataset.restored = "true";
        
        if (typeof localforage !== 'undefined') {
            localforage.getItem('aiHistory').then(history => {
                if (history) {
                    const session = history.find(h => String(h.id) === String(restoreId));
                    if (session && session.interactions) {
                        liveSessionId = session.id;
                        currentInteractions = session.interactions;
                        interactionCount = currentInteractions.length;
                        
                        session.interactions.forEach(inter => {
                            if (inter.question) {
                                const u = newLine('you');
                                u.classList.remove('cursor');
                                u.lastChild.textContent = inter.question;
                            }
                            if (inter.answer) {
                                const b = newLine('bot');
                                b.classList.remove('cursor');
                                b.lastChild.textContent = inter.answer;
                            }
                        });
                        chat.scrollTop = 1e9;
                    }
                }
            }).catch(e => console.error("Restore Error:", e));
        }
    }
});
</script>
<script src="nav-sidebar.js" data-pos="none"></script>
</body>
</html>