File size: 50,391 Bytes
af5d2e2
 
 
 
f8d45d4
 
af5d2e2
 
 
 
 
 
c546535
 
af5d2e2
 
 
 
 
 
 
c546535
af5d2e2
 
 
 
 
 
 
 
 
 
c546535
af5d2e2
 
 
c546535
 
 
 
 
af5d2e2
 
 
 
 
 
c546535
 
af5d2e2
 
 
c546535
af5d2e2
c546535
 
 
f8d45d4
af5d2e2
 
c546535
 
af5d2e2
 
 
 
c546535
 
 
af5d2e2
 
c546535
af5d2e2
c546535
 
 
 
 
 
af5d2e2
 
c546535
 
af5d2e2
 
 
c546535
af5d2e2
c546535
af5d2e2
c546535
af5d2e2
 
 
c546535
 
 
 
 
af5d2e2
c546535
af5d2e2
 
c546535
af5d2e2
 
 
 
c546535
 
 
 
af5d2e2
c546535
 
 
 
 
 
 
 
af5d2e2
 
 
c546535
af5d2e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c546535
 
 
 
 
af5d2e2
 
c546535
 
 
 
 
 
 
 
 
 
af5d2e2
c546535
 
 
 
 
 
af5d2e2
c546535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c62efad
af5d2e2
c546535
af5d2e2
c546535
af5d2e2
 
 
c546535
 
af5d2e2
 
 
 
 
 
c546535
af5d2e2
 
c546535
 
af5d2e2
c546535
 
af5d2e2
 
c546535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af5d2e2
 
 
 
 
f8d45d4
af5d2e2
 
 
 
 
c546535
 
 
af5d2e2
c546535
 
 
 
af5d2e2
 
 
c546535
 
 
 
 
 
af5d2e2
 
 
 
 
c546535
 
 
af5d2e2
 
 
 
c546535
 
 
 
 
 
 
af5d2e2
 
 
 
c546535
 
 
af5d2e2
c546535
 
 
 
 
 
 
 
 
af5d2e2
 
 
 
 
 
 
 
 
 
 
c546535
 
 
af5d2e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c546535
 
 
 
 
 
 
 
 
 
af5d2e2
 
 
 
 
c546535
 
 
af5d2e2
c546535
af5d2e2
 
 
 
f8d45d4
af5d2e2
c546535
 
 
 
af5d2e2
 
 
 
 
 
 
 
c546535
 
af5d2e2
 
 
 
c546535
 
af5d2e2
 
 
 
 
 
 
c546535
af5d2e2
c546535
 
af5d2e2
c546535
af5d2e2
c546535
af5d2e2
 
c546535
af5d2e2
c546535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af5d2e2
c546535
 
 
 
 
 
 
 
 
 
 
 
 
c62efad
c546535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af5d2e2
 
 
 
c546535
 
af5d2e2
 
c546535
 
 
 
af5d2e2
 
 
 
c546535
 
af5d2e2
c546535
 
 
af5d2e2
c546535
 
af5d2e2
c546535
 
 
 
 
 
af5d2e2
 
c546535
af5d2e2
c546535
 
 
af5d2e2
c546535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af5d2e2
c546535
 
 
 
 
 
 
af5d2e2
c546535
af5d2e2
c546535
af5d2e2
 
 
 
c546535
 
 
af5d2e2
 
 
 
c546535
 
 
 
 
 
f8d45d4
c546535
 
 
 
f8d45d4
 
 
c546535
 
 
f8d45d4
 
 
 
c546535
 
af5d2e2
 
c546535
af5d2e2
f8d45d4
af5d2e2
 
 
c546535
 
af5d2e2
 
c546535
af5d2e2
c546535
af5d2e2
c546535
af5d2e2
f8d45d4
af5d2e2
c546535
af5d2e2
c546535
af5d2e2
f8d45d4
af5d2e2
f8d45d4
c546535
 
f8d45d4
af5d2e2
f8d45d4
af5d2e2
c546535
af5d2e2
 
 
 
c546535
af5d2e2
c546535
 
 
 
af5d2e2
c546535
af5d2e2
 
c546535
 
 
af5d2e2
 
c546535
 
 
 
 
af5d2e2
c546535
 
 
 
 
 
 
 
 
 
 
 
af5d2e2
 
c546535
 
 
 
af5d2e2
 
c546535
 
 
 
af5d2e2
c546535
 
 
 
 
f8d45d4
af5d2e2
c546535
af5d2e2
c546535
 
 
 
 
 
af5d2e2
 
c546535
 
 
 
 
 
af5d2e2
c546535
 
 
 
 
af5d2e2
 
 
c546535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c62efad
c546535
 
c62efad
 
c546535
 
af5d2e2
 
 
c546535
 
af5d2e2
c546535
 
 
 
 
 
af5d2e2
c546535
 
 
 
 
 
 
f8d45d4
c546535
af5d2e2
 
c546535
f8d45d4
c546535
 
 
 
