File size: 47,097 Bytes
cb8bcc0
6dd95c3
cb8bcc0
e16f30c
5b19d71
332718b
d6cf69e
224b8d2
a56402f
d6cf69e
332718b
6dd95c3
224b8d2
a20f468
 
 
d6cf69e
e2b719d
 
e16f30c
 
 
 
 
5b19d71
a56402f
e52e0f4
 
e16f30c
 
e2b719d
332718b
e2b719d
e16f30c
 
 
 
a56402f
e52e0f4
 
7fd6923
332718b
7fd6923
5b19d71
94533db
 
d6cf69e
7fd6923
d6cf69e
224b8d2
7fd6923
6dd95c3
94533db
5b19d71
 
e52e0f4
e16f30c
94533db
5b19d71
94533db
d6cf69e
94533db
 
5b19d71
 
e52e0f4
94533db
 
 
 
5b19d71
 
a56402f
5b19d71
e16f30c
7fd6923
5b19d71
 
7fd6923
5b19d71
a56402f
e52e0f4
 
5b19d71
 
a56402f
 
e52e0f4
 
 
 
 
 
 
 
d6cf69e
 
5b19d71
 
e52e0f4
 
 
 
 
 
 
 
94533db
d6cf69e
 
5b19d71
332718b
 
7fd6923
5b19d71
332718b
94533db
5b19d71
 
94533db
 
 
d6cf69e
 
a56402f
5b19d71
d6cf69e
e52e0f4
5b19d71
e52e0f4
7fd6923
94533db
5b19d71
 
7fd6923
 
94533db
a56402f
d6cf69e
5b19d71
e52e0f4
 
 
 
224b8d2
e52e0f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b19d71
e52e0f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332718b
d6cf69e
332718b
e52e0f4
 
 
332718b
94533db
c351f8b
5b19d71
e52e0f4
e16f30c
e52e0f4
e16f30c
d6cf69e
 
e52e0f4
 
 
 
e16f30c
e52e0f4
e16f30c
d6cf69e
e52e0f4
 
e16f30c
d6cf69e
 
5b19d71
e52e0f4
 
 
5b19d71
 
d6cf69e
 
5b19d71
 
 
 
e52e0f4
5b19d71
e52e0f4
d6cf69e
e52e0f4
a56402f
5b19d71
d6cf69e
5b19d71
 
c351f8b
d6cf69e
e52e0f4
5b19d71
a56402f
e52e0f4
e16f30c
5b19d71
a56402f
e52e0f4
d6cf69e
e52e0f4
 
a56402f
e52e0f4
 
 
a56402f
e52e0f4
 
 
 
a56402f
 
e52e0f4
 
 
 
a56402f
e52e0f4
 
a56402f
e52e0f4
 
a56402f
e52e0f4
 
 
 
 
 
 
a56402f
d6cf69e
5b19d71
 
 
7fd6923
5b19d71
 
 
e16f30c
c351f8b
 
e52e0f4
a56402f
5b19d71
94533db
c351f8b
 
 
 
e52e0f4
5b19d71
e52e0f4
c351f8b
 
d6cf69e
e52e0f4
5b19d71
e52e0f4
a56402f
5b19d71
e52e0f4
a56402f
5b19d71
d6cf69e
332718b
e16f30c
5b19d71
 
 
 
 
332718b
 
a20f468
e2b719d
cb8bcc0
 
7fd6923
d6cf69e
224b8d2
e52e0f4
e2b719d
7fd6923
9db58f2
7fd6923
e2b719d
 
d6cf69e
a56402f
d6cf69e
 
6dd95c3
e2b719d
7fd6923
e52e0f4
 
 
 
 
 
 
e2b719d
 
d6cf69e
332718b
e2b719d
 
e52e0f4
 
 
e2b719d
 
d6cf69e
e16f30c
d6cf69e
e2b719d
c351f8b
94533db
 
e16f30c
a56402f
 
332718b
a56402f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e52e0f4
a56402f
 
 
 
 
e52e0f4
a56402f
 
 
 
 
e16f30c
a56402f
 
94533db
e2b719d
 
 
 
 
0a4669e
e16f30c
e2b719d
c351f8b
 
a56402f
c351f8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a56402f
c351f8b
a56402f
e2b719d
 
 
 
66e4a72
224b8d2
66e4a72
332718b
 
e16f30c
d6cf69e
 
 
332718b
d6cf69e
 
332718b
e52e0f4
d6cf69e
 
 
 
 
332718b
d6cf69e
e52e0f4
 
d6cf69e
 
 
 
 
332718b
 
e52e0f4
 