af5d2e2
 
 
c546535
 
 
 
 
 
 
 
 
af5d2e2
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>Genisi AI ยท Hidden Sidebar</title>
  <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/dompurify@3.1.6/dist/purify.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css"/>
  <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js"></script>
  <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js"></script>
  <!-- Lucide Icons -->
  <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
  <style>
    :root {
      --bg: #0d0f14; --surface: #161920; --surface2: #1e2230; --surface3: #252a3a;
      --border: #2a2f42; --border2: #333a52;
      --accent: #4f8ef7; --accent2: #7c5cf7; --accent-soft: rgba(79,142,247,0.12);
      --text: #e8eaf2; --text2: #9aa3be; --text3: #5c6480;
      --user-bubble: #1a2340; --bot-bubble: #161920;
      --danger: #f75f5f;
      --radius: 28px; --radius-sm: 18px; --radius-pill: 50px;
      --sidebar-w: 280px; --tr: 0.3s cubic-bezier(.4,0,.2,1);
    }
    [data-theme="light"] {
      --bg: #f0f2f8; --surface: #fff; --surface2: #f5f6fa; --surface3: #ebedf5;
      --border: #d8dce8; --border2: #c5cad8;
      --text: #1a1d2e; --text2: #4a5070; --text3: #8a90a8;
      --user-bubble: #dde6ff; --bot-bubble: #fff; --accent-soft: rgba(79,142,247,0.1);
    }
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    html,body{height:100%;font-family:'Cairo',sans-serif;background:var(--bg);color:var(--text);scroll-behavior:smooth;}
    ::-webkit-scrollbar{width:6px}::-webkit-scrollbar-track{background:transparent}
    ::-webkit-scrollbar-thumb{background:var(--border2);border-radius:var(--radius-pill)}

    /* Lucide icon base style */
    .icon { width:20px; height:20px; stroke:currentColor; fill:none; stroke-width:2; stroke-linecap:round; stroke-linejoin:round; pointer-events:none; flex-shrink:0; }
    .icon-sm { width:16px; height:16px; }
    .icon-lg { width:22px; height:22px; }

    .app{display:flex;height:100vh;overflow:hidden}

    /* SIDEBAR */
    .sidebar{width:var(--sidebar-w);min-width:var(--sidebar-w);background:var(--surface);
      border-right:1px solid var(--border);display:flex;flex-direction:column;
      transition:width var(--tr),min-width var(--tr);overflow:hidden;
      border-top-right-radius:var(--radius);border-bottom-right-radius:var(--radius);}
    [dir="rtl"] .sidebar{border-right:none;border-left:1px solid var(--border);border-radius:0 var(--radius) var(--radius) 0;}
    .sidebar.collapsed{width:0;min-width:0;border:none}
    .sidebar-header{padding:24px 20px 16px;display:flex;align-items:center;gap:12px;}
    .s-logo{display:flex;align-items:center;gap:12px;flex:1}
    .s-logo img{width:36px;height:36px;border-radius:12px;object-fit:cover;box-shadow:0 4px 12px var(--accent-soft);}
    .s-logo-name{font-size:1.2rem;font-weight:700;background:linear-gradient(135deg,var(--accent),var(--accent2));-webkit-background-clip:text;-webkit-text-fill-color:transparent}

    .close-sidebar-btn{background:none;border:none;color:var(--text2);cursor:pointer;padding:8px;border-radius:var(--radius-pill);transition:all 0.2s;display:flex;align-items:center;justify-content:center;width:36px;height:36px;}
    .close-sidebar-btn:hover{background:var(--surface2);color:var(--danger);transform:scale(1.1);}

    .btn-new{margin:12px 16px;padding:12px 16px;background:linear-gradient(135deg,var(--accent),var(--accent2));
      color:#fff;border:none;border-radius:var(--radius-pill);cursor:pointer;font-family:'Cairo',sans-serif;
      font-size:.95rem;font-weight:600;display:flex;align-items:center;gap:8px;justify-content:center;
      transition:all var(--tr);box-shadow:0 4px 15px var(--accent-soft);}
    .btn-new:hover{opacity:.9;transform:translateY(-2px)}
    .s-label{padding:10px 20px;font-size:.75rem;font-weight:700;color:var(--text3);letter-spacing:.08em;text-transform:uppercase}
    .chats-list{flex:1;overflow-y:auto;padding:4px 12px;display:flex;flex-direction:column;gap:6px}
    .chat-item{padding:10px 16px;border-radius:var(--radius-sm);cursor:pointer;font-size:.9rem;color:var(--text2);
      display:flex;align-items:center;gap:10px;transition:all var(--tr);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .chat-item:hover{background:var(--surface2);color:var(--text);transform:translateX(4px);}
    [dir="rtl"] .chat-item:hover{transform:translateX(-4px);}
    .chat-item.active{background:var(--accent-soft);color:var(--accent);font-weight:600;}
    .chat-item .ct{flex:1;overflow:hidden;text-overflow:ellipsis}
    .del-btn{opacity:0;background:none;border:none;color:var(--danger);cursor:pointer;padding:4px;border-radius:50%;transition:all var(--tr);display:flex;align-items:center;justify-content:center;}
    .chat-item:hover .del-btn{opacity:1}
    .del-btn:hover{background:rgba(247,95,95,.15);transform:scale(1.1);}
    .s-footer{padding:16px;display:flex;align-items:center;gap:12px;justify-content:center;}
    .btn-icon{width:42px;height:42px;background:var(--surface2);border:none;border-radius:var(--radius-pill);
      color:var(--text2);cursor:pointer;display:flex;align-items:center;justify-content:center;
      transition:all var(--tr)}
    .btn-icon:hover{background:var(--surface3);color:var(--text);transform:rotate(10deg);}

    /* MAIN */
    .main{flex:1;display:flex;flex-direction:column;overflow:hidden;min-width:0;background:var(--bg);}
    .topbar{height:70px;padding:0 24px;display:flex;align-items:center;gap:16px;flex-shrink:0}
    .topbar-title{flex:1;font-size:1.05rem;font-weight:600;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}

    /* CHAT AREA */
    .chat-area{flex:1;overflow-y:auto;padding:20px 0 40px;display:flex;flex-direction:column;scroll-behavior:smooth;}
    .welcome{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;
      gap:20px;padding:40px 24px;text-align:center;animation:fadeSlideUp 0.6s ease;}
    .w-logo{width:85px;height:85px;border-radius:24px;object-fit:cover;box-shadow:0 12px 40px var(--accent-soft)}
    .w-title{font-size:2.4rem;font-weight:700;background:linear-gradient(135deg,var(--accent),var(--accent2));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
    .w-sub{color:var(--text2);font-size:1.05rem}
    .chips{display:flex;flex-wrap:wrap;justify-content:center;gap:10px;margin-top:12px;max-width:600px}
    .chip{padding:10px 20px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-pill);
      font-size:.9rem;color:var(--text);cursor:pointer;transition:all var(--tr);box-shadow:0 4px 12px rgba(0,0,0,0.05);}
    .chip:hover{background:var(--accent-soft);border-color:var(--accent);color:var(--accent);transform:translateY(-2px);}

    @keyframes popIn{from{opacity:0;transform:translateY(15px) scale(0.98);filter:blur(4px);}to{opacity:1;transform:translateY(0) scale(1);filter:blur(0);}}
    @keyframes fadeSlideUp{from{opacity:0;transform:translateY(20px);}to{opacity:1;transform:translateY(0);}}

    .msg-row{display:flex;padding:8px 30px;gap:16px;animation:popIn 0.4s cubic-bezier(0.16,1,0.3,1) forwards;}
    .msg-row.user{flex-direction:row-reverse}
    .msg-av{width:38px;height:38px;border-radius:14px;flex-shrink:0;display:flex;align-items:center;
      justify-content:center;font-size:1.1rem;font-weight:700;margin-top:2px;overflow:hidden;box-shadow:0 4px 10px rgba(0,0,0,0.1);}
    .msg-row.bot .msg-av{background:linear-gradient(135deg,var(--accent),var(--accent2))}
    .msg-row.bot .msg-av img{width:100%;height:100%;object-fit:cover}
    .msg-row.user .msg-av{background:var(--surface3);color:var(--text)}

    .bubble{max-width:min(700px,80vw);padding:16px 22px;border-radius:var(--radius);font-size:.98rem;line-height:1.75;word-break:break-word;box-shadow:0 4px 15px rgba(0,0,0,0.03);}
    .msg-row.bot .bubble{background:transparent;border:none;padding:8px 4px;box-shadow:none;border-top-left-radius:var(--radius);}
    .msg-row.user .bubble{background:var(--user-bubble);border:none;border-top-right-radius:6px}
    [dir="rtl"] .msg-row.user .bubble{border-top-right-radius:var(--radius);border-top-left-radius:6px;}

    .bubble img{max-width:100%;height:auto;border-radius:16px;margin:12px 0;box-shadow:0 8px 25px rgba(0,0,0,0.15);cursor:zoom-in;transition:transform 0.2s;border:1px solid var(--border);}
    .bubble img:active{transform:scale(1.02);}

    .gemini-cursor{display:inline-block;width:14px;height:14px;margin-inline-start:6px;background:linear-gradient(135deg,var(--accent),var(--accent2));mask-image:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 0l2.5 9.5L24 12l-9.5 2.5L12 24l-2.5-9.5L0 12l9.5-2.5z"/></svg>');-webkit-mask-image:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 0l2.5 9.5L24 12l-9.5 2.5L12 24l-2.5-9.5L0 12l9.5-2.5z"/></svg>');mask-size:cover;-webkit-mask-size:cover;animation:spinPulse 1s infinite linear;transform-origin:center;vertical-align:middle;}
    @keyframes spinPulse{0%{transform:scale(0.8) rotate(0deg);opacity:0.5;}50%{transform:scale(1.2) rotate(90deg);opacity:1;filter:drop-shadow(0 0 5px var(--accent));}100%{transform:scale(0.8) rotate(180deg);opacity:0.5;}}

    .skeleton-img{width:100%;max-width:400px;height:350px;margin:15px auto;border-radius:18px;background:linear-gradient(90deg,var(--surface2) 25%,var(--surface3) 50%,var(--surface2) 75%);background-size:200% 100%;animation:skeletonLoading 1.5s infinite linear;box-shadow:0 8px 25px rgba(0,0,0,0.1);display:flex;align-items:center;justify-content:center;color:var(--text3);font-size:2rem;}
    @keyframes skeletonLoading{0%{background-position:200% 0;}100%{background-position:-200% 0;}}

    .bubble p{margin-bottom:12px}.bubble p:last-child{margin-bottom:0}
    .bubble ul,.bubble ol{padding-inline-start:24px;margin:12px 0}
    .bubble li{margin-bottom:6px;}
    .bubble .table-wrapper{width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;margin:16px 0;border-radius:var(--radius-sm);border:1px solid var(--border);}
    .bubble table{width:100%;border-collapse:collapse;min-width:400px;}
    .bubble th,.bubble td{border:1px solid var(--border);padding:10px 14px;text-align:start;white-space:nowrap;}
    .bubble th{background:var(--surface3);font-weight:600;}

    .code-container{position:relative;margin:16px 0;background:var(--surface3);border-radius:var(--radius-sm);border:1px solid var(--border);overflow:hidden;max-width:100%;}
    .code-header{display:flex;justify-content:space-between;align-items:center;background:#12141a;padding:8px 16px;font-size:0.8rem;color:var(--text2);font-family:'JetBrains Mono',monospace;}
    .copy-btn{background:var(--surface2);border:none;color:var(--text);cursor:pointer;display:flex;align-items:center;gap:6px;font-size:0.8rem;padding:4px 10px;border-radius:var(--radius-pill);transition:all 0.2s;}
    .copy-btn:hover{background:var(--accent);color:#fff;}
    .code-container pre{margin:0;padding:16px;overflow-x:auto;-webkit-overflow-scrolling:touch;font-family:'JetBrains Mono',monospace;font-size:0.85rem;max-width:100%;}
    .code-container pre code{white-space:pre;display:block;}
    .bubble code:not(pre code){font-family:'JetBrains Mono',monospace;font-size:.85rem;background:var(--surface3);padding:3px 6px;border-radius:6px;color:var(--accent);}

    .katex-display{overflow-x:auto;overflow-y:hidden;padding:8px 0;-webkit-overflow-scrolling:touch;}
    .katex{font-size:1.05em;}

    .file-chip{display:inline-flex;align-items:center;gap:6px;background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius-pill);padding:4px 12px;font-size:0.85rem;margin:0 4px 8px 0;color:var(--text);}
    .file-chip button{background:none;border:none;color:var(--danger);cursor:pointer;font-size:1rem;padding:0;margin-left:4px;transition:transform 0.2s;}
    .file-chip button:hover{transform:scale(1.2);}
    .file-prev{display:flex;align-items:center;gap:8px;background:var(--surface3);padding:8px 12px;border-radius:8px;margin-bottom:8px;font-size:0.85rem;}
    .mem-badge{font-size:.75rem;color:var(--text3);padding:4px 30px 10px;display:flex;align-items:center;gap:6px;font-weight:600;}

    /* INPUT */
    .input-area{padding:0 24px 30px;display:flex;flex-direction:column;align-items:center;flex-shrink:0;}
    .input-wrapper{width:100%;max-width:850px;position:relative;}
    .file-chips-container{width:100%;max-width:850px;display:flex;flex-wrap:wrap;margin-bottom:8px;}
    .input-box{display:flex;align-items:flex-end;gap:10px;background:var(--surface);border:1px solid var(--border);border-radius:32px;padding:10px 14px;transition:all var(--tr);box-shadow:0 8px 30px rgba(0,0,0,0.15);}
    .input-box:focus-within{border-color:var(--accent);box-shadow:0 8px 30px var(--accent-soft),0 0 0 3px var(--accent-soft);}

    .btn-attach{background:none;border:none;color:var(--text3);cursor:pointer;padding:8px;border-radius:50%;transition:all var(--tr);display:flex;align-items:center;justify-content:center;width:38px;height:38px;}
    .btn-attach:hover{color:var(--accent);background:var(--surface2);}

    .input-box textarea{flex:1;background:none;border:none;outline:none;color:var(--text);font-family:'Cairo',sans-serif;font-size:.98rem;resize:none;max-height:160px;line-height:1.6;padding:8px 0;}
    .input-box textarea::placeholder{color:var(--text3)}

    /* Action buttons in input */
    .btn-send,.btn-stop,.btn-voice{width:38px;height:38px;border:none;border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all var(--tr);flex-shrink:0;margin-bottom:2px;}
    .btn-send{background:linear-gradient(135deg,var(--accent),var(--accent2));color:#fff;}
    .btn-send:hover{opacity:.9;transform:scale(1.08) rotate(-10deg);}
    [dir="rtl"] .btn-send:hover{transform:scale(1.08) rotate(10deg);}
    .btn-send:disabled{opacity:.4;cursor:not-allowed;transform:none;}
    .btn-stop{background:var(--surface3);color:var(--text);border:1px solid var(--border);}
    .btn-stop:hover{background:var(--danger);color:#fff;transform:scale(1.05);}
    .btn-voice{background:var(--surface2);color:var(--text2);}
    .btn-voice:hover{background:var(--surface3);color:var(--accent);transform:scale(1.05);}

    /* Recording state */
    .btn-voice.recording{background:var(--danger);color:#fff;animation:pulseRecord 1.5s infinite;}
    @keyframes pulseRecord{0%{box-shadow:0 0 0 0 rgba(247,95,95,0.4);}70%{box-shadow:0 0 0 12px rgba(247,95,95,0);}100%{box-shadow:0 0 0 0 rgba(247,95,95,0);}}

    /* STT status banner */
    .stt-status{display:none;align-items:center;gap:10px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-pill);padding:8px 18px;font-size:.85rem;color:var(--text2);width:100%;max-width:850px;margin-bottom:8px;box-shadow:0 4px 15px rgba(0,0,0,0.1);}
    .stt-status.visible{display:flex;}
    .stt-dot{width:10px;height:10px;border-radius:50%;background:var(--danger);animation:pulseRecord 1.5s infinite;flex-shrink:0;}
    .stt-text{flex:1;font-style:italic;}
    /* TTS playing indicator */
    .tts-badge{display:inline-flex;align-items:center;gap:6px;background:linear-gradient(135deg,rgba(79,142,247,0.15),rgba(124,92,247,0.15));border:1px solid var(--border);border-radius:var(--radius-pill);padding:5px 14px;font-size:.8rem;color:var(--accent);margin-top:8px;cursor:pointer;}
    .tts-badge:hover{background:var(--accent-soft);}
    .tts-wave{display:flex;align-items:center;gap:2px;height:14px;}
    .tts-wave span{display:block;width:3px;border-radius:2px;background:var(--accent);animation:wave 1s ease-in-out infinite;}
    .tts-wave span:nth-child(1){height:5px;animation-delay:0s;}
    .tts-wave span:nth-child(2){height:10px;animation-delay:0.15s;}
    .tts-wave span:nth-child(3){height:14px;animation-delay:0.3s;}
    .tts-wave span:nth-child(4){height:10px;animation-delay:0.45s;}
    .tts-wave span:nth-child(5){height:5px;animation-delay:0.6s;}
    @keyframes wave{0%,100%{transform:scaleY(0.5);}50%{transform:scaleY(1);}}

    /* MODAL */
    .overlay{position:fixed;inset:0;z-index:999;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;backdrop-filter:blur(8px);opacity:0;pointer-events:none;transition:opacity var(--tr)}
    .overlay.open{opacity:1;pointer-events:all}
    .modal{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:32px;width:min(440px,90vw);box-shadow:0 30px 80px rgba(0,0,0,.5);transform:translateY(20px) scale(0.95);transition:all var(--tr)}
    .overlay.open .modal{transform:translateY(0) scale(1)}
    .m-header{display:flex;align-items:center;gap:12px;margin-bottom:24px}
    .m-title{font-size:1.3rem;font-weight:700;flex:1}
    .m-close{background:var(--surface2);border:none;color:var(--text);cursor:pointer;width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;transition:background var(--tr);}
    .m-close:hover{background:var(--danger);color:#fff;}
    .s-row{display:flex;align-items:center;justify-content:space-between;padding:16px 0;border-bottom:1px solid var(--border)}
    .s-lbl{font-size:.95rem;font-weight:600;color:var(--text)}
    .s-desc{font-size:.8rem;color:var(--text3);margin-top:4px}
    .toggle{position:relative;width:48px;height:26px}
    .toggle input{opacity:0;width:0;height:0}
    .tslider{position:absolute;inset:0;background:var(--surface3);border-radius:var(--radius-pill);cursor:pointer;transition:all var(--tr)}
    .tslider::before{content:'';position:absolute;width:20px;height:20px;border-radius:50%;background:#fff;top:3px;left:4px;transition:all var(--tr);box-shadow:0 2px 5px rgba(0,0,0,0.2);}
    .toggle input:checked+.tslider{background:var(--accent)}
    .toggle input:checked+.tslider::before{transform:translateX(20px)}
    select.s-input{width:auto;padding:8px 16px;background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius-pill);color:var(--text);cursor:pointer;font-family:'Cairo',sans-serif;font-weight:600;}
    .btn-save{width:100%;margin-top:24px;padding:14px;background:linear-gradient(135deg,var(--accent),var(--accent2));color:#fff;border:none;border-radius:var(--radius-pill);cursor:pointer;font-family:'Cairo',sans-serif;font-size:1rem;font-weight:700;transition:opacity var(--tr);}
    .btn-save:hover{opacity:.9}
    .btn-danger{padding:8px 18px;background:rgba(247,95,95,.12);border:1px solid var(--danger);color:var(--danger);border-radius:var(--radius-pill);cursor:pointer;font-size:.9rem;font-weight:600;font-family:'Cairo',sans-serif;transition:all var(--tr);}
    .btn-danger:hover{background:var(--danger);color:#fff;}

    @media (max-width: 640px) {
      .msg-row{padding:6px 12px;gap:10px;}
      .bubble{max-width:92vw;padding:12px 14px;font-size:.93rem;}
      .msg-row.bot .bubble{padding:6px 2px;}
      .topbar{height:56px;padding:0 14px;}
      .input-area{padding:0 10px 18px;}
      .code-container pre{font-size:0.78rem;padding:12px;}
      .bubble th,.bubble td{font-size:0.85rem;padding:8px 10px;}
      .w-title{font-size:1.8rem;}
      .chips{gap:8px;}
      .chip{font-size:.82rem;padding:8px 14px;}
      .sidebar{position:fixed;top:0;bottom:0;left:0;z-index:100;height:100vh;box-shadow:4px 0 20px rgba(0,0,0,0.2);transition:transform 0.3s ease,width 0.3s ease;}
      [dir="rtl"] .sidebar{left:auto;right:0;}
      .sidebar.collapsed{transform:translateX(-100%);width:var(--sidebar-w) !important;min-width:var(--sidebar-w) !important;}
      [dir="rtl"] .sidebar.collapsed{transform:translateX(100%);}
      .sidebar:not(.collapsed){transform:translateX(0);}
    }
  </style>
</head>
<body>
<div class="app">
  <aside class="sidebar collapsed" id="sidebar">
    <div class="sidebar-header">
      <div class="s-logo">
        <img src="https://copilot.microsoft.com/th/id/BCO.f29916dd-b0c1-4089-87cd-43d099a7d1a6.png" alt="Genisi"/>
        <span class="s-logo-name">Genisi AI</span>
      </div>
      <button class="close-sidebar-btn" onclick="toggleSidebar()" title="ุฅุฎูุงุก ุงู„ู‚ุงุฆู…ุฉ">
        <i data-lucide="x" class="icon"></i>
      </button>
    </div>
    <button class="btn-new" onclick="newChat()" id="i18n-new-chat">
      <i data-lucide="sparkles" class="icon-sm"></i>
      <span>New Chat</span>
    </button>
    <div class="s-label" id="i18n-chats-label">CHATS</div>
    <div class="chats-list" id="chats-list"></div>
    <div class="s-footer">
      <button class="btn-icon" onclick="openSettings()" title="Settings">
        <i data-lucide="settings" class="icon"></i>
      </button>
      <button class="btn-icon" id="theme-btn" onclick="toggleTheme()" title="Toggle theme">
        <i data-lucide="moon" class="icon" id="theme-icon"></i>
      </button>
    </div>
  </aside>

  <main class="main">
    <div class="topbar">
      <button class="btn-icon" id="menu-toggle-btn" onclick="toggleSidebar()">
        <i data-lucide="menu" class="icon" id="menu-icon"></i>
      </button>
      <div class="topbar-title" id="topbar-title">Genisi AI</div>
    </div>
    <div class="chat-area" id="chat-area"></div>
    <div class="input-area">
      <div class="stt-status" id="stt-status">
        <div class="stt-dot"></div>
        <span class="stt-text" id="stt-text">Listening...</span>
        <button class="btn-icon" style="width:28px;height:28px;" onclick="stopSpeechInput()" title="Stop">
          <i data-lucide="square" class="icon-sm"></i>
        </button>
      </div>
      <div class="file-chips-container" id="file-chips"></div>
      <div class="input-wrapper">
        <div class="input-box">
          <input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)" />
          <button class="btn-attach" onclick="document.getElementById('file-input').click()" title="Attach file">
            <i data-lucide="paperclip" class="icon"></i>
          </button>
          <textarea id="msg-input" rows="1" onkeydown="handleKey(event)" oninput="autoResize(this)" placeholder="Type a message..."></textarea>
          <button class="btn-voice" id="voice-btn" onclick="toggleSpeechInput()" title="Voice input">
            <i data-lucide="mic" class="icon" id="mic-icon"></i>
          </button>
          <button class="btn-send" id="send-btn" onclick="sendMessage()" title="Send">
            <i data-lucide="send" class="icon"></i>
          </button>
          <button class="btn-stop" id="stop-btn" onclick="stopGeneration()" style="display:none;" title="Stop generation">
            <i data-lucide="square" class="icon"></i>
          </button>
        </div>
      </div>
    </div>
  </main>
</div>

<!-- SETTINGS MODAL -->
<div class="overlay" id="settings-modal">
  <div class="modal">
    <div class="m-header">
      <div class="m-title" id="i18n-settings-title">Settings</div>
      <button class="m-close" onclick="closeSettings()">
        <i data-lucide="x" class="icon-sm"></i>
      </button>
    </div>
    <div class="s-row">
      <div class="s-lbl" id="i18n-lang-lbl">Language</div>
      <select id="lang-select" class="s-input" onchange="changeLanguage(this.value)">
        <option value="en">English</option>
        <option value="ar">ุงู„ุนุฑุจูŠุฉ</option>
        <option value="fr">Franรงais</option>
        <option value="es">Espaรฑol</option>
      </select>
    </div>
    <div class="s-row">
      <div class="s-lbl" id="i18n-dark-lbl">Dark Mode</div>
      <label class="toggle">
        <input type="checkbox" id="dark-toggle" onchange="applyThemeToggle()"/>
        <span class="tslider"></span>
      </label>
    </div>
    <div class="s-row">
      <div>
        <div class="s-lbl" id="i18n-tts-lbl">Auto-speak Responses</div>
        <div class="s-desc" id="i18n-tts-desc">Read bot responses aloud automatically</div>
      </div>
      <label class="toggle">
        <input type="checkbox" id="tts-toggle" onchange="saveTtsSetting()"/>
        <span class="tslider"></span>
      </label>
    </div>
    <div class="s-row">
      <div>
        <div class="s-lbl" id="i18n-del-lbl">Delete All Chats</div>
        <div class="s-desc" id="i18n-del-desc">This action cannot be undone</div>
      </div>
      <button class="btn-danger" onclick="clearAllChats()" id="i18n-del-btn">
        <i data-lucide="trash-2" class="icon-sm" style="display:inline;vertical-align:middle;margin-right:4px;"></i>Delete
      </button>
    </div>
    <button class="btn-save" onclick="closeSettings()" id="i18n-save-btn">Close</button>
  </div>
</div>

<script>
// โ•โ•โ•โ•โ•โ•โ•โ• i18n โ•โ•โ•โ•โ•โ•โ•โ•
const i18n = {
  en: { newChat:"โœฆ New Chat", chatsLabel:"CHATS", settings:"Settings", lang:"Language", dark:"Dark Mode", ttsLabel:"Auto-speak Responses", ttsDesc:"Read bot responses aloud automatically", del:"Delete All Chats", delDesc:"This action cannot be undone", delBtn:"Delete", saveBtn:"Close", placeholder:"Type your message... (Enter to send)", welcomeTitle:"Welcome to Genisi", welcomeSub:"Your smart assistant by AnesNT โ€” Batna ๐Ÿ‡ฉ๐Ÿ‡ฟ", c1:"What is AI?", c2:"Write Python code", c3:"Summarize a topic", c4:"Design an image in space ๐Ÿš€", errConnect:"Connection Error", memBadge:"Memory: {c}/{t} messages", stopMsg:"[Generation stopped by user]", vListening:"Listening... speak now", vProcessing:"Processing your voice...", vPlay:"Speaking response...", vEnd:"Done speaking", vNotSupported:"Voice input not supported in this browser" },
  ar: { newChat:"โœฆ ู…ุญุงุฏุซุฉ ุฌุฏูŠุฏุฉ", chatsLabel:"ุงู„ู…ุญุงุฏุซุงุช", settings:"ุงู„ุฅุนุฏุงุฏุงุช", lang:"ุงู„ู„ุบุฉ", dark:"ุงู„ูˆุถุน ุงู„ู„ูŠู„ูŠ", ttsLabel:"ู‚ุฑุงุกุฉ ุงู„ุฑุฏูˆุฏ ุตูˆุชูŠุงู‹", ttsDesc:"ุงู‚ุฑุฃ ุฑุฏูˆุฏ ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ ุจุตูˆุช ุชู„ู‚ุงุฆูŠ", del:"ุญุฐู ุฌู…ูŠุน ุงู„ู…ุญุงุฏุซุงุช", delDesc:"ู„ุง ูŠู…ูƒู† ุงู„ุชุฑุงุฌุน ุนู† ู‡ุฐุง ุงู„ุฅุฌุฑุงุก", delBtn:"ุญุฐู", saveBtn:"ุฅุบู„ุงู‚", placeholder:"ุงูƒุชุจ ุฑุณุงู„ุชูƒ... (Enter ู„ู„ุฅุฑุณุงู„)", welcomeTitle:"ู…ุฑุญุจู‹ุง ููŠ Genisi", welcomeSub:"ุฃู†ุง GenisiุŒ ู…ุณุงุนุฏูƒ ุงู„ุฐูƒูŠ ู…ู† AnesNT โ€” ุจุงุชู†ุฉ ๐Ÿ‡ฉ๐Ÿ‡ฟ", c1:"ู…ุง ู‡ูˆ ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠุŸ", c2:"ุงูƒุชุจ ูƒูˆุฏ ุจุงูŠุซูˆู†", c3:"ู„ุฎุต ู„ูŠ ู…ูˆุถูˆุนุงู‹", c4:"ุตู…ู… ุตูˆุฑุฉ ุจุงู„ูุถุงุก ๐Ÿš€", errConnect:"ุฎุทุฃ ููŠ ุงู„ุงุชุตุงู„", memBadge:"ุงู„ุฐุงูƒุฑุฉ: {c}/{t} ุฑุณุงุฆู„", stopMsg:"[ุชู… ุฅูŠู‚ุงู ุงู„ุชูˆู„ูŠุฏ]", vListening:"ุงุณุชู…ุน... ุชุญุฏุซ ุงู„ุขู†", vProcessing:"ุฌุงุฑูŠ ู…ุนุงู„ุฌุฉ ุตูˆุชูƒ...", vPlay:"ูŠู‚ุฑุฃ ุงู„ุฑุฏ ุงู„ุขู†...", vEnd:"ุงู†ุชู‡ุช ุงู„ู‚ุฑุงุกุฉ ุงู„ุตูˆุชูŠุฉ", vNotSupported:"ุงู„ุชุนุฑู ุนู„ู‰ ุงู„ูƒู„ุงู… ุบูŠุฑ ู…ุฏุนูˆู… ููŠ ู‡ุฐุง ุงู„ู…ุชุตูุญ" },
  fr: { newChat:"โœฆ Nouveau", chatsLabel:"DISCUSSIONS", settings:"Paramรจtres", lang:"Langue", dark:"Mode Sombre", ttsLabel:"Lire les rรฉponses", ttsDesc:"Lire les rรฉponses du bot ร  voix haute", del:"Supprimer Tout", delDesc:"Action irrรฉversible", delBtn:"Supprimer", saveBtn:"Fermer", placeholder:"ร‰crivez votre message...", welcomeTitle:"Bienvenue sur Genisi", welcomeSub:"Votre assistant par AnesNT โ€” Batna ๐Ÿ‡ฉ๐Ÿ‡ฟ", c1:"Qu'est-ce que l'IA?", c2:"Code Python", c3:"Rรฉsumer un sujet", c4:"Crรฉer une image ๐Ÿš€", errConnect:"Erreur de connexion", memBadge:"Mรฉmoire: {c}/{t} msgs", stopMsg:"[Gรฉnรฉration arrรชtรฉe]", vListening:"ร‰coute... parlez maintenant", vProcessing:"Traitement de votre voix...", vPlay:"Lecture en cours...", vEnd:"Fin de la lecture", vNotSupported:"Reconnaissance vocale non supportรฉe" },
  es: { newChat:"โœฆ Nuevo Chat", chatsLabel:"CHATS", settings:"Ajustes", lang:"Idioma", dark:"Modo Oscuro", ttsLabel:"Leer respuestas", ttsDesc:"Leer respuestas del bot en voz alta", del:"Borrar Todo", delDesc:"Acciรณn irreversible", delBtn:"Borrar", saveBtn:"Cerrar", placeholder:"Escribe tu mensaje...", welcomeTitle:"Bienvenido a Genisi", welcomeSub:"Tu asistente por AnesNT โ€” Batna ๐Ÿ‡ฉ๐Ÿ‡ฟ", c1:"ยฟQuรฉ es la IA?", c2:"Cรณdigo Python", c3:"Resumir", c4:"Diseรฑar imagen ๐Ÿš€", errConnect:"Error de conexiรณn", memBadge:"Memoria: {c}/{t} msgs", stopMsg:"[Generaciรณn detenida]", vListening:"Escuchando... habla ahora", vProcessing:"Procesando tu voz...", vPlay:"Leyendo respuesta...", vEnd:"Fin de la lectura", vNotSupported:"Reconocimiento de voz no soportado" }
};

let currentLang = localStorage.getItem('genisi_lang') || 'en';

function applyI18n() {
  const t = i18n[currentLang];
  document.documentElement.dir = currentLang === 'ar' ? 'rtl' : 'ltr';
  document.documentElement.lang = currentLang;
  const newChatBtn = document.getElementById('i18n-new-chat');
  newChatBtn.querySelector('span').textContent = t.newChat;
  document.getElementById('i18n-chats-label').textContent = t.chatsLabel;
  document.getElementById('i18n-settings-title').textContent = t.settings;
  document.getElementById('i18n-lang-lbl').textContent = t.lang;
  document.getElementById('i18n-dark-lbl').textContent = t.dark;
  document.getElementById('i18n-tts-lbl').textContent = t.ttsLabel;
  document.getElementById('i18n-tts-desc').textContent = t.ttsDesc;
  document.getElementById('i18n-del-lbl').textContent = t.del;
  document.getElementById('i18n-del-desc').textContent = t.delDesc;
  document.getElementById('i18n-save-btn').textContent = t.saveBtn;
  document.getElementById('msg-input').placeholder = t.placeholder;
  if(!activeChatId) renderWelcome();
  renderChatList();
}
function changeLanguage(val){ currentLang=val; localStorage.setItem('genisi_lang',val); applyI18n(); }

// โ•โ•โ•โ•โ•โ•โ•โ• STATE โ•โ•โ•โ•โ•โ•โ•โ•
const genId = () => Date.now().toString(36)+Math.random().toString(36).substring(2,6);
let userId = localStorage.getItem('genisi_user_id');
if(!userId){ userId='user_'+genId(); localStorage.setItem('genisi_user_id',userId); }

let chats = JSON.parse(localStorage.getItem('genisi_chats')||'[]');
let activeChatId = null;
let isGenerating = false;
let pendingFiles = [];
let currentAbortController = null;
let autoTTS = localStorage.getItem('genisi_tts') !== 'false';
let currentUtterance = null;

// โ•โ•โ•โ•โ•โ•โ•โ• SPEECH RECOGNITION (STT) โ•โ•โ•โ•โ•โ•โ•โ•
let recognition = null;
let isListening = false;

function initSpeechRecognition() {
  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  if (!SpeechRecognition) return null;
  const rec = new SpeechRecognition();
  rec.continuous = false;
  rec.interimResults = true;
  // Set language based on current UI language
  const langMap = { en: 'en-US', ar: 'ar-DZ', fr: 'fr-FR', es: 'es-ES' };
  rec.lang = langMap[currentLang] || 'en-US';

  rec.onstart = () => {
    isListening = true;
    document.getElementById('stt-status').classList.add('visible');
    document.getElementById('stt-text').textContent = i18n[currentLang].vListening;
    const voiceBtn = document.getElementById('voice-btn');
    voiceBtn.classList.add('recording');
    // swap mic icon to mic-off
    lucide.createIcons({ icons: { 'mic-off': lucide.icons['mic-off'] }, attrs: { class: 'icon' } });
    const micIcon = document.getElementById('mic-icon');
    micIcon.setAttribute('data-lucide', 'mic-off');
    lucide.createIcons({ nameAttr: 'data-lucide', attrs: { class: 'icon' } });
  };

  rec.onresult = (event) => {
    let interim = '';
    let final = '';
    for (let i = event.resultIndex; i < event.results.length; i++) {
      if (event.results[i].isFinal) final += event.results[i][0].transcript;
      else interim += event.results[i][0].transcript;
    }
    const input = document.getElementById('msg-input');
    input.value = (final || interim);
    autoResize(input);
    if (final) document.getElementById('stt-text').textContent = final;
    else document.getElementById('stt-text').textContent = interim || i18n[currentLang].vListening;
  };

  rec.onend = () => {
    isListening = false;
    document.getElementById('stt-status').classList.remove('visible');
    const voiceBtn = document.getElementById('voice-btn');
    voiceBtn.classList.remove('recording');
    const micIcon = document.getElementById('mic-icon');
    micIcon.setAttribute('data-lucide', 'mic');
    lucide.createIcons({ nameAttr: 'data-lucide', attrs: { class: 'icon' } });
    // Auto-send if there's text
    const input = document.getElementById('msg-input');
    if (input.value.trim()) sendMessage();
  };

  rec.onerror = (event) => {
    console.error('STT error:', event.error);
    isListening = false;
    document.getElementById('stt-status').classList.remove('visible');
    const voiceBtn = document.getElementById('voice-btn');
    voiceBtn.classList.remove('recording');
    const micIcon = document.getElementById('mic-icon');
    micIcon.setAttribute('data-lucide', 'mic');
    lucide.createIcons({ nameAttr: 'data-lucide', attrs: { class: 'icon' } });
  };

  return rec;
}

function toggleSpeechInput() {
  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  if (!SpeechRecognition) {
    alert(i18n[currentLang].vNotSupported);
    return;
  }
  if (isListening) {
    stopSpeechInput();
    return;
  }
  recognition = initSpeechRecognition();
  if (recognition) recognition.start();
}

function stopSpeechInput() {
  if (recognition && isListening) recognition.stop();
}

// โ•โ•โ•โ•โ•โ•โ•โ• TTS (Text-to-Speech) โ•โ•โ•โ•โ•โ•โ•โ•
function saveTtsSetting() {
  autoTTS = document.getElementById('tts-toggle').checked;
  localStorage.setItem('genisi_tts', autoTTS);
}

function speakText(text) {
  if (!window.speechSynthesis) return;
  // Cancel any ongoing speech
  window.speechSynthesis.cancel();
  // Strip markdown symbols for cleaner speech
  const clean = text
    .replace(/```[\s\S]*?```/g, 'code block.')
    .replace(/`([^`]+)`/g, '$1')
    .replace(/\*\*([^*]+)\*\*/g, '$1')
    .replace(/\*([^*]+)\*/g, '$1')
    .replace(/#{1,6}\s/g, '')
    .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
    .replace(/!\[([^\]]+)\]\([^)]+\)/g, 'image.')
    .replace(/\n+/g, '. ')
    .trim();

  const utterance = new SpeechSynthesisUtterance(clean);
  const langMap = { en: 'en-US', ar: 'ar-SA', fr: 'fr-FR', es: 'es-ES' };
  utterance.lang = langMap[currentLang] || 'en-US';
  utterance.rate = 1.0;
  utterance.pitch = 1.0;
  currentUtterance = utterance;
  window.speechSynthesis.speak(utterance);
  return utterance;
}

function stopTTS() {
  if (window.speechSynthesis) window.speechSynthesis.cancel();
}

// โ•โ•โ•โ•โ•โ•โ•โ• MARKDOWN โ•โ•โ•โ•โ•โ•โ•โ•
const renderer = new marked.Renderer();
renderer.code = function(token) {
  const codeText = typeof token === 'string' ? token : token.text || '';
  const lang = typeof token === 'string' ? arguments[1] : token.lang || 'text';
  const escapedCode = String(codeText).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
  return `<div class="code-container"><div class="code-header"><span>${lang}</span><button class="copy-btn" onclick="copyCode(this,'${encodeURIComponent(codeText)}')"><i data-lucide="copy" class="icon-sm"></i> Copy</button></div><pre><code class="language-${lang}">${escapedCode}</code></pre></div>`;
};
renderer.table = function(header, body) {
  if(typeof header==='object'&&header!==null&&'header' in header){
    const token=header;
    const hdr=token.header.map(cell=>`<th>${cell.tokens.map(t=>t.raw||'').join('')}</th>`).join('');
    const rows=(token.rows||[]).map(row=>`<tr>${row.map(cell=>`<td>${cell.tokens.map(t=>t.raw||'').join('')}</td>`).join('')}</tr>`).join('');
    return `<div class="table-wrapper"><table><thead><tr>${hdr}</tr></thead><tbody>${rows}</tbody></table></div>`;
  }
  return `<div class="table-wrapper"><table><thead>${header}</thead><tbody>${body}</tbody></table></div>`;
};
renderer.html = function(html){ return html; };
marked.setOptions({ renderer, breaks:true, gfm:true });

function safeMarked(text){
  if(!text) return '';
  return DOMPurify.sanitize(marked.parse(text),{USE_PROFILES:{html:true}});
}
function renderKaTeX(el){
  if(window.renderMathInElement) renderMathInElement(el,{delimiters:[{left:'$$',right:'$$',display:true},{left:'$',right:'$',display:false},{left:'\\(',right:'\\)',display:false},{left:'\\[',right:'\\]',display:true}],throwOnError:false});
}
function copyCode(btn, encodedCode){
  navigator.clipboard.writeText(decodeURIComponent(encodedCode)).then(()=>{
    const orig = btn.innerHTML;
    btn.innerHTML = '<i data-lucide="check" class="icon-sm" style="color:var(--accent)"></i> Copied!';
    lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon-sm'} });
    setTimeout(()=>{btn.innerHTML=orig; lucide.createIcons({nameAttr:'data-lucide',attrs:{class:'icon-sm'}});},2000);
  });
}
function removeGeminiCursor(){ document.querySelectorAll('.gemini-cursor').forEach(el=>el.remove()); }

// โ•โ•โ•โ•โ•โ•โ•โ• UTILS โ•โ•โ•โ•โ•โ•โ•โ•
const saveChats = () => localStorage.setItem('genisi_chats',JSON.stringify(chats));
const getChat = (id) => chats.find(c=>c.id===(id??activeChatId));
function esc(t){ return String(t).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
function scrollToBottom(){ const area=document.getElementById('chat-area'); area.scrollTop=area.scrollHeight; }

async function handleFiles(files){
  for(let f of files){
    const isText = f.type.startsWith('text/')||f.name.match(/\.(py|js|html|css|json|md|txt|csv|cpp|java)$/i);
    const reader = new FileReader();
    reader.onload = (e)=>{
      let data=e.target.result;
      if(!isText) data=data.split(',')[1];
      pendingFiles.push({name:f.name,type:f.type||'application/octet-stream',data,isText});
      renderFileChips();
    };
    if(isText) reader.readAsText(f); else reader.readAsDataURL(f);
  }
  document.getElementById('file-input').value='';
}
function renderFileChips(){
  const c=document.getElementById('file-chips'); c.innerHTML='';
  pendingFiles.forEach((f,idx)=>{
    const icon = f.isText ? 'file-text' : 'image';
    c.innerHTML += `<div class="file-chip"><i data-lucide="${icon}" class="icon-sm"></i>${f.name}<button onclick="removeFile(${idx})"><i data-lucide="x" class="icon-sm"></i></button></div>`;
  });
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon-sm'} });
}
function removeFile(idx){ pendingFiles.splice(idx,1); renderFileChips(); }

// โ•โ•โ•โ•โ•โ•โ•โ• THEME โ•โ•โ•โ•โ•โ•โ•โ•
function applyTheme(t){
  document.documentElement.setAttribute('data-theme',t);
  localStorage.setItem('genisi_theme',t);
  document.getElementById('dark-toggle').checked = t==='dark';
  const themeIcon = document.getElementById('theme-icon');
  themeIcon.setAttribute('data-lucide', t==='dark'?'moon':'sun');
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon'} });
}
function toggleTheme(){ applyTheme(document.documentElement.getAttribute('data-theme')==='dark'?'light':'dark'); }
function applyThemeToggle(){ applyTheme(document.getElementById('dark-toggle').checked?'dark':'light'); }

// โ•โ•โ•โ•โ•โ•โ•โ• SIDEBAR โ•โ•โ•โ•โ•โ•โ•โ•
function updateMenuIcon(){
  const sidebar=document.getElementById('sidebar');
  const menuIcon=document.getElementById('menu-icon');
  menuIcon.setAttribute('data-lucide', sidebar.classList.contains('collapsed')?'menu':'x');
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon'} });
}
function toggleSidebar(){ document.getElementById('sidebar').classList.toggle('collapsed'); updateMenuIcon(); }
function initSidebarState(){
  const sidebar=document.getElementById('sidebar');
  if(window.innerWidth<=640) sidebar.classList.add('collapsed');
  else sidebar.classList.remove('collapsed');
  updateMenuIcon();
}
window.addEventListener('resize',()=>{
  const sidebar=document.getElementById('sidebar');
  if(window.innerWidth>640) sidebar.classList.remove('collapsed');
  else sidebar.classList.add('collapsed');
  updateMenuIcon();
});

// โ•โ•โ•โ•โ•โ•โ•โ• SETTINGS โ•โ•โ•โ•โ•โ•โ•โ•
function openSettings(){ document.getElementById('settings-modal').classList.add('open'); document.getElementById('lang-select').value=currentLang; document.getElementById('tts-toggle').checked=autoTTS; }
function closeSettings(){ document.getElementById('settings-modal').classList.remove('open'); }

// โ•โ•โ•โ•โ•โ•โ•โ• CHAT LIST โ•โ•โ•โ•โ•โ•โ•โ•
function renderChatList(){
  const list=document.getElementById('chats-list'); list.innerHTML='';
  [...chats].reverse().forEach(chat=>{
    const div=document.createElement('div');
    div.className='chat-item'+(chat.id===activeChatId?' active':'');
    div.innerHTML=`<i data-lucide="message-circle" class="icon-sm"></i><span class="ct">${esc(chat.title||'Chat')}</span><button class="del-btn" onclick="deleteChat('${chat.id}',event)"><i data-lucide="x" class="icon-sm"></i></button>`;
    div.onclick = ()=>loadChat(chat.id);
    list.appendChild(div);
  });
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon-sm'} });
}

function renderWelcome(){
  const t=i18n[currentLang];
  document.getElementById('topbar-title').textContent='Genisi AI';
  document.getElementById('chat-area').innerHTML=`<div class="welcome" id="welcome"><img src="https://copilot.microsoft.com/th/id/BCO.f29916dd-b0c1-4089-87cd-43d099a7d1a6.png" class="w-logo" alt="Genisi"/><div class="w-title">${t.welcomeTitle}</div><div class="w-sub">${t.welcomeSub}</div><div class="chips"><div class="chip" onclick="quickSend('${t.c1}')">${t.c1}</div><div class="chip" onclick="quickSend('${t.c2}')">${t.c2}</div><div class="chip" onclick="quickSend('${t.c3}')">${t.c3}</div><div class="chip" onclick="quickSend('${t.c4}')">${t.c4}</div></div></div>`;
}

function newChat(){ activeChatId=null; pendingFiles=[]; renderFileChips(); document.getElementById('msg-input').value=''; renderWelcome(); renderChatList(); }

function loadChat(id){
  activeChatId=id; const chat=getChat(id); if(!chat) return;
  document.getElementById('topbar-title').textContent=chat.title;
  const area=document.getElementById('chat-area'); area.innerHTML='';
  chat.history.forEach(entry=>{ appendBubble('user',entry.user,false,entry.uiFiles); appendBubble('bot',entry.bot,true); });
  if(chat.history.length) appendMemBadge(chat.history.length,chat.history.length);
  scrollToBottom(); renderChatList();
}
function deleteChat(id,e){ e.stopPropagation(); chats=chats.filter(c=>c.id!==id); saveChats(); if(activeChatId===id) newChat(); else renderChatList(); }
function clearAllChats(){ chats=[]; saveChats(); newChat(); closeSettings(); }
function stopGeneration(){ if(currentAbortController) currentAbortController.abort(); }
function quickSend(text){ document.getElementById('msg-input').value=text; sendMessage(); }
function handleKey(e){ if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();sendMessage();} }
function autoResize(el){ el.style.height='auto'; el.style.height=Math.min(el.scrollHeight,160)+'px'; }

// โ•โ•โ•โ•โ•โ•โ•โ• SEND MESSAGE โ•โ•โ•โ•โ•โ•โ•โ•
async function sendMessage(){
  if(isGenerating||isListening) return;
  const input=document.getElementById('msg-input'); let text=input.value.trim();
  if(!text&&pendingFiles.length===0) return;
  const welcome=document.getElementById('welcome'); if(welcome) welcome.remove();
  input.value=''; input.style.height='auto';
  stopTTS();

  if(!activeChatId){
    activeChatId=genId();
    const chatTitle=text?text.slice(0,35)+'...':(pendingFiles[0]?pendingFiles[0].name:'Chat');
    chats.push({id:activeChatId,title:chatTitle,history:[]});
    document.getElementById('topbar-title').textContent=chatTitle;
  }
  const chat=getChat();
  const uiFiles=pendingFiles.map(f=>f.name); const binaryFiles=[];
  pendingFiles.forEach(f=>{
    if(f.isText){ text+=`\n\n\`\`\`${f.name.split('.').pop()}\n// File: ${f.name}\n${f.data}\n\`\`\``; }
    else{ binaryFiles.push({name:f.name,mime_type:f.type,data:f.data}); }
  });
  appendBubble('user',text,false,uiFiles);
  pendingFiles=[]; renderFileChips();

  isGenerating=true;
  document.getElementById('send-btn').style.display='none';
  document.getElementById('stop-btn').style.display='flex';
  const botContentDiv=appendBubble('bot','',true);

  const imageTriggers=["ุงุฑุณู…","ุตู…ู…","ุชุฎูŠู„","ุตูˆุฑุฉ ู„","draw","generate","imagine","create an image","ุชุตู…ูŠู…"];
  const isImageRequest=imageTriggers.some(trigger=>text.toLowerCase().startsWith(trigger));
  currentAbortController=new AbortController();
  let fullBotResponse="";

  try {
    const response=await fetch('/chat',{
      method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify({user_id:userId,message:text,history:chat.history,files:binaryFiles}),
      signal:currentAbortController.signal
    });
    if(!response.ok) throw new Error("Server Error");
    const reader=response.body.getReader();
    const decoder=new TextDecoder("utf-8");
    while(true){
      const{value,done}=await reader.read();
      if(done) break;
      fullBotResponse+=decoder.decode(value,{stream:true});
      let safeHtml=safeMarked(fullBotResponse);
      botContentDiv.innerHTML=safeHtml;
      if(isImageRequest&&!botContentDiv.querySelector('img')) botContentDiv.innerHTML+='<div class="skeleton-img">๐ŸŽจ ุฌุงุฑูŠ ุงู„ุชุฎูŠู„...</div>';
      else botContentDiv.innerHTML+='<span class="gemini-cursor"></span>';
      renderKaTeX(botContentDiv); scrollToBottom();
    }
    botContentDiv.innerHTML=safeMarked(fullBotResponse);
    renderKaTeX(botContentDiv);
    // Add TTS play button
    appendTTSBadge(botContentDiv, fullBotResponse);
    // Auto TTS
    if(autoTTS) speakText(fullBotResponse);
    chat.history.push({user:text,bot:fullBotResponse,uiFiles});
    saveChats(); appendMemBadge(chat.history.length,chat.history.length);
  } catch(err){
    removeGeminiCursor();
    if(err.name==='AbortError'){
      botContentDiv.innerHTML=safeMarked(fullBotResponse)+`<br><br><span style="color:var(--text3);font-style:italic;">${i18n[currentLang].stopMsg}</span>`;
      renderKaTeX(botContentDiv);
      chat.history.push({user:text,bot:fullBotResponse+"\n\n*"+i18n[currentLang].stopMsg+"*",uiFiles});
      saveChats();
    } else { botContentDiv.innerHTML=`<span style="color:var(--danger)">โš ๏ธ ${i18n[currentLang].errConnect}: ${err.message}</span>`; }
  } finally {
    removeGeminiCursor(); isGenerating=false;
    document.getElementById('send-btn').style.display='flex';
    document.getElementById('stop-btn').style.display='none';
    lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon'} });
    renderChatList(); scrollToBottom();
  }
}

// โ•โ•โ•โ•โ•โ•โ•โ• TTS BADGE โ•โ•โ•โ•โ•โ•โ•โ•
function appendTTSBadge(container, text) {
  if (!window.speechSynthesis) return;
  const badge = document.createElement('div');
  badge.className = 'tts-badge';
  badge.title = 'Click to play / stop';
  badge.innerHTML = `<div class="tts-wave"><span></span><span></span><span></span><span></span><span></span></div><span id="tts-label-${Date.now()}">Play</span>`;
  let playing = false;
  badge.onclick = () => {
    if (playing) {
      stopTTS(); playing = false;
      badge.querySelector('span:last-child').textContent = 'Play';
    } else {
      const utt = speakText(text); playing = true;
      badge.querySelector('span:last-child').textContent = i18n[currentLang].vPlay;
      if (utt) utt.onend = () => { playing=false; badge.querySelector('span:last-child').textContent='Play'; };
    }
  };
  container.appendChild(badge);
}

// โ•โ•โ•โ•โ•โ•โ•โ• BUBBLES โ•โ•โ•โ•โ•โ•โ•โ•
function appendBubble(role,text,isMarkdown,filesList=[]){
  const area=document.getElementById('chat-area');
  const row=document.createElement('div'); row.className=`msg-row ${role}`;
  const av=document.createElement('div'); av.className='msg-av';
  if(role==='bot') av.innerHTML=`<img src="https://copilot.microsoft.com/th/id/BCO.f29916dd-b0c1-4089-87cd-43d099a7d1a6.png" alt="G"/>`;
  else av.innerHTML=`<i data-lucide="user" class="icon"></i>`;
  const bub=document.createElement('div'); bub.className='bubble';
  if(filesList&&filesList.length>0) filesList.forEach(name=>{ bub.innerHTML+=`<div class="file-prev"><i data-lucide="paperclip" class="icon-sm"></i>${esc(name)}</div>`; });
  const contentDiv=document.createElement('div');
  contentDiv.dir='auto'; contentDiv.style.unicodeBidi='plaintext';
  if(text){
    contentDiv.innerHTML=isMarkdown?safeMarked(text):esc(text).replace(/\n/g,'<br/>');
    if(isMarkdown) renderKaTeX(contentDiv);
  }
  bub.appendChild(contentDiv); row.appendChild(av); row.appendChild(bub); area.appendChild(row);
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon'} });
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon-sm'} });
  if(role==='bot'){
    const images=bub.querySelectorAll('img');
    if(images.length) Promise.all(Array.from(images).map(img=>img.complete?Promise.resolve():new Promise(r=>img.onload=r))).then(()=>scrollToBottom());
    else scrollToBottom();
  } else scrollToBottom();
  return contentDiv;
}

function appendMemBadge(count,total){
  const area=document.getElementById('chat-area'); const b=document.createElement('div'); b.className='mem-badge';
  b.innerHTML=`<i data-lucide="brain" class="icon-sm"></i>${i18n[currentLang].memBadge.replace('{c}',count).replace('{t}',total)}`;
  area.appendChild(b);
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon-sm'} });
  scrollToBottom();
}

// โ•โ•โ•โ•โ•โ•โ•โ• INIT โ•โ•โ•โ•โ•โ•โ•โ•
window.addEventListener('DOMContentLoaded', ()=>{
  applyTheme(localStorage.getItem('genisi_theme')||'dark');
  document.getElementById('lang-select').value=currentLang;
  document.getElementById('tts-toggle').checked=autoTTS;
  applyI18n();
  initSidebarState();
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon'} });
  lucide.createIcons({ nameAttr:'data-lucide', attrs:{class:'icon-sm'} });
});
</script>
</body>
</html>