d6cf69e
 
 
 
 
 
 
e52e0f4
 
d6cf69e
6dd95c3
d6cf69e
332718b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6cf69e
332718b
 
 
 
 
 
 
224b8d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332718b
 
 
 
 
 
 
 
 
 
e16f30c
 
 
 
d6cf69e
5b19d71
e16f30c
 
 
 
 
 
5b19d71
e16f30c
 
d6cf69e
16520ea
c351f8b
a56402f
c351f8b
d6cf69e
e52e0f4
5b19d71
332718b
 
 
 
 
 
 
 
 
 
d6cf69e
332718b
 
 
 
 
 
 
 
389a55d
332718b
a56402f
332718b
 
389a55d
a56402f
332718b
 
 
 
 
 
 
 
 
 
 
 
c351f8b
332718b
 
 
c351f8b
d6cf69e
66e4a72
5b19d71
332718b
 
 
 
 
 
 
 
 
 
 
 
f59fe60
5b19d71
332718b
 
 
 
 
a56402f
f59fe60
332718b
e16f30c
66e4a72
332718b
 
 
 
 
 
 
 
 
 
5b19d71
c351f8b
 
a56402f
c351f8b
92e308f
332718b
5b19d71
332718b
 
 
5c2fda3
332718b
 
5b19d71
a56402f
 
 
 
5b19d71
 
a56402f
e2b719d
d6cf69e
332718b
 
 
 
 
 
 
d6cf69e
332718b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224b8d2
 
332718b
 
 
 
 
 
 
 
 
 
 
e52e0f4
5b19d71
332718b
 
 
 
f59fe60
332718b
 
 
5b19d71
 
332718b
 
 
 
5b19d71
332718b
c351f8b
332718b
5b19d71
332718b
 
 
c351f8b
5b19d71
 
332718b
 
 
 
 
 
 
 
5b19d71
332718b
5b19d71
 
 
 
92e308f
5b19d71
332718b
 
5b19d71
e52e0f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b19d71
 
e52e0f4
e16f30c
 
5b19d71
 
332718b
 
 
 
 
5b19d71
e2b719d
332718b
 
5b19d71
 
 
 
332718b
5b19d71
332718b
d6cf69e
332718b
e52e0f4
5b19d71
e52e0f4
332718b
e52e0f4
 
 
332718b
e52e0f4
332718b
 
e52e0f4
 
332718b
e52e0f4
332718b
 
e52e0f4
224b8d2
 
 
e52e0f4
 
224b8d2
 
5b19d71
e52e0f4
a56402f
5b19d71
c351f8b
b09618d
332718b
42ea841
e52e0f4
332718b
e52e0f4
 
 
5b19d71
 
 
332718b
5b19d71
332718b
 
 
5b19d71
332718b
5b19d71
a56402f
224b8d2
 
5b19d71
332718b
 
 
 
 
5b19d71
16520ea
 
332718b
 
 
 
9db58f2
d6cf69e
332718b
 
 
c351f8b
d6cf69e
5b19d71
e52e0f4
 
 
332718b
 
 
 
e52e0f4
332718b
e52e0f4
332718b
 
 
5b19d71
d6cf69e
e52e0f4
 
332718b
224b8d2
 
 
 
92e308f
a56402f
332718b
5b19d71
 
332718b
 
 
 
e52e0f4
e2b719d
 
332718b
 
5b19d71
 
332718b
 
 
 
 
 
 
 
 
 
 
 
a56402f
389a55d
332718b
 
 
 
 
 
389a55d
e52e0f4
332718b
e2b719d
cb8bcc0
42ea841
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Genisi AI - مساعدك الذكي</title>
  
  <!-- 🌟 Lucide Icons -->
  <script src="https://unpkg.com/lucide@latest"></script>
  
  <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <!-- KaTeX CSS + JS -->
  <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>
  
  <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; 
      --flash-color: #fbbf24; --pro-color: #a78bfa;
      --thinking-bg: rgba(124, 92, 247, 0.08);
      --thinking-border: rgba(124, 92, 247, 0.2);
      --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);
      --flash-color: #d97706; --pro-color: #7c3aed;
      --thinking-bg: rgba(124, 58, 237, 0.05);
      --thinking-border: rgba(124, 58, 237, 0.15);
    }
    
    *,*::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)}

    .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;padding:0;}
    .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}
    
    .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 svg { width: 18px; height: 18px; }
    .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 svg { width: 18px; height: 18px; color: var(--accent); }
    .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;font-size:.9rem;
      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);}
    .del-btn svg { width: 16px; height: 16px; }
    .s-footer{padding:16px;display:flex;align-items:center;gap:12px; justify-content: space-between; border-top: 1px solid var(--border); margin-top: auto;}
    .s-footer-actions {display: flex; align-items: center; gap: 8px;}
    .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 svg { width: 20px; height: 20px; }
    .btn-icon:hover{background:var(--surface3);color:var(--text);}
    .btn-collapse-sidebar {
      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-collapse-sidebar svg { width: 20px; height: 20px; }
    .btn-collapse-sidebar:hover { background: var(--surface3); color: var(--text); }

    /* 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}
    .btn-show-sidebar {
      width: 42px; height: 42px; background: var(--surface2); border: none;
      border-radius: var(--radius-pill); color: var(--text2); cursor: pointer;
      display: none; align-items: center; justify-content: center; transition: all var(--tr);
    }
    .btn-show-sidebar svg { width: 20px; height: 20px; }
    .btn-show-sidebar:hover { background: var(--surface3); color: var(--text); }
    .sidebar.collapsed ~ .main .btn-show-sidebar { display: flex; }
    .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 SCREEN */
    .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;}
    @keyframes fadeSlideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    .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);
      display:flex; align-items:center; gap:8px;}
    .chip svg { width: 18px; height: 18px; color: var(--accent); }
    .chip:hover{background:var(--accent-soft);border-color:var(--accent);color:var(--accent); transform:translateY(-2px);}

    /* MESSAGES */
    .msg-row{display:flex;padding:8px 30px;gap:16px; animation: popIn 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;}
    @keyframes popIn { from { opacity: 0; transform: translateY(15px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
    .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)}
    .msg-row.user .msg-av svg { width: 20px; height: 20px; }
    
    .bubble{max-width:min(700px,80vw);padding:16px 22px;border-radius:var(--radius);
      font-size:.98rem;line-height:1.75;word-break:break-word;}
    .msg-row.bot .bubble{background:transparent;border:none;padding:8px 4px;box-shadow:none;}
    .msg-row.user .bubble{background:var(--user-bubble);border:none;}

    /* حاوية التفكير */
    .thinking-container {
      margin: 16px 0;
      padding: 16px 18px;
      background: var(--thinking-bg);
      border: 1px solid var(--thinking-border);
      border-radius: var(--radius-sm);
      border-left: 3px solid var(--pro-color);
    }
    [dir="rtl"] .thinking-container {
      border-left: 1px solid var(--thinking-border);
      border-right: 3px solid var(--pro-color);
    }
    .thinking-header {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 12px;
      color: var(--pro-color);
      font-weight: 600;
      font-size: 0.9rem;
    }
    .thinking-header svg {
      width: 18px;
      height: 18px;
      animation: pulse 1.5s ease-in-out infinite;
    }
    @keyframes pulse {
      0%, 100% { opacity: 0.6; transform: scale(1); }
      50% { opacity: 1; transform: scale(1.1); }
    }
    .thinking-content {
      color: var(--text2);
      font-size: 0.9rem;
      line-height: 1.7;
      white-space: pre-wrap;
      word-break: break-word;
    }
    .pro-response { margin-top: 8px; }

    /* CURSOR */
    .genisi-cursor { display: inline-block; width: 12px; height: 12px; margin-inline-start: 6px; background: var(--accent); border-radius: 50%; animation: blink 1s infinite; }
    @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }

    /* MARKDOWN */
    .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;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;}
    .bubble th{background:var(--surface3);font-weight:600;}

    /* Code Blocks */
    .code-container{position:relative;margin:16px 0;background:var(--surface3);border-radius:var(--radius-sm);border:1px solid var(--border);overflow:hidden;}
    .code-header{display:flex;justify-content:space-between;align-items:center;background:#12141a;padding:8px 16px;font-size:0.8rem;color:var(--text2);}
    .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);}
    .copy-btn svg { width: 14px; height: 14px; }
    .copy-btn:hover{background:var(--accent);color:#fff;}
    .code-container pre{margin:0;padding:16px;overflow-x:auto;font-family:'JetBrains Mono',monospace;font-size:0.85rem;}
    .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 */
    .katex-display{overflow-x:auto;overflow-y:hidden;padding:8px 0;}
    .katex{font-size:1.05em;}

    /* Files */
    .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 svg { width: 14px; height: 14px; }
    .file-chip button {background:none; border:none; color:var(--danger); cursor:pointer; padding:0; margin-left:4px; display: flex; align-items: center;}
    .file-chip button svg { width: 12px; height: 12px; }
    .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:12px;background:var(--surface);
      border:1px solid var(--border);border-radius:32px;padding:12px 16px;
      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);}
    
    .btn-attach{background:none; border:none; color:var(--text3); cursor:pointer; padding:6px; border-radius:50%; display:flex; align-items:center; justify-content:center;}
    .btn-attach svg { width: 22px; height: 22px; }
    .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: 6px 0;}
    .input-box textarea::placeholder{color:var(--text3)}
    
    .btn-send, .btn-stop {width:42px;height:42px; border:none;border-radius:50%;cursor:pointer;color:#fff;display:flex;align-items:center;justify-content:center;transition:all var(--tr); flex-shrink:0;}
    .btn-send {background:linear-gradient(135deg,var(--accent),var(--accent2));}
    .btn-send svg { width: 20px; height: 20px; }
    .btn-send:hover{opacity:.9;transform:scale(1.08);}
    .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 svg { width: 20px; height: 20px; }
    .btn-stop:hover {background:var(--danger); color:#fff;}

    /* MODEL SELECTOR */
    .model-selector-input { position: relative; display: flex; align-items: center; }
    .model-toggle-btn {
      display: flex; align-items: center; justify-content: center; width: 36px; height: 36px;
      background: var(--surface2); border: 1px solid var(--border); border-radius: 50%;
      cursor: pointer; transition: all var(--tr);
    }
    .model-toggle-btn:hover { background: var(--surface3); border-color: var(--accent); transform: scale(1.05); }
    .model-toggle-btn svg { width: 18px; height: 18px; }
    .model-toggle-btn.flash-active svg { color: var(--flash-color); }
    .model-toggle-btn.pro-active svg { color: var(--pro-color); }
    
    .model-dropdown-input {
      position: absolute; bottom: calc(100% + 8px); left: 0; background: var(--surface);
      border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 8px;
      min-width: 220px; box-shadow: 0 10px 40px rgba(0,0,0,0.4); z-index: 100;
      opacity: 0; visibility: hidden; transform: translateY(10px); transition: all var(--tr);
    }
    [dir="rtl"] .model-dropdown-input { left: auto; right: 0; }
    .model-dropdown-input.show { opacity: 1; visibility: visible; transform: translateY(0); }
    .model-option-input {
      display: flex; align-items: center; gap: 12px; padding: 12px 14px;
      border-radius: var(--radius-sm); cursor: pointer; transition: background var(--tr);
    }
    .model-option-input:hover { background: var(--surface2); }
    .model-option-input.active { background: var(--accent-soft); border: 1px solid var(--accent); }
    .model-option-input svg { width: 22px; height: 22px; flex-shrink: 0; }
    .model-info-input { flex: 1; }
    .model-name-input { font-weight: 600; font-size: 0.95rem; color: var(--text); display: flex; align-items: center; gap: 6px; }
    .model-desc-input { font-size: 0.75rem; color: var(--text3); margin-top: 2px; }
    .model-badge-input { padding: 2px 8px; border-radius: var(--radius-pill); font-size: 0.65rem; font-weight: 700; color: #fff; }

    /* 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;}
    .m-close svg { width: 20px; height: 20px; }
    .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;}
    .tslider::before{content:'';position:absolute;width:20px;height:20px;border-radius:50%;
      background:#fff;top:3px;left:4px;transition:all var(--tr);}
    .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;}
    .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-size:1rem;font-weight:700; display: flex; align-items: center; justify-content: center; gap: 8px;}
    .btn-save svg { width: 18px; height: 18px; }
    .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; display: flex; align-items: center; gap: 6px;}
    .btn-danger svg { width: 16px; height: 16px; }
    .btn-danger:hover{background:var(--danger); color:#fff;}

    /* RESPONSIVE */
    @media (max-width: 640px) {
      .msg-row { padding: 6px 12px; gap: 10px; }
      .bubble { max-width: 92vw; padding: 12px 14px; font-size: .93rem; }
      .topbar { height: 56px; padding: 0 14px; }
      .input-area { padding: 0 10px 18px; }
      .w-title { font-size: 1.8rem; }
      .chips { gap: 8px; }
      .chip { font-size: .82rem; padding: 8px 14px; }
    }
  </style>
</head>
<body>
<div class="app">

  <!-- SIDEBAR -->
  <aside class="sidebar collapsed" id="sidebar">
    <div class="sidebar-header">
      <div class="s-logo">
        <img src="Genisi.png" alt="Genisi"/>
        <span class="s-logo-name">Genisi AI</span>
      </div>
    </div>
    <button class="btn-new" onclick="newChat()">
      <i data-lucide="plus-circle"></i>
      <span id="i18n-new-chat">✦ 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">
      <div class="s-footer-actions">
        <button class="btn-icon" onclick="openSettings()"><i data-lucide="settings"></i></button>
        <button class="btn-icon" id="theme-btn" onclick="toggleTheme()"><i data-lucide="moon"></i></button>
      </div>
      <button class="btn-collapse-sidebar" onclick="toggleSidebar()" title="إخفاء القائمة">
        <i data-lucide="panel-left-close"></i>
      </button>
    </div>
  </aside>

  <!-- MAIN -->
  <main class="main">
    <div class="topbar">
      <button class="btn-show-sidebar" onclick="toggleSidebar()" title="إظهار القائمة">
        <i data-lucide="panel-left-open"></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="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()"><i data-lucide="paperclip"></i></button>
          
          <!-- MODEL SELECTOR -->
          <div class="model-selector-input">
            <div class="model-toggle-btn" id="model-toggle-btn" onclick="toggleModelDropdownInput(event)">
              <i id="model-icon-input" data-lucide="zap"></i>
            </div>
            <div class="model-dropdown-input" id="model-dropdown-input">
              <div class="model-option-input" data-model="flash" onclick="selectModelInput('flash', event)">
                <i data-lucide="zap" style="color: var(--flash-color);"></i>
                <div class="model-info-input">
                  <div class="model-name-input">
                    Genisi Flash
                    <span class="model-badge-input" style="background: var(--flash-color);">⚡ Fast</span>
                  </div>
                  <div class="model-desc-input">سريع، مثالي للمهام اليومية</div>
                </div>
              </div>
              <div class="model-option-input" data-model="pro" onclick="selectModelInput('pro', event)">
                <i data-lucide="brain" style="color: var(--pro-color);"></i>
                <div class="model-info-input">
                  <div class="model-name-input">
                    Genisi Pro
                    <span class="model-badge-input" style="background: var(--pro-color);">💎 Pro</span>
                  </div>
                  <div class="model-desc-input">يفكر بعمق، تحليل وإبداع</div>
                </div>
              </div>
            </div>
          </div>
          
          <textarea id="msg-input" rows="1" onkeydown="handleKey(event)" oninput="autoResize(this)" placeholder="Type a message..."></textarea>
          <button class="btn-send" id="send-btn" onclick="sendMessage()"><i data-lucide="arrow-up"></i></button>
          <button class="btn-stop" id="stop-btn" onclick="stopGeneration()" style="display:none;"><i data-lucide="square"></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"></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-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()"><i data-lucide="trash-2"></i> <span id="i18n-del-btn">Delete</span></button>
    </div>
    <button class="btn-save" onclick="closeSettings()"><i data-lucide="check"></i> <span id="i18n-save-btn">Close</span></button>
  </div>
</div>

<script>
// ═════════════════════════════════════════════════════════════
// 🌟 GENISI AI - مع دعم ديناميكي كامل لـ KaTeX
// ═════════════════════════════════════════════════════════════

// i18n
const i18n = {
  en: { 
    newChat: "New Chat", chatsLabel: "CHATS", settings: "Settings", lang: "Language", 
    dark: "Dark Mode", 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]",
    thinking: "Genisi Pro is thinking..."
  },
  ar: { 
    newChat: "محادثة جديدة", chatsLabel: "المحادثات", settings: "الإعدادات", lang: "اللغة", 
    dark: "الوضع الليلي", del: "حذف جميع المحادثات", delDesc: "لا يمكن التراجع عن هذا الإجراء", 
    delBtn: "حذف", saveBtn: "إغلاق", placeholder: "اكتب رسالتك... (Enter للإرسال)", 
    welcomeTitle: "مرحباً في Genisi", welcomeSub: "مساعدك الذكي من AnesNT — ولاية باتنة 🇩🇿", 
    c1: "ما هو الذكاء الاصطناعي؟", c2: "اكتب كود بايثون", c3: "لخص لي موضوعاً", c4: "صمم صورة بالفضاء 🚀", 
    errConnect: "خطأ في الاتصال", memBadge: "الذاكرة: {c}/{t} رسائل", stopMsg: "[تم إيقاف التوليد]",
    thinking: "Genisi Pro يفكر..."
  },
  fr: { 
    newChat: "Nouvelle Disc.", chatsLabel: "DISCUSSIONS", settings: "Paramètres", lang: "Langue", 
    dark: "Mode Sombre", 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", c4: "Créer une image 🚀", 
    errConnect: "Erreur de connexion", memBadge: "Mémoire: {c}/{t} msgs", stopMsg: "[Génération arrêtée]",
    thinking: "Genisi Pro réfléchit..."
  },
  es: { 
    newChat: "Nuevo Chat", chatsLabel: "CHATS", settings: "Ajustes", lang: "Idioma", 
    dark: "Modo Oscuro", 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]",
    thinking: "Genisi Pro está pensando..."
  }
};

let currentLang = localStorage.getItem('genisi_lang') || 'ar';
let userId = localStorage.getItem('genisi_user_id') || ('user_' + Date.now().toString(36) + Math.random().toString(36).substring(2, 6));
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 currentModel = localStorage.getItem('genisi_model') || 'flash';

// Markdown setup
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;');
  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"></i> Copy</button></div><pre><code>${escapedCode}</code></pre></div>`;
};
marked.setOptions({ renderer, breaks: true, gfm: true });

// Helper functions
const genId = () => Date.now().toString(36) + Math.random().toString(36).substring(2, 6);
const saveChats = () => localStorage.setItem('genisi_chats', JSON.stringify(chats));
const getChat = (id) => chats.find(c => c.id === (id ?? activeChatId));
const esc = (t) => String(t).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const scrollToBottom = () => { const area = document.getElementById('chat-area'); area.scrollTop = area.scrollHeight; };

// 🌟🌟🌟 دالة تصيير KaTeX يدوياً (التحسين الأساسي)
function renderMath(element) {
  if (window.renderMathInElement) {
    try {
      renderMathInElement(element, {
        delimiters: [
          {left: '$$', right: '$$', display: true},
          {left: '$', right: '$', display: false},
          {left: '\\(', right: '\\)', display: false},
          {left: '\\[', right: '\\]', display: true}
        ],
        throwOnError: false
      });
    } catch (e) {
      console.warn('KaTeX render error:', e);
    }
  }
}

// Copy code
window.copyCode = function(btn, encodedCode) {
  navigator.clipboard.writeText(decodeURIComponent(encodedCode)).then(() => {
    btn.innerHTML = '<i data-lucide="check"></i> Copied!';
    lucide.createIcons();
    setTimeout(() => { btn.innerHTML = '<i data-lucide="copy"></i> Copy'; lucide.createIcons(); }, 2000);
  });
};

// I18n
function applyI18n() {
  const t = i18n[currentLang];
  document.documentElement.dir = currentLang === 'ar' ? 'rtl' : 'ltr';
  document.documentElement.lang = currentLang;
  
  document.getElementById('i18n-new-chat').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-del-lbl').textContent = t.del;
  document.getElementById('i18n-del-desc').textContent = t.delDesc;
  document.getElementById('i18n-del-btn').textContent = t.delBtn;
  document.getElementById('i18n-save-btn').textContent = t.saveBtn;
  document.getElementById('msg-input').placeholder = t.placeholder;
  
  if(!activeChatId) renderWelcome();
  renderChatList();
  setTimeout(() => lucide.createIcons(), 10);
}

function changeLanguage(val) { currentLang = val; localStorage.setItem('genisi_lang', val); applyI18n(); }

// Theme
function applyTheme(t) {
  document.documentElement.setAttribute('data-theme', t);
  localStorage.setItem('genisi_theme', t);
  document.getElementById('theme-btn').querySelector('i').setAttribute('data-lucide', t === 'dark' ? 'moon' : 'sun');
  document.getElementById('dark-toggle').checked = t === 'dark';
  lucide.createIcons();
}
function toggleTheme() { applyTheme(document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark'); }
function applyThemeToggle() { applyTheme(document.getElementById('dark-toggle').checked ? 'dark' : 'light'); }

// Sidebar
function toggleSidebar() { 
  const sidebar = document.getElementById('sidebar');
  sidebar.classList.toggle('collapsed');
  const icon = sidebar.classList.contains('collapsed') ? 'panel-left-open' : 'panel-left-close';
  document.querySelector('.btn-collapse-sidebar i').setAttribute('data-lucide', icon);
  lucide.createIcons();
}

// Model selector
function toggleModelDropdownInput(event) {
  event.stopPropagation();
  document.getElementById('model-dropdown-input').classList.toggle('show');
}
function selectModelInput(model, event) {
  event.stopPropagation();
  currentModel = model;
  localStorage.setItem('genisi_model', model);
  
  const toggleBtn = document.getElementById('model-toggle-btn');
  const icon = document.getElementById('model-icon-input');
  toggleBtn.classList.remove('flash-active', 'pro-active');
  icon.setAttribute('data-lucide', model === 'flash' ? 'zap' : 'brain');
  toggleBtn.classList.add(model === 'flash' ? 'flash-active' : 'pro-active');
  
  document.querySelectorAll('.model-option-input').forEach(opt => {
    opt.classList.toggle('active', opt.dataset.model === model);
  });
  
  document.getElementById('model-dropdown-input').classList.remove('show');
  lucide.createIcons();
}

// Files
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();
    };
    isText ? reader.readAsText(f) : reader.readAsDataURL(f);
  }
  document.getElementById('file-input').value = '';
}
function renderFileChips() {
  const container = document.getElementById('file-chips');
  container.innerHTML = '';
  pendingFiles.forEach((f, idx) => {
    container.innerHTML += `<div class="file-chip"><i data-lucide="${f.isText ? 'file-text' : 'image'}"></i> ${f.name} <button onclick="removeFile(${idx})"><i data-lucide="x"></i></button></div>`;
  });
  lucide.createIcons();
}
function removeFile(idx) { pendingFiles.splice(idx, 1); renderFileChips(); }

// UI
function openSettings() { document.getElementById('settings-modal').classList.add('open'); document.getElementById('lang-select').value = currentLang; }
function closeSettings() { document.getElementById('settings-modal').classList.remove('open'); }

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-square"></i><span class="ct">${esc(chat.title || 'Chat')}</span><button class="del-btn" onclick="deleteChat('${chat.id}',event)"><i data-lucide="trash-2"></i></button>`;
    div.onclick = () => loadChat(chat.id);
    list.appendChild(div);
  });
  lucide.createIcons();
}

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="Genisi.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}')"><i data-lucide="brain"></i> ${t.c1}</div>
        <div class="chip" onclick="quickSend('${t.c2}')"><i data-lucide="code-2"></i> ${t.c2}</div>
        <div class="chip" onclick="quickSend('${t.c3}')"><i data-lucide="list"></i> ${t.c3}</div>
        <div class="chip" onclick="quickSend('${t.c4}')"><i data-lucide="palette"></i> ${t.c4}</div>
      </div>
    </div>`;
  lucide.createIcons();
}

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, idx) => {
    appendBubble('user', entry.user, false, entry.uiFiles);
    appendBubble('bot', entry.bot, true, null, entry.thinking);
    appendMemBadge(idx + 1, chat.history.length);
  });
  scrollToBottom();
  renderChatList();
  // 🟢 إعادة تصيير الرياضيات بعد تحميل المحادثة
  document.querySelectorAll('.bubble').forEach(bubble => renderMath(bubble));
}

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(); }

// Input
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) 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';

  if (!activeChatId) {
    activeChatId = genId();
    const title = text ? text.slice(0, 35) + '...' : (pendingFiles[0] ? pendingFiles[0].name : 'Chat');
    chats.push({ id: activeChatId, title, history: [] });
    document.getElementById('topbar-title').textContent = title;
  }

  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);
  let thinkingContainer = null, thinkingContent = null, responseContainer = null;
  let thinkingText = '', finalResponse = '', isThinkingPhase = currentModel === 'pro';
  
  if (currentModel === 'pro') {
    const t = i18n[currentLang];
    thinkingContainer = document.createElement('div');
    thinkingContainer.className = 'thinking-container';
    thinkingContainer.innerHTML = `
      <div class="thinking-header">
        <i data-lucide="brain"></i>
        <span>${t.thinking}</span>
      </div>
      <div class="thinking-content" id="thinking-content"></div>
    `;
    botContentDiv.appendChild(thinkingContainer);
    responseContainer = document.createElement('div');
    responseContainer.className = 'pro-response';
    botContentDiv.appendChild(responseContainer);
    thinkingContent = document.getElementById('thinking-content');
    lucide.createIcons();
  }

  currentAbortController = new AbortController();
  let fullResponse = "";

  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, model: currentModel 
      }),
      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;
      
      const chunk = decoder.decode(value, { stream: true });
      fullResponse += chunk;
      
      if (currentModel === 'pro') {
        const markerIndex = fullResponse.indexOf(" instant");
        
        if (markerIndex !== -1 && isThinkingPhase) {
          thinkingText = fullResponse.substring(0, markerIndex);
          finalResponse = fullResponse.substring(markerIndex + 8);
          isThinkingPhase = false;
          if (thinkingContent) thinkingContent.innerHTML = marked.parse(thinkingText);
          if (responseContainer) responseContainer.innerHTML = marked.parse(finalResponse) + '<span class="genisi-cursor"></span>';
        } else if (isThinkingPhase) {
          thinkingText = fullResponse;
          if (thinkingContent) thinkingContent.innerHTML = marked.parse(thinkingText) + '<span class="genisi-cursor"></span>';
        } else {
          finalResponse = fullResponse.substring(fullResponse.indexOf(" instant") + 8);
          if (responseContainer) responseContainer.innerHTML = marked.parse(finalResponse) + '<span class="genisi-cursor"></span>';
        }
        // 🟢 تصيير الرياضيات أثناء التدفق
        if (thinkingContainer) renderMath(thinkingContainer);
        if (responseContainer) renderMath(responseContainer);
      } else {
        botContentDiv.innerHTML = marked.parse(fullResponse) + '<span class="genisi-cursor"></span>';
        // 🟢 تصيير الرياضيات أثناء التدفق
        renderMath(botContentDiv);
      }
      
      lucide.createIcons();
      scrollToBottom();
    }

    document.querySelector('.genisi-cursor')?.remove();

    const historyEntry = { 
      user: text, bot: fullResponse, uiFiles,
      thinking: currentModel === 'pro' ? thinkingText : null
    };
    chat.history.push(historyEntry);
    saveChats();
    appendMemBadge(chat.history.length, chat.history.length);

  } catch (err) {
    if (err.name === 'AbortError') {
      botContentDiv.innerHTML = marked.parse(fullResponse) + `<br><br><span style="color:var(--text3);"><i data-lucide="ban"></i> ${i18n[currentLang].stopMsg}</span>`;
      chat.history.push({ user: text, bot: fullResponse + "\n\n*" + i18n[currentLang].stopMsg + "*", uiFiles });
      saveChats();
    } else {
      botContentDiv.innerHTML = `<span style="color:var(--danger)"><i data-lucide="alert-circle"></i> ${i18n[currentLang].errConnect}: ${err.message}</span>`;
    }
    lucide.createIcons();
    // 🟢 تصيير الرياضيات في حالة الخطأ
    renderMath(botContentDiv);
  } finally {
    isGenerating = false;
    document.getElementById('send-btn').style.display = 'flex';
    document.getElementById('stop-btn').style.display = 'none';
    renderChatList();
    scrollToBottom();
  }
}

function appendBubble(role, text, isMarkdown, filesList = [], thinkingText = null) {
  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';
  av.innerHTML = role === 'bot' ? `<img src="Genisi.png" alt="G"/>` : '<i data-lucide="user"></i>';
  
  const bub = document.createElement('div'); bub.className = 'bubble';
  if (filesList?.length) {
    filesList.forEach(name => { bub.innerHTML += `<div class="file-prev"><i data-lucide="file"></i> ${esc(name)}</div>`; });
  }

  const contentDiv = document.createElement('div');
  
  if (thinkingText) {
    const t = i18n[currentLang];
    contentDiv.innerHTML = `
      <div class="thinking-container">
        <div class="thinking-header"><i data-lucide="brain"></i><span>${t.thinking}</span></div>
        <div class="thinking-content">${marked.parse(thinkingText)}</div>
      </div>
      <div class="pro-response">${marked.parse(text.replace(thinkingText + " instant", ""))}</div>
    `;
  } else if (text) {
    const safeText = String(text);
    contentDiv.innerHTML = isMarkdown ? marked.parse(safeText) : esc(safeText).replace(/\n/g, '<br/>');
  }
  
  bub.appendChild(contentDiv);
  row.appendChild(av); row.appendChild(bub);
  area.appendChild(row);
  
  // 🟢 تصيير الرياضيات بعد إضافة الفقاعة
  renderMath(bub);
  
  scrollToBottom();
  lucide.createIcons();
  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="database"></i> ${i18n[currentLang].memBadge.replace('{c}', count).replace('{t}', total)}`;
  area.appendChild(b); scrollToBottom(); lucide.createIcons();
}

// Initialize
applyTheme(localStorage.getItem('genisi_theme') || 'dark');
document.getElementById('lang-select').value = currentLang;
applyI18n();

(function loadSavedModel() {
  const toggleBtn = document.getElementById('model-toggle-btn');
  const icon = document.getElementById('model-icon-input');
  toggleBtn.classList.remove('flash-active', 'pro-active');
  icon.setAttribute('data-lucide', currentModel === 'flash' ? 'zap' : 'brain');
  toggleBtn.classList.add(currentModel === 'flash' ? 'flash-active' : 'pro-active');
  document.querySelectorAll('.model-option-input').forEach(opt => {
    opt.classList.toggle('active', opt.dataset.model === currentModel);
  });
})();

lucide.createIcons();

document.addEventListener('click', (e) => {
  const selector = document.querySelector('.model-selector-input');
  const dropdown = document.getElementById('model-dropdown-input');
  if (selector && !selector.contains(e.target) && dropdown.classList.contains('show')) {
    dropdown.classList.remove('show');
  }
});

document.getElementById('sidebar').classList.add('collapsed');
</script>
</body>
</html>