File size: 71,813 Bytes
aafe02c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
<!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 - by Anes Kameche</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>๐Ÿค–</text></svg>">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github-dark.min.css">
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }

:root {
  --sidebar-bg: #dde3ea;
  --sidebar-hover: rgba(0,0,0,.08);
  --sidebar-active: rgba(0,0,0,.10);
  --bg: #ffffff;
  --text: #1f1f1f;
  --text2: #444746;
  --muted: #6b6f6e;
  --divider: #e3e6ea;
  --white: #fff;
  --purple: #7c3aed;
  --upgrade-bg: #f3e8ff;
  --card: #fff;
  --code-bg: #0d1117;
  --think-bg: #f5f3fb;
  --input-shadow: 0 1px 3px rgba(0,0,0,.10),0 1px 2px rgba(0,0,0,.06);
  --menu-shadow: 0 2px 6px 2px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.3);
  --sidebar-w: 268px;
  --transition: cubic-bezier(0.2,0,0,1);
  --success: #22c55e;
  --warning: #f59e0b;
  --danger: #ef4444;
}

html[data-theme="dark"] {
  --sidebar-bg: #1b1c1d;
  --sidebar-hover: rgba(255,255,255,.08);
  --sidebar-active: rgba(255,255,255,.12);
  --bg: #131314;
  --text: #e3e3e3;
  --text2: #c4c7c5;
  --muted: #9aa0a6;
  --divider: #3c4043;
  --white: #1e1f20;
  --upgrade-bg: #2d2535;
  --card: #1e1f20;
  --think-bg: #202124;
}

html, body { height: 100%; font-family: 'Inter','Cairo',sans-serif; background: var(--bg); color: var(--text); overflow: hidden; }
html[dir="rtl"] body { font-family: 'Cairo','Inter',sans-serif; }

.shell { display: flex; height: 100vh; position: relative; }

/* SIDEBAR */
.sidebar { width: var(--sidebar-w); min-width: var(--sidebar-w); background: var(--sidebar-bg); display: flex; flex-direction: column; overflow: hidden; transition: width .25s var(--transition),min-width .25s var(--transition); position: relative; z-index: 20; }
.sidebar.closed { width: 0; min-width: 0; }
.sb-head { display: flex; align-items: center; padding: 10px 8px 4px 16px; gap: 4px; height: 52px; flex-shrink: 0; }
.sb-logo { display: flex; align-items: center; gap: 9px; flex: 1; min-width: 0; text-decoration: none; }
.sb-logo img { border-radius: 50%; object-fit: cover; flex-shrink: 0; }
.sb-logo-text { font-size: 18px; font-weight: 700; color: var(--text); white-space: nowrap; }
.sb-ico-btn { width: 40px; height: 40px; border: none; background: transparent; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: var(--text2); transition: background .15s; flex-shrink: 0; }
.sb-ico-btn:hover { background: var(--sidebar-hover); }
.sb-scroll { flex: 1; overflow-y: auto; overflow-x: hidden; padding: 4px 0 8px; }
.sb-scroll::-webkit-scrollbar { width: 4px; }
.sb-scroll::-webkit-scrollbar-thumb { background: rgba(128,128,128,.4); border-radius: 2px; }
.sb-nav { padding: 4px 8px 0; }
.sb-item { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-radius: 28px; cursor: pointer; font-size: 14px; font-weight: 500; color: var(--text); white-space: nowrap; transition: background .15s; user-select: none; }
.sb-item:hover { background: var(--sidebar-hover); }
.sb-item svg { flex-shrink: 0; color: var(--text2); }
.sb-section { font-size: 11px; font-weight: 600; color: var(--muted); padding: 14px 16px 4px; letter-spacing: .6px; text-transform: uppercase; white-space: nowrap; }
.recent-wrap { padding: 0 8px; }
.recent-item { display: flex; align-items: center; padding: 8px 14px; border-radius: 28px; cursor: pointer; font-size: 13.5px; color: var(--text); white-space: nowrap; gap: 6px; transition: background .15s; }
.recent-item:hover { background: var(--sidebar-hover); }
.recent-item.active { background: var(--sidebar-active); }
.recent-item .ri-text { flex: 1; overflow: hidden; text-overflow: ellipsis; }
.recent-item .ri-more { width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; opacity: 0; transition: opacity .15s,background .15s; color: var(--text2); }
.recent-item:hover .ri-more { opacity: 1; }
.recent-item .ri-more:hover { background: rgba(128,128,128,.25); }
.sb-bottom { flex-shrink: 0; padding: 6px 8px 10px; border-top: 1px solid var(--divider); }
.sb-settings { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-radius: 28px; cursor: pointer; font-size: 14px; font-weight: 500; color: var(--text); white-space: nowrap; transition: background .15s; }
.sb-settings:hover { background: var(--sidebar-hover); }
.sb-settings svg { color: var(--text2); }
.sb-user { display: flex; align-items: center; gap: 10px; padding: 8px 14px; border-radius: 28px; cursor: pointer; transition: background .15s; }
.sb-user:hover { background: var(--sidebar-hover); }
.avatar { width: 30px; height: 30px; border-radius: 50%; background: var(--purple); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 700; flex-shrink: 0; }
.sb-user-name { font-size: 14px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.owner-tag { font-size: 11px; color: var(--muted); text-align: center; padding: 2px 0; opacity: .6; }

/* MAIN */
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; position: relative; background: var(--bg); }

/* TOPBAR */
.topbar { position: fixed; top: 0; inset-inline: 0; height: 52px; z-index: 90; display: flex; align-items: center; padding: 0 8px; background: var(--bg); border-bottom: 1px solid transparent; }
.tb-left { display: flex; align-items: center; flex: 1; }
.tb-right { display: flex; align-items: center; gap: 4px; }
.tb-btn { width: 40px; height: 40px; border: none; background: transparent; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: var(--text2); transition: background .15s; }
.tb-btn:hover { background: var(--sidebar-hover); }
.mobile-model-btn { display: none; align-items: center; gap: 3px; padding: 7px 10px; border-radius: 20px; border: none; background: transparent; font-family: inherit; font-size: 13px; color: var(--text2); font-weight: 600; cursor: pointer; white-space: nowrap; transition: background .15s; }
.mobile-model-btn:hover { background: var(--sidebar-hover); }

/* HOME */
.home { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 0 20px 80px; position: relative; overflow: hidden; }
.home::before { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-55%); width: 900px; height: 700px; background: radial-gradient(ellipse 50% 45% at 50% 50%,rgba(168,85,247,.30) 0%,rgba(168,85,247,.15) 30%,transparent 60%),radial-gradient(ellipse 40% 50% at 55% 45%,rgba(147,112,219,.18) 0%,transparent 65%),radial-gradient(ellipse 45% 40% at 45% 60%,rgba(196,124,255,.16) 0%,transparent 70%); filter: blur(90px); pointer-events: none; z-index: 0; }
.greeting { font-size: 38px; font-weight: 600; color: var(--text); margin-bottom: 28px; text-align: center; position: relative; z-index: 1; animation: greet .45s ease both; }
@keyframes greet { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: translateY(0); } }
.input-wrap { width: 100%; max-width: 720px; position: relative; z-index: 1; }
.input-stack { display: flex; flex-direction: column; width: 100%; }
.attachments { display: flex; flex-wrap: wrap; gap: 8px; padding: 0 4px 8px; }
.att-chip { display: flex; align-items: center; gap: 8px; background: var(--upgrade-bg); color: var(--purple); border-radius: 12px; padding: 6px 10px; font-size: 13px; max-width: 220px; }
.att-chip img { width: 32px; height: 32px; border-radius: 6px; object-fit: cover; flex-shrink: 0; }
.att-chip .att-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.att-chip .att-x { cursor: pointer; border: none; background: transparent; color: inherit; font-weight: 700; font-size: 16px; line-height: 1; }
.input-box { background: var(--card); border-radius: 28px; box-shadow: var(--input-shadow); display: flex; align-items: flex-end; padding: 10px 16px; gap: 4px; border: 1.5px solid var(--divider); transition: box-shadow .2s,border-color .2s; }
.input-box:focus-within { border-color: transparent; box-shadow: 0 0 28px rgba(124,58,237,.25),0 0 60px rgba(168,85,247,.12); }
.input-plus, .mic-btn { width: 36px; height: 36px; border: none; background: transparent; border-radius: 50%; cursor: pointer; flex-shrink: 0; display: flex; align-items: center; justify-content: center; color: var(--text2); transition: background .15s; }
.input-plus:hover, .mic-btn:hover { background: var(--sidebar-hover); }
.mic-btn.recording { background: #e8453c; color: #fff; }
.input-ta { flex: 1; border: none; outline: none; background: transparent; font-family: inherit; font-size: 16px; color: var(--text); line-height: 1.5; resize: none; max-height: 180px; min-height: 24px; padding: 7px 6px; scrollbar-width: none; }
.input-ta::-webkit-scrollbar { display: none; }
.input-ta::placeholder { color: var(--muted); }
.input-right { display: flex; align-items: center; gap: 2px; flex-shrink: 0; padding-bottom: 2px; }
.model-btn { display: flex; align-items: center; gap: 3px; padding: 7px 10px; border-radius: 20px; border: none; background: transparent; font-family: inherit; font-size: 14px; color: var(--text2); font-weight: 600; cursor: pointer; white-space: nowrap; transition: background .15s; }
.model-btn:hover { background: var(--sidebar-hover); }
.send-btn { width: 36px; height: 36px; border: none; background: var(--purple); border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: #fff; transition: background .15s,transform .1s; }
.send-btn:hover { background: #6d28d9; }
.send-btn:active { transform: scale(.93); }
.send-btn:disabled { background: #c4c7c5; cursor: default; }
.send-btn.stop { background: #1f1f1f; }
html[data-theme="dark"] .send-btn.stop { background: #e3e3e3; color: #1f1f1f; }

/* CHAT */
.chat-view { flex: 1; display: none; flex-direction: column; min-height: 0; padding-top: 52px; }
.shell.chat .home { display: none; }
.shell.chat .chat-view { display: flex; }
.msgs { flex: 1; overflow-y: auto; padding: 8px 0 12px; }
.msgs::-webkit-scrollbar { width: 6px; }
.msgs::-webkit-scrollbar-thumb { background: var(--divider); border-radius: 3px; }
.msgs-inner { max-width: 760px; width: 100%; margin: 0 auto; padding: 0 20px; display: flex; flex-direction: column; gap: 20px; }

/* User message */
.msg-user-wrap { display: flex; flex-direction: column; align-items: flex-end; max-width: 78%; align-self: flex-end; position: relative; }
html[dir="rtl"] .msg-user-wrap { align-items: flex-start; align-self: flex-start; }
.msg-user { background: var(--upgrade-bg); color: var(--text); padding: 12px 18px; border-radius: 20px 20px 5px 20px; font-size: 15px; line-height: 1.6; word-break: break-word; white-space: pre-wrap; width: 100%; }
html[dir="rtl"] .msg-user { border-radius: 20px 20px 20px 5px; }
.msg-user-actions { display: flex; gap: 2px; margin-top: 3px; opacity: 0; transition: opacity .15s; }
.msg-user-wrap:hover .msg-user-actions { opacity: 1; }

/* AI message */
.msg-ai { align-self: flex-start; max-width: 92%; width: 100%; position: relative; }
html[dir="rtl"] .msg-ai { align-self: flex-end; }
.msg-ai-body { font-size: 15.5px; line-height: 1.75; color: var(--text); }
.msg-ai-actions { display: flex; gap: 2px; margin-top: 3px; opacity: 0; transition: opacity .15s; }
.msg-ai:hover .msg-ai-actions { opacity: 1; }
.msg-act-btn { width: 30px; height: 30px; border: none; background: transparent; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: var(--muted); transition: background .15s,color .15s; flex-shrink: 0; }
.msg-act-btn:hover { background: var(--sidebar-hover); color: var(--text); }
.msg-act-btn.copied { color: var(--success); }

/* Markdown styles */
.msg-ai-body p { margin: 0 0 12px; }
.msg-ai-body ul, .msg-ai-body ol { margin: 0 0 12px; padding-inline-start: 24px; }
.msg-ai-body h1, .msg-ai-body h2, .msg-ai-body h3 { margin: 14px 0 8px; }
.msg-ai-body a { color: var(--purple); }
.msg-ai-body blockquote { border-inline-start: 3px solid var(--purple); padding-inline-start: 12px; color: var(--muted); margin: 0 0 12px; }
.msg-ai-body table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; border-radius: 8px; overflow: hidden; }
.msg-ai-body th, .msg-ai-body td { border: 1px solid var(--divider); padding: 8px 12px; text-align: start; }
.msg-ai-body th { background: var(--upgrade-bg); color: var(--purple); font-weight: 700; }
.msg-ai-body tr:nth-child(even) td { background: rgba(124,58,237,.04); }

/* Code */
.code-wrap { position: relative; margin: 12px 0; border-radius: 12px; overflow: hidden; border: 1px solid var(--divider); direction: ltr; }
.code-bar { display: flex; align-items: center; justify-content: space-between; background: #161b22; color: #c9d1d9; padding: 6px 12px; font-size: 12px; font-family: monospace; }
.copy-btn { background: transparent; border: 1px solid #30363d; color: #c9d1d9; border-radius: 6px; padding: 3px 10px; font-size: 12px; cursor: pointer; font-family: inherit; }
.copy-btn:hover { background: #21262d; }
.code-wrap pre { margin: 0; }
.code-wrap pre code { display: block; padding: 14px; background: var(--code-bg); overflow-x: auto; font-family: 'Consolas',monospace; font-size: 13.5px; line-height: 1.6; }

/* Dots animation */
.dots span { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin: 0 2px; background: var(--text); animation: dot 1.2s infinite; }
.dots span:nth-child(2) { animation-delay: .18s; }
.dots span:nth-child(3) { animation-delay: .36s; }
@keyframes dot { 0%,80%,100% { transform: scale(.6); opacity: .4; } 40% { transform: scale(1); opacity: 1; } }

/* Suggestions */
.suggests { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
.suggest { background: var(--card); border: 1px solid var(--divider); color: var(--text); border-radius: 18px; padding: 8px 16px; font-size: 14px; cursor: pointer; font-family: inherit; transition: background .15s; text-decoration: none; display: inline-block; }
.suggest:hover { background: var(--sidebar-hover); }

/* Chat input bar */
.chat-input-bar { padding: 10px 20px 18px; display: none; justify-content: center; flex-shrink: 0; }
.shell.chat .chat-input-bar { display: flex; }

/* Model menu */
.model-menu { position: absolute; bottom: calc(100% + 6px); inset-inline-end: 0; background: var(--card); border-radius: 14px; box-shadow: var(--menu-shadow); padding: 6px; min-width: 200px; z-index: 200; display: none; }
.model-menu.open { display: block; }
.mm-item { display: flex; flex-direction: column; padding: 10px 14px; border-radius: 10px; cursor: pointer; }
.mm-item:hover { background: var(--sidebar-hover); }
.mm-item b { font-size: 14px; }
.mm-item small { font-size: 12px; color: var(--muted); }

/* Settings */
.settings-panel { position: fixed; top: 0; inset-inline-end: 0; bottom: 0; width: 380px; max-width: 90vw; background: var(--card); box-shadow: -2px 0 10px rgba(0,0,0,.15); z-index: 100; transform: translateX(100%); transition: transform .3s var(--transition); display: flex; flex-direction: column; overflow: hidden; }
html[dir="rtl"] .settings-panel { transform: translateX(-100%); }
.settings-panel.open { transform: translateX(0) !important; }
.settings-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid var(--divider); }
.settings-title { font-size: 16px; font-weight: 700; }
.settings-close { width: 36px; height: 36px; border: none; background: transparent; border-radius: 50%; cursor: pointer; color: var(--text2); display: flex; align-items: center; justify-content: center; }
.settings-close:hover { background: var(--sidebar-hover); }
.settings-content { flex: 1; overflow-y: auto; padding: 20px; }
.settings-group { margin-bottom: 24px; }
.settings-label { font-size: 14px; font-weight: 700; margin-bottom: 12px; display: block; }
.settings-option { display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 12px; cursor: pointer; transition: background .15s; }
.settings-option:hover { background: var(--sidebar-hover); }
.settings-option input { width: 18px; height: 18px; cursor: pointer; accent-color: var(--purple); }
.option-text { font-size: 14px; flex: 1; }
.settings-divider { height: 1px; background: var(--divider); margin: 16px 0; }

/* Overlay */
.overlay { position: fixed; inset: 0; background: rgba(0,0,0,0); z-index: 50; opacity: 0; pointer-events: none; transition: opacity .3s; }
.overlay.active { opacity: 1; pointer-events: all; background: rgba(0,0,0,.4); }

/* Toast */
.toast { position: fixed; bottom: 20px; inset-inline-end: 20px; background: var(--card); color: var(--text); padding: 12px 18px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,.15); z-index: 400; font-size: 14px; display: flex; align-items: center; gap: 10px; transform: translateY(100px); opacity: 0; transition: all .3s; }
.toast.show { transform: translateY(0); opacity: 1; }
.toast.success { border-inline-start: 4px solid var(--success); }
.toast.error { border-inline-start: 4px solid var(--danger); }

/* Search pane */
.search-pane { position: absolute; inset: 0; background: var(--bg); z-index: 30; display: none; flex-direction: column; padding: 12px 60px 20px; }
.search-pane.open { display: flex; }
.sp-top { display: flex; align-items: center; gap: 12px; height: 56px; flex-shrink: 0; }
.sp-input-wrap { flex: 1; display: flex; align-items: center; gap: 10px; background: var(--card); border: 1.5px solid var(--divider); border-radius: 26px; padding: 10px 16px; box-shadow: var(--input-shadow); }
.sp-input { flex: 1; border: none; outline: none; background: transparent; font-size: 16px; font-family: inherit; color: var(--text); }
.sp-x { border: none; background: transparent; cursor: pointer; color: var(--muted); display: flex; }
.sp-sect { font-size: 12px; font-weight: 600; color: var(--muted); padding: 16px 4px 6px; text-transform: uppercase; }
.sp-results { flex: 1; overflow-y: auto; }
.sp-row { display: flex; align-items: center; gap: 14px; padding: 11px 12px; border-radius: 12px; cursor: pointer; font-size: 14px; color: var(--text); transition: background .12s; }
.sp-row:hover { background: var(--sidebar-hover); }
.sp-row .sr-text { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sp-row .sr-date { font-size: 13px; color: var(--muted); white-space: nowrap; }
.sp-row.hide { display: none; }

/* Document */
.doc-preview { border: 1px solid var(--divider); border-radius: 14px; background: #fff; padding: 28px 32px; margin: 12px 0; box-shadow: 0 2px 14px rgba(124,58,237,.08); max-height: 520px; overflow-y: auto; }
.doc-paper { font-family: 'Inter','Cairo',sans-serif; color: #1f1f1f; line-height: 1.7; }
.doc-title { font-size: 26px; font-weight: 700; color: #7c3aed; text-align: center; border-bottom: 3px solid #7c3aed; padding-bottom: 12px; margin-bottom: 18px; }
.doc-dl { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 6px 0 4px; }
.doc-dl-label { font-size: 13px; color: var(--muted); font-weight: 600; }
.doc-dl-btn { background: var(--upgrade-bg); color: var(--purple); border: 1px solid transparent; border-radius: 14px; padding: 7px 16px; font-size: 14px; font-weight: 600; cursor: pointer; font-family: inherit; transition: background .15s; }
.doc-dl-btn:hover { background: #e9d5ff; }
.doc-dl-btn:disabled { opacity: .6; cursor: default; }

/* Generated image */
.gen-img { max-width: 100%; border-radius: 14px; margin: 8px 0; display: block; }
.img-actions { display: flex; gap: 8px; margin: 4px 0 8px; }

/* Responsive */
@media (max-width: 767px) {
  .topbar { position: fixed; top: 0; left: 0; right: 0; z-index: 90; }
  .sidebar { position: fixed; top: 0; left: 0; bottom: 0; z-index: 100; box-shadow: 2px 0 10px rgba(0,0,0,.3); }
  .mobile-model-btn { display: flex; }
  .desktop-model-wrap { display: none !important; }
  .home { padding-top: 60px; }
  .chat-view { padding-top: 52px; }
  .msgs-inner { padding: 0 12px; gap: 16px; }
  .msg-user { font-size: 14px; }
  .msg-user-wrap { max-width: 85%; }
  .msg-ai-body { font-size: 14px; }
  .msg-user-actions, .msg-ai-actions { opacity: .7; }
}
</style>
</head>
<body>
<div class="shell" id="shell">
  <!-- SIDEBAR -->
  <div class="sidebar closed" id="sidebar">
    <div class="sb-head">
      <a class="sb-logo" href="#" onclick="return false;">
        <img src="https://qph.cf2.poecdn.net/main-thumb-pb-6867722-200-mqrjiwnfubtpxjfdovmmfgdaicgosphq.jpeg" alt="Genisi" width="30" height="30" onerror="this.style.display='none'">
        <span class="sb-logo-text">Genisi</span>
      </a>
      <button class="sb-ico-btn" onclick="closeSidebar()">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="3" width="18" height="18" rx="2.5"/><line x1="9" y1="3" x2="9" y2="21"/></svg>
      </button>
    </div>
    <div class="sb-scroll">
      <div class="sb-nav">
        <div class="sb-item" onclick="newChat()">
          <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
          <span data-i18n="newChat">New chat</span>
        </div>
        <div class="sb-item" onclick="openSearch()">
          <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
          <span data-i18n="searchChats">Search chats</span>
        </div>
      </div>
      <div class="sb-section" data-i18n="recent">Recent</div>
      <div class="recent-wrap" id="recentWrap"></div>
    </div>
    <div class="sb-bottom">
      <div class="sb-settings" onclick="openSettings()">
        <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
        <span data-i18n="settings">Settings</span>
      </div>
      <div class="sb-user" onclick="openHowto()">
        <div class="avatar" id="userAvatar">G</div>
        <span class="sb-user-name" id="userName">Genisi user</span>
      </div>
      <div class="owner-tag">ยฉ Anes Kameche</div>
    </div>
  </div>

  <!-- MAIN -->
  <div class="main" id="main">
    <!-- TOPBAR -->
    <div class="topbar" id="topbar">
      <div class="tb-left">
        <button class="tb-btn" onclick="openSidebar()">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="3" width="18" height="18" rx="2.5"/><line x1="9" y1="3" x2="9" y2="21"/></svg>
        </button>
        <button class="tb-btn" onclick="newChat()">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
        </button>
        <button class="tb-btn" onclick="openSearch()">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
        </button>
      </div>
      <div class="tb-right">
        <button class="mobile-model-btn" id="mobileModelBtn" onclick="toggleModelMenu(event,'mobileModelMenu')">
          <span class="modelLabel">Genisi Flash 2</span>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="6 9 12 15 18 9"/></svg>
        </button>
        <div class="model-menu" id="mobileModelMenu">
          <div class="mm-item" onclick="setModel('flash')"><b>Genisi Flash 2</b><small>Fast &amp; direct</small></div>
          <div class="mm-item" onclick="setModel('pro')"><b>Genisi Pro 2</b><small>Deep thinking</small></div>
        </div>
      </div>
    </div>

    <!-- HOME -->
    <div class="home" id="homeView">
      <h1 class="greeting" id="greeting">How can I help you?</h1>
      <div class="input-wrap">
        <div class="input-stack">
          <div class="attachments" id="homeAtts"></div>
          <div class="input-box">
            <button class="input-plus" onclick="uploadFiles()">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            </button>
            <textarea class="input-ta" id="homeTA" data-ph="askGenisi" placeholder="Ask Genisi" rows="1"
              oninput="onTaInput(this,'homeSend')" onkeydown="onTaKey(event,'home')"></textarea>
            <div class="input-right">
              <div style="position:relative" class="desktop-model-wrap">
                <button class="model-btn" onclick="toggleModelMenu(event,'modelMenuHome')">
                  <span class="modelLabel">Genisi Flash 2</span>
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="6 9 12 15 18 9"/></svg>
                </button>
                <div class="model-menu" id="modelMenuHome">
                  <div class="mm-item" onclick="setModel('flash')"><b>Genisi Flash 2</b><small>Fast &amp; smart</small></div>
                  <div class="mm-item" onclick="setModel('pro')"><b>Genisi Pro 2</b><small>Deep thinking</small></div>
                </div>
              </div>
              <button class="mic-btn" id="homeMic" onclick="toggleMic('homeTA',this)">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
              </button>
              <button class="send-btn" id="homeSend" onclick="send('home')" disabled>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="20" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- CHAT VIEW -->
    <div class="chat-view" id="chatView">
      <div class="msgs" id="msgs"><div class="msgs-inner" id="msgsInner"></div></div>
      <div class="chat-input-bar">
        <div class="input-wrap">
          <div class="input-stack">
            <div class="attachments" id="chatAtts"></div>
            <div class="input-box">
              <button class="input-plus" onclick="uploadFiles()">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
              </button>
              <textarea class="input-ta" id="chatTA" data-ph="askGenisi" placeholder="Ask Genisi" rows="1"
                oninput="onTaInput(this,'chatSend')" onkeydown="onTaKey(event,'chat')"></textarea>
              <div class="input-right">
                <div style="position:relative" class="desktop-model-wrap">
                  <button class="model-btn" onclick="toggleModelMenu(event,'modelMenuChat')">
                    <span class="modelLabel">Genisi Flash 2</span>
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="6 9 12 15 18 9"/></svg>
                  </button>
                  <div class="model-menu" id="modelMenuChat">
                    <div class="mm-item" onclick="setModel('flash')"><b>Genisi Flash 2</b><small>Fast &amp; smart</small></div>
                    <div class="mm-item" onclick="setModel('pro')"><b>Genisi Pro 2</b><small>Deep thinking</small></div>
                  </div>
                </div>
                <button class="mic-btn" id="chatMic" onclick="toggleMic('chatTA',this)">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
                </button>
                <button class="send-btn" id="chatSend" onclick="send('chat')" disabled>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="20" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- SEARCH PANE -->
    <div class="search-pane" id="searchPane">
      <div class="sp-top">
        <div class="sp-input-wrap">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
          <input class="sp-input" id="spInput" data-ph="searchChats" placeholder="Search chats" oninput="filterSP(this.value)" autocomplete="off">
          <button class="sp-x" onclick="closeSearch()">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
      </div>
      <div class="sp-sect" data-i18n="recent">Recent</div>
      <div class="sp-results" id="spResults"></div>
    </div>
  </div>

  <!-- SETTINGS PANEL -->
  <div class="settings-panel" id="settingsPanel">
    <div class="settings-header">
      <h2 class="settings-title" data-i18n="settings">Settings</h2>
      <button class="settings-close" onclick="closeSettings()">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
    </div>
    <div class="settings-content">
      <div class="settings-group">
        <label class="settings-label" data-i18n="theme">Theme</label>
        <label class="settings-option"><input type="radio" name="theme" value="light" onchange="setTheme('light')"><span class="option-text" data-i18n="light">Light</span></label>
        <label class="settings-option"><input type="radio" name="theme" value="dark" onchange="setTheme('dark')"><span class="option-text" data-i18n="dark">Dark</span></label>
        <label class="settings-option"><input type="radio" name="theme" value="auto" onchange="setTheme('auto')"><span class="option-text" data-i18n="auto">Auto</span></label>
      </div>
      <div class="settings-divider"></div>
      <div class="settings-group">
        <label class="settings-label" data-i18n="language">Language</label>
        <label class="settings-option"><input type="radio" name="lang" value="en" onchange="setLang('en')"><span class="option-text">English</span></label>
        <label class="settings-option"><input type="radio" name="lang" value="ar" onchange="setLang('ar')"><span class="option-text">ุงู„ุนุฑุจูŠุฉ</span></label>
        <label class="settings-option"><input type="radio" name="lang" value="fr" onchange="setLang('fr')"><span class="option-text">Franรงais</span></label>
      </div>
      <div class="settings-divider"></div>
      <div class="settings-group">
        <label class="settings-label" data-i18n="defaultModel">Default model</label>
        <label class="settings-option"><input type="radio" name="dmodel" value="flash" onchange="setModel('flash')"><span class="option-text">Genisi Flash 2 โšก</span></label>
        <label class="settings-option"><input type="radio" name="dmodel" value="pro" onchange="setModel('pro')"><span class="option-text">Genisi Pro 2 ๐Ÿง </span></label>
      </div>
      <div class="settings-divider"></div>
      <div class="settings-group">
        <label class="settings-label" data-i18n="voice">Voice</label>
        <label class="settings-option"><input type="checkbox" id="ttsAuto"><span class="option-text" data-i18n="autoTts">Auto-play audio</span></label>
      </div>
    </div>
  </div>

  <div class="overlay" id="overlay" onclick="closeSettings()"></div>
  <div class="toast" id="toast"></div>
</div>

<script>
// ===================== CONFIG =====================
// API base URL โ€” empty string = same origin (correct for Flask)
const API = "";

// ===================== i18n =====================
const I18N = {
  en: {
    newChat:"New chat", searchChats:"Search chats", recent:"Recent", settings:"Settings",
    askGenisi:"Ask Genisi", theme:"Theme", light:"Light", dark:"Dark", auto:"Auto",
    language:"Language", defaultModel:"Default model", voice:"Voice", autoTts:"Auto-play audio",
    howtoBtn:"How to use Genisi?", clearBtn:"Clear all chats and data",
    flashDesc:"Fast & direct", proDesc:"Deep thinking",
    welcome:"Welcome to Genisi", welcomeSub:"Let's personalize your experience.",
    name:"Name", yourName:"Your name", dob:"Date of birth", gender:"Gender",
    male:"Male", female:"Female", noSay:"Prefer not to say", confirm:"Confirm & continue",
    howtoTitle:"How to use Genisi", getStarted:"Get started",
    thinking:"Genisi Pro 2 is thinking deeply...", showThinking:"Show thinking",
    generatingImage:"Generating image...", searching:"Searching...",
    searchingImages:"Finding images...", creatingDoc:"Creating document...",
    downloadDoc:"Download as", downloadImg:"Download image", imagesLeft:"images left",
    errConnect:"Connection failed", stopped:"Response stopped",
    newConvo:"New conversation", micUnsupported:"Your browser doesn't support voice input.",
    confirmClear:"Clear all chats and data?", cutoff:"Response was too long.",
    unsupportedFile:"Unsupported file type.",
    recording:"Recording...", copied:"Copied",
    editMsg:"Edit message", copyMsg:"Copy message", copyReply:"Copy reply"
  },
  ar: {
    newChat:"ู…ุญุงุฏุซุฉ ุฌุฏูŠุฏุฉ", searchChats:"ุงู„ุจุญุซ", recent:"ุงู„ุฃุฎูŠุฑุฉ", settings:"ุงู„ุฅุนุฏุงุฏุงุช",
    askGenisi:"ุงุณุฃู„ Genisi", theme:"ุงู„ู…ุธู‡ุฑ", light:"ูุงุชุญ", dark:"ุฏุงูƒู†", auto:"ุชู„ู‚ุงุฆูŠ",
    language:"ุงู„ู„ุบุฉ", defaultModel:"ุงู„ู†ู…ูˆุฐุฌ", voice:"ุงู„ุตูˆุช", autoTts:"ุชุดุบูŠู„ ุชู„ู‚ุงุฆูŠ",
    howtoBtn:"ูƒูŠู ุชุณุชุฎุฏู… GenisiุŸ", clearBtn:"ู…ุณุญ ุงู„ุจูŠุงู†ุงุช",
    flashDesc:"ุณุฑูŠุน ูˆู…ุจุงุดุฑ", proDesc:"ุชููƒูŠุฑ ุนู…ูŠู‚",
    welcome:"ู…ุฑุญุจุงู‹ ุจูƒ ููŠ Genisi", welcomeSub:"ู„ู†ุฎุตู‘ุต ุชุฌุฑุจุชูƒ.",
    name:"ุงู„ุงุณู…", yourName:"ุงุณู…ูƒ", dob:"ุชุงุฑูŠุฎ ุงู„ู…ูŠู„ุงุฏ", gender:"ุงู„ุฌู†ุณ",
    male:"ุฐูƒุฑ", female:"ุฃู†ุซู‰", noSay:"ู„ุง ุฃูุถู„", confirm:"ุชุฃูƒูŠุฏ",
    howtoTitle:"ูƒูŠู ุชุณุชุฎุฏู… Genisi", getStarted:"ุงุจุฏุฃ",
    thinking:"Genisi Pro 2 ูŠููƒุฑ ุจุนู…ู‚...", showThinking:"ุนุฑุถ ุงู„ุชููƒูŠุฑ",
    generatingImage:"ุชูˆู„ูŠุฏ ุตูˆุฑุฉ...", searching:"ุจุญุซ...",
    searchingImages:"ุจุญุซ ุนู† ุตูˆุฑ...", creatingDoc:"ุฅู†ุดุงุก ู…ุณุชู†ุฏ...",
    downloadDoc:"ุชุญู…ูŠู„", downloadImg:"ุชุญู…ูŠู„ ุงู„ุตูˆุฑุฉ", imagesLeft:"ู…ุชุจู‚ูŠ",
    errConnect:"ุฎุทุฃ ุงุชุตุงู„", stopped:"ุชูˆู‚ู",
    newConvo:"ู…ุญุงุฏุซุฉ ุฌุฏูŠุฏุฉ", micUnsupported:"ู…ุชุตูุญูƒ ู„ุง ูŠุฏุนู… ุงู„ุตูˆุช.",
    confirmClear:"ู…ุณุญ ูƒู„ ุงู„ุจูŠุงู†ุงุชุŸ", cutoff:"ุงู„ุฑุฏ ุทูˆูŠู„.",
    unsupportedFile:"ู…ู„ู ุบูŠุฑ ู…ุฏุนูˆู….",
    recording:"ุชุณุฌูŠู„...", copied:"ุชู… ุงู„ู†ุณุฎ",
    editMsg:"ุชุนุฏูŠู„ ุงู„ุฑุณุงู„ุฉ", copyMsg:"ู†ุณุฎ ุงู„ุฑุณุงู„ุฉ", copyReply:"ู†ุณุฎ ุงู„ุฑุฏ"
  },
  fr: {
    newChat:"Nouveau", searchChats:"Rechercher", recent:"Rรฉcents", settings:"Paramรจtres",
    askGenisi:"Demandez ร  Genisi", theme:"Thรจme", light:"Clair", dark:"Sombre", auto:"Auto",
    language:"Langue", defaultModel:"Modรจle", voice:"Voix", autoTts:"Lecture auto",
    howtoBtn:"Comment utiliser?", clearBtn:"Effacer",
    flashDesc:"Rapide", proDesc:"Rรฉflexion profonde",
    welcome:"Bienvenue", welcomeSub:"Personnalisons.",
    name:"Nom", yourName:"Votre nom", dob:"Date", gender:"Genre",
    male:"Homme", female:"Femme", noSay:"Prรฉfรจre pas", confirm:"Continuer",
    howtoTitle:"Comment utiliser", getStarted:"Commencer",
    thinking:"Genisi Pro 2 rรฉflรฉchit...", showThinking:"Voir",
    generatingImage:"Gรฉnรฉration...", searching:"Recherche...",
    searchingImages:"Recherche images...", creatingDoc:"Crรฉation...",
    downloadDoc:"Tรฉlรฉcharger", downloadImg:"Tรฉlรฉcharger", imagesLeft:"restants",
    errConnect:"Erreur", stopped:"Arrรชtรฉ",
    newConvo:"Nouveau", micUnsupported:"Non supportรฉ.",
    confirmClear:"Effacer?", cutoff:"Trop long.",
    unsupportedFile:"Fichier non supportรฉ.",
    recording:"Enregistrement...", copied:"Copiรฉ",
    editMsg:"Modifier le message", copyMsg:"Copier le message", copyReply:"Copier la rรฉponse"
  }
};

const t = k => (I18N[state.settings.lang] || I18N.en)[k] || I18N.en[k] || k;

// ===================== STATE =====================
let state = {
  user: JSON.parse(localStorage.getItem("genisi_user") || "null"),
  settings: JSON.parse(localStorage.getItem("genisi_settings") || '{"theme":"light","lang":"en","model":"flash","ttsAuto":false}'),
  sessions: JSON.parse(localStorage.getItem("genisi_sessions") || "[]"),
  interests: JSON.parse(localStorage.getItem("genisi_interests") || "[]"),
  currentId: null,
  busy: false,
  abort: null,
};

let clientId = localStorage.getItem("genisi_client") || (Date.now() + "-" + Math.random().toString(36).slice(2));
localStorage.setItem("genisi_client", clientId);

let pendingAttachments = [];

const save = () => {
  localStorage.setItem("genisi_user", JSON.stringify(state.user));
  localStorage.setItem("genisi_settings", JSON.stringify(state.settings));
  localStorage.setItem("genisi_sessions", JSON.stringify(state.sessions));
  localStorage.setItem("genisi_interests", JSON.stringify(state.interests));
};

const $ = s => document.querySelector(s);
const cur = () => state.sessions.find(s => s.id === state.currentId);

// ===================== INIT =====================
function init() {
  applyTheme();
  applyLang();

  document.querySelectorAll('input[name="theme"]').forEach(r => r.checked = r.value === state.settings.theme);
  document.querySelectorAll('input[name="lang"]').forEach(r => r.checked = r.value === state.settings.lang);
  document.querySelectorAll('input[name="dmodel"]').forEach(r => r.checked = r.value === state.settings.model);

  const ttsEl = $("#ttsAuto");
  if (ttsEl) ttsEl.checked = !!state.settings.ttsAuto;

  setModel(state.settings.model, true);
  buildRecents();

  if (state.user) refreshUserUI();

  // Configure marked
  marked.use({
    gfm: true,
    breaks: true,
  });
}

// ===================== LANGUAGE & THEME =====================
function applyLang() {
  const l = state.settings.lang;
  const rtl = l === "ar";
  document.documentElement.lang = l;
  document.documentElement.dir = rtl ? "rtl" : "ltr";

  document.querySelectorAll("[data-i18n]").forEach(el => {
    const k = el.getAttribute("data-i18n");
    el.textContent = t(k);
  });

  document.querySelectorAll("[data-ph]").forEach(el => {
    el.placeholder = t(el.getAttribute("data-ph"));
  });

  $("#greeting").textContent = greetText();
}

function setLang(l) {
  state.settings.lang = l;
  save();
  applyLang();
}

function greetText() {
  const n = state.user?.name || "";
  const l = state.settings.lang;
  if (l === "ar") return `ูƒูŠู ูŠู…ูƒู†ู†ูŠ ู…ุณุงุนุฏุชูƒ${n ? "ุŒ " + n : ""}ุŸ`;
  if (l === "fr") return `Comment puis-je vous aider${n ? ", " + n : ""} ?`;
  return `How can I help you${n ? ", " + n : ""}?`;
}

function setTheme(th) {
  state.settings.theme = th;
  save();
  applyTheme();
}

function applyTheme() {
  let th = state.settings.theme;
  if (th === "auto") th = matchMedia("(prefers-color-scheme:dark)").matches ? "dark" : "light";
  document.documentElement.setAttribute("data-theme", th);
}

function refreshUserUI() {
  if (state.user && state.user.name) {
    $("#userAvatar").textContent = state.user.name[0].toUpperCase();
    $("#userName").textContent = state.user.name;
  }
}

// ===================== SIDEBAR =====================
function closeSidebar() { $("#sidebar").classList.add("closed"); }
function openSidebar() { $("#sidebar").classList.remove("closed"); }

// ===================== SETTINGS =====================
function openSettings() {
  $("#settingsPanel").classList.add("open");
  $("#overlay").classList.add("active");
}

function closeSettings() {
  $("#settingsPanel").classList.remove("open");
  $("#overlay").classList.remove("active");
}

// ===================== SEARCH =====================
function openSearch() {
  $("#searchPane").classList.add("open");
  buildSP();
  setTimeout(() => $("#spInput").focus(), 50);
}

function closeSearch() {
  $("#searchPane").classList.remove("open");
  $("#spInput").value = "";
}

// ===================== MODEL MENU =====================
function toggleModelMenu(e, id) {
  e.stopPropagation();
  document.querySelectorAll(".model-menu").forEach(m => {
    if (m.id !== id) m.classList.remove("open");
  });
  $("#" + id).classList.toggle("open");
}

document.addEventListener("click", () => {
  document.querySelectorAll(".model-menu").forEach(m => m.classList.remove("open"));
});

function setModel(m, silent) {
  state.settings.model = m;
  save();
  const label = m === "flash" ? "Genisi Flash 2 โšก" : "Genisi Pro 2 ๐Ÿง ";
  document.querySelectorAll(".modelLabel").forEach(e => e.textContent = label);
  document.querySelectorAll('input[name="dmodel"]').forEach(r => r.checked = r.value === m);
  if (!silent) document.querySelectorAll(".model-menu").forEach(mm => mm.classList.remove("open"));
}

// ===================== CHAT MANAGEMENT =====================
function newChat() {
  state.currentId = null;
  $("#shell").classList.remove("chat");
  $("#msgsInner").innerHTML = "";
  $("#homeTA").value = "";
  $("#homeSend").disabled = true;
  clearAttachments();
  $("#greeting").textContent = greetText();
  buildRecents();
  closeSearch();
}

function buildRecents() {
  $("#recentWrap").innerHTML = state.sessions.map(s =>
    `<div class="recent-item ${s.id === state.currentId ? 'active' : ''}" onclick="loadSession('${s.id}')">
      <span class="ri-text">${escapeHtml(s.title || t("newConvo"))}</span>
      <span class="ri-more" onclick="event.stopPropagation();deleteSession('${s.id}')">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
      </span>
    </div>`
  ).join("");
}

function buildSP() {
  $("#spResults").innerHTML = state.sessions.map(s =>
    `<div class="sp-row" data-t="${escapeHtml((s.title||'').toLowerCase())}" onclick="loadSession('${s.id}');closeSearch();">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
      <span class="sr-text">${escapeHtml(s.title || t("newConvo"))}</span>
      <span class="sr-date">${s.date || ""}</span>
    </div>`
  ).join("");
}

function filterSP(q) {
  q = q.toLowerCase();
  document.querySelectorAll("#spResults .sp-row").forEach(r => {
    r.classList.toggle("hide", !!(q && !r.dataset.t.includes(q)));
  });
}

function deleteSession(id) {
  state.sessions = state.sessions.filter(s => s.id !== id);
  if (state.currentId === id) newChat();
  save();
  buildRecents();
}

function loadSession(id) {
  state.currentId = id;
  const s = cur();
  if (!s) return;
  $("#shell").classList.add("chat");
  $("#msgsInner").innerHTML = "";
  s.messages.forEach((m, i) => {
    if (m.role === "user") addUser(m.content, m.attachments, i);
    else addAI(m.content, false, i);
  });
  buildRecents();
  renderMathAll();
  scrollDown();
}

// ===================== TEXTAREA =====================
function onTaInput(el, sendId) {
  el.style.height = "auto";
  el.style.height = Math.min(el.scrollHeight, 180) + "px";
  if (!state.busy) {
    const btn = $("#" + sendId);
    if (btn) btn.disabled = !el.value.trim();
  }
}

function onTaKey(e, mode) {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    send(mode);
  }
}

// ===================== FILE UPLOAD =====================
function uploadFiles() {
  const model = state.settings.model;
  const input = document.createElement("input");
  input.type = "file";
  input.multiple = true;

  // Build accepted types
  const CAPS_CLIENT = {
    flash: { docExts: ["pdf","docx","txt","md","csv","json","js","ts","py","html","css","java","c","cpp"] },
    pro: { docExts: ["pdf","docx","txt","md","csv","json","js","ts","py","html","css","java","c","cpp"] },
  };
  const caps = CAPS_CLIENT[model] || CAPS_CLIENT.flash;
  input.accept = caps.docExts.map(e => "." + e).join(",");

  input.onchange = async e => {
    for (const f of e.target.files) {
      await doUpload(f, model);
    }
    renderAttachments();
  };
  input.click();
}

async function doUpload(file, model) {
  const fd = new FormData();
  fd.append("file", file);
  fd.append("model", model);
  try {
    const r = await fetch(API + "/api/upload", { method: "POST", body: fd });
    const j = await r.json();
    if (!r.ok) {
      showToast(j.message || t("unsupportedFile"), "error");
      return;
    }
    if (j.kind === "image") {
      pendingAttachments.push({ kind: "image", name: j.name, dataUrl: j.dataUrl });
    } else {
      pendingAttachments.push({ kind: "text", name: j.name, text: j.text });
    }
  } catch (err) {
    showToast(t("unsupportedFile"), "error");
  }
}

function attChipHtml(a, idx) {
  const icon = a.kind === "image"
    ? `<img src="${a.dataUrl}" alt="">`
    : `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`;
  const x = idx !== undefined
    ? `<button class="att-x" onclick="removeAttachment(${idx})">ร—</button>`
    : "";
  return `<div class="att-chip">${icon}<span class="att-name">${escapeHtml(a.name)}</span>${x}</div>`;
}

function renderAttachments() {
  [$("#homeAtts"), $("#chatAtts")].forEach(w => {
    if (w) w.innerHTML = pendingAttachments.map((a, i) => attChipHtml(a, i)).join("");
  });
}

function removeAttachment(i) {
  pendingAttachments.splice(i, 1);
  renderAttachments();
}

function clearAttachments() {
  pendingAttachments = [];
  renderAttachments();
}

// ===================== HELPERS =====================
function escapeHtml(s) {
  return (s || "").replace(/[&<>"']/g, c => ({
    "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":'&#39;'
  }[c]));
}

function openHowto() {
  // Simplified - could open a modal
  showToast("Genisi AI by Anes Kameche (AnesNT Project)", "success");
}

// ===================== MESSAGE RENDERING =====================
function addUser(text, atts, msgIndex) {
  const wrap = document.createElement("div");
  wrap.className = "msg-user-wrap";
  if (msgIndex !== undefined) wrap.setAttribute("data-msg-index", msgIndex);

  const bubble = document.createElement("div");
  bubble.className = "msg-user";

  if (atts && atts.length) {
    const box = document.createElement("div");
    box.className = "attachments";
    box.style.padding = "0 0 8px";
    box.innerHTML = atts.map(a => attChipHtml(a)).join("");
    bubble.appendChild(box);
  }

  const tx = document.createElement("div");
  tx.className = "msg-user-text";
  tx.textContent = text;
  bubble.appendChild(tx);
  wrap.appendChild(bubble);

  // Action buttons
  const actions = document.createElement("div");
  actions.className = "msg-user-actions";
  actions.innerHTML = `
    <button class="msg-act-btn" title="${t('copyMsg')}" onclick="copyUserMessage(this)">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
    </button>
    <button class="msg-act-btn" title="${t('editMsg')}" onclick="editUserMessage(this)">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
    </button>`;
  wrap.appendChild(actions);

  $("#msgsInner").appendChild(wrap);
  scrollDown();
  return wrap;
}

function copyUserMessage(btn) {
  const wrap = btn.closest(".msg-user-wrap");
  const textEl = wrap.querySelector(".msg-user-text");
  const text = textEl ? textEl.textContent : "";
  navigator.clipboard.writeText(text).then(() => {
    btn.classList.add("copied");
    showToast(t("copied"), "success");
    setTimeout(() => btn.classList.remove("copied"), 1500);
  }).catch(() => showToast("Failed to copy", "error"));
}

function editUserMessage(btn) {
  const wrap = btn.closest(".msg-user-wrap");
  const textEl = wrap.querySelector(".msg-user-text");
  const text = textEl ? textEl.textContent : "";
  const msgIndexStr = wrap.getAttribute("data-msg-index");
  const msgIndex = msgIndexStr !== null ? parseInt(msgIndexStr) : null;
  const s = cur();

  // Truncate session messages up to this point
  if (s && msgIndex !== null && msgIndex >= 0) {
    s.messages = s.messages.slice(0, msgIndex);
    save();
  }

  // Remove DOM elements from this message onward
  let el = wrap;
  while (el) {
    const next = el.nextElementSibling;
    el.remove();
    el = next;
  }

  // Populate chat textarea
  const ta = $("#chatTA");
  if (ta) {
    ta.value = text;
    ta.style.height = "auto";
    ta.style.height = Math.min(ta.scrollHeight, 180) + "px";
    const sendBtn = $("#chatSend");
    if (sendBtn) sendBtn.disabled = !ta.value.trim();
    ta.focus();
    ta.setSelectionRange(ta.value.length, ta.value.length);
  }

  // Go back to home if no messages left
  if (s && s.messages.length === 0) {
    newChat();
  }

  buildRecents();
}

function addAI(md, skipRender, msgIndex) {
  const wrap = document.createElement("div");
  wrap.className = "msg-ai";
  if (msgIndex !== undefined) wrap.setAttribute("data-msg-index", msgIndex);

  const body = document.createElement("div");
  body.className = "msg-ai-body";
  wrap.appendChild(body);

  if (md !== undefined && !skipRender) {
    renderInto(body, md);
  }

  const actions = document.createElement("div");
  actions.className = "msg-ai-actions";
  actions.innerHTML = `
    <button class="msg-act-btn" title="${t('copyReply')}" onclick="copyAIReply(this)">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
    </button>`;
  wrap.appendChild(actions);

  $("#msgsInner").appendChild(wrap);
  if (md !== undefined && !skipRender) scrollDown();
  return { wrap, body };
}

function copyAIReply(btn) {
  const wrap = btn.closest(".msg-ai");
  const body = wrap ? wrap.querySelector(".msg-ai-body") : null;
  const text = body ? body.innerText : "";
  navigator.clipboard.writeText(text).then(() => {
    btn.classList.add("copied");
    showToast(t("copied"), "success");
    setTimeout(() => btn.classList.remove("copied"), 1500);
  }).catch(() => showToast("Failed to copy", "error"));
}

// ===================== RENDER =====================
function renderInto(body, md) {
  const cleaned = cleanForRender(md || "");
  body.innerHTML = marked.parse(cleaned);
  enhanceCode(body);
  renderMath(body);
}

function cleanForRender(text) {
  if (!text) return "";
  let out = text;

  // Remove tool JSON objects
  out = out.replace(/\{[^{}]*"tool"\s*:[^{}]*\}/gs, "");

  // Remove JSON code blocks with tool
  out = out.replace(/```(?:json)?\s*\{[\s\S]*?"tool"[\s\S]*?\}\s*```/g, "");

  // Remove SUGGESTIONS block
  out = out.replace(/\nSUGGESTIONS:\s*\[[\s\S]*?\]\s*$/m, "");
  out = out.replace(/SUGGESTIONS:\s*\[[\s\S]*?\]\s*$/m, "");

  return out.trim();
}

function extractSuggestions(text) {
  const m = text.match(/SUGGESTIONS:\s*(\[[\s\S]*?\])/);
  if (!m) return [];
  try {
    const arr = JSON.parse(m[1]);
    return Array.isArray(arr) ? arr.slice(0, 4) : [];
  } catch (e) {
    return [];
  }
}

function enhanceCode(scope) {
  scope.querySelectorAll("pre code").forEach(code => {
    if (code.dataset.done) return;
    code.dataset.done = "1";
    const pre = code.parentElement;
    const lang = (code.className.match(/language-(\w+)/) || [])[1] || "code";

    const wrap = document.createElement("div");
    wrap.className = "code-wrap";

    const bar = document.createElement("div");
    bar.className = "code-bar";

    const langSpan = document.createElement("span");
    langSpan.textContent = lang;
    bar.appendChild(langSpan);

    const btn = document.createElement("button");
    btn.className = "copy-btn";
    btn.textContent = "Copy";
    btn.onclick = () => {
      navigator.clipboard.writeText(code.innerText).then(() => {
        btn.textContent = "Copied!";
        setTimeout(() => btn.textContent = "Copy", 1500);
      });
    };
    bar.appendChild(btn);

    pre.parentNode.insertBefore(wrap, pre);
    wrap.appendChild(bar);
    wrap.appendChild(pre);

    try { hljs.highlightElement(code); } catch (e) {}
  });
}

function renderMath(scope) {
  if (window.renderMathInElement) {
    try {
      renderMathInElement(scope, {
        delimiters: [
          { left: "$$", right: "$$", display: true },
          { left: "\\[", right: "\\]", display: true },
          { left: "\\(", right: "\\)", display: false },
          { left: "$", right: "$", display: false }
        ],
        throwOnError: false
      });
    } catch (e) {}
  }
}

function renderMathAll() {
  document.querySelectorAll(".msg-ai-body").forEach(renderMath);
}

function scrollDown() {
  const m = $("#msgs");
  if (m) m.scrollTop = m.scrollHeight;
}

// ===================== SEND BUTTON STATE =====================
function setSendButtons(stop) {
  [["#homeSend","home"],["#chatSend","chat"]].forEach(([sel, mode]) => {
    const b = $(sel);
    if (!b) return;
    if (stop) {
      b.classList.add("stop");
      b.disabled = false;
      b.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="5" width="14" height="14" rx="2"/></svg>`;
      b.onclick = stopResponse;
    } else {
      b.classList.remove("stop");
      b.innerHTML = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="20" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg>`;
      b.onclick = () => send(mode);
    }
  });
}

function stopResponse() {
  if (state.abort) state.abort.abort();
}

// ===================== SSE PARSER =====================
/**
 * Properly parse SSE stream.
 * SSE format: each event ends with double newline (\n\n)
 * Each line can be: "data: ...", "event: ...", etc.
 */
function parseSSEChunk(buf) {
  const events = [];
  // Split on double newline (event separator)
  const rawEvents = buf.split(/\n\n/);
  const remaining = rawEvents.pop(); // Last might be incomplete
  
  for (const rawEvent of rawEvents) {
    const lines = rawEvent.split(/\n/);
    let data = null;
    for (const line of lines) {
      if (line.startsWith("data: ")) {
        data = line.slice(6).trim();
      }
    }
    if (data && data !== "[DONE]") {
      events.push(data);
    }
  }
  
  return { events, remaining };
}

// ===================== MAIN SEND =====================
async function send(mode) {
  const ta = mode === "home" ? $("#homeTA") : $("#chatTA");
  const text = (ta ? ta.value : "").trim();

  if ((!text && !pendingAttachments.length) || state.busy) return;

  // Create session if needed
  if (!state.currentId) {
    const id = Date.now() + "-" + Math.random().toString(36).slice(2);
    state.sessions.unshift({
      id,
      title: "",
      date: new Date().toLocaleDateString(),
      messages: []
    });
    state.currentId = id;
  }

  const s = cur();
  if (!s) return;

  // Switch to chat view
  $("#shell").classList.add("chat");

  // If transitioning from home, render existing messages
  if (mode === "home" && $("#msgsInner").children.length === 0) {
    s.messages.forEach((m, i) => {
      if (m.role === "user") addUser(m.content, m.attachments, i);
      else addAI(m.content, false, i);
    });
  }

  // Clear input
  if (ta) {
    ta.value = "";
    ta.style.height = "auto";
  }

  // Prepare attachments & message
  const atts = pendingAttachments.slice();
  const userMsgIndex = s.messages.length;

  // Build content with attachments
  let userContent = text;
  if (atts.length) {
    const textAtts = atts.filter(a => a.kind === "text");
    if (textAtts.length) {
      userContent += "\n\n" + textAtts.map(a => `[File: ${a.name}]\n${a.text}`).join("\n\n");
    }
  }

  s.messages.push({ role: "user", content: userContent, attachments: atts });
  addUser(text, atts, userMsgIndex);
  clearAttachments();
  buildRecents();

  // Add AI response placeholder
  const aiMsgIndex = s.messages.length;
  const { wrap, body } = addAI(undefined, true, aiMsgIndex);

  const answer = document.createElement("div");
  answer.innerHTML = `<div class="dots"><span></span><span></span><span></span></div>`;
  body.appendChild(answer);

  state.busy = true;
  setSendButtons(true);
  state.abort = new AbortController();

  let full = "";
  let rafPending = false;

  const paint = () => {
    rafPending = false;
    const cleaned = cleanForRender(full);
    answer.innerHTML = marked.parse(cleaned);
    enhanceCode(answer);
    renderMath(answer);
    scrollDown();
  };

  try {
    const res = await fetch(API + "/api/chat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      signal: state.abort.signal,
      body: JSON.stringify({
        messages: s.messages,
        model: state.settings.model,
        user: state.user || {},
        interests: state.interests,
        think: state.settings.model === "pro"
      })
    });

    if (!res.ok) {
      const errText = await res.text();
      throw new Error(`HTTP ${res.status}: ${errText.slice(0, 200)}`);
    }

    const reader = res.body.getReader();
    const dec = new TextDecoder();
    let buf = "";

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;

      buf += dec.decode(value, { stream: true });
      
      // Parse SSE properly
      const { events, remaining } = parseSSEChunk(buf);
      buf = remaining;

      for (const dataStr of events) {
        let j;
        try {
          j = JSON.parse(dataStr);
        } catch (e) {
          continue;
        }

        if (j.error) {
          answer.innerHTML = `<p style="color:var(--danger)">${escapeHtml(j.error)}</p>`;
          continue;
        }

        if (j.done) continue;

        // Handle image tool signal from backend
        if (j.tool === "image" && j.prompt) {
          const imgNode = document.createElement("p");
          imgNode.textContent = t("generatingImage");
          answer.appendChild(imgNode);
          generateImage(j.prompt, imgNode);
          continue;
        }

        if (j.delta) {
          full += j.delta;
          if (!rafPending) {
            rafPending = true;
            requestAnimationFrame(paint);
          }
        }
      }
    }

    // Final render
    const cleaned = cleanForRender(full);
    answer.innerHTML = marked.parse(cleaned);
    enhanceCode(answer);
    renderMath(answer);

    // Handle suggestions
    const sugg = extractSuggestions(full);
    if (sugg.length) renderSuggestions(answer, sugg);

    // Save to session
    s.messages.push({ role: "assistant", content: full });

    // Auto TTS
    if (state.settings.ttsAuto) speak(stripForTTS(full));

    // Generate title
    maybeTitle(s);

    // Learn user interests
    learnInterests(text);

    save();
    buildRecents();

  } catch (err) {
    if (err.name === "AbortError") {
      const cleaned = cleanForRender(full);
      answer.innerHTML = full.trim()
        ? marked.parse(cleaned)
        : `<p style="color:var(--muted)">${t("stopped")}</p>`;
      enhanceCode(answer);
      renderMath(answer);
      if (full.trim()) {
        s.messages.push({ role: "assistant", content: full });
      }
      maybeTitle(s);
      save();
      buildRecents();
    } else {
      console.error("[send]", err);
      answer.innerHTML = `<p style="color:var(--danger)">${t("errConnect")}: ${escapeHtml(String(err.message || err))}</p>`;
    }
  } finally {
    state.busy = false;
    state.abort = null;
    setSendButtons(false);
    // Disable send buttons (no text)
    const hBtn = $("#homeSend");
    const cBtn = $("#chatSend");
    if (hBtn) hBtn.disabled = true;
    if (cBtn) cBtn.disabled = true;
  }
}

// ===================== IMAGE GENERATION =====================
async function generateImage(prompt, placeholder) {
  try {
    const r = await fetch(API + "/api/image", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ prompt, clientId })
    });
    const j = await r.json();
    if (j.image) {
      const fname = "genisi-" + Date.now() + ".png";
      const container = document.createElement("div");
      container.innerHTML = `
        <img class="gen-img" src="${j.image}" alt="Generated image">
        <div class="img-actions">
          <button class="suggest" onclick="downloadDataUrl('${j.image}','${fname}')">${t("downloadImg")}</button>
        </div>
        <p style="color:var(--muted);font-size:13px">${j.remaining ?? 0} ${t("imagesLeft")}</p>`;
      placeholder.replaceWith(container);
      showToast("Image generated!", "success");
    } else {
      placeholder.textContent = j.message || "Image generation failed";
      showToast(j.message || "Failed", "error");
    }
  } catch (e) {
    placeholder.textContent = "Image generation error";
    showToast("Image generation failed", "error");
  }
}

// ===================== DOCUMENT TOOLS =====================
function renderDocPreview(cmd, scope) {
  const wrap = document.createElement("div");
  wrap.className = "doc-preview";
  wrap.innerHTML = docToHtml(cmd);
  scope.appendChild(wrap);

  const bar = document.createElement("div");
  bar.className = "doc-dl";
  bar.innerHTML = `<span class="doc-dl-label">${t("downloadDoc")}:</span>`;

  [["pdf","PDF"],["docx","Word"],["pptx","PowerPoint"],["xlsx","Excel"]].forEach(([fmt, label]) => {
    const b = document.createElement("button");
    b.className = "doc-dl-btn";
    b.textContent = label;
    b.onclick = () => downloadDoc({ ...cmd, format: fmt }, b);
    bar.appendChild(b);
  });
  scope.appendChild(bar);
}

function docToHtml(cmd) {
  const c = cmd.content || {};
  const esc = escapeHtml;
  const blocks = [];

  if (c.heading) blocks.push(`<h2>${esc(c.heading)}</h2>`);
  (c.paragraphs || []).forEach(p => blocks.push(`<p>${esc(as_text_js(p))}</p>`));
  (c.sections || []).forEach(s => {
    if (s.title) blocks.push(`<h3>${esc(s.title)}</h3>`);
    const b = s.body || s.content || s.text;
    if (b) blocks.push(`<p>${esc(as_text_js(b))}</p>`);
    (s.bullets || s.points || []).forEach(x => blocks.push(`<li>${esc(as_text_js(x))}</li>`));
  });
  if (c.headers) {
    blocks.push(`<table><thead><tr>${c.headers.map(h => `<th>${esc(as_text_js(h))}</th>`).join("")}</tr></thead><tbody>${(c.rows||[]).map(r => `<tr>${r.map(x => `<td>${esc(as_text_js(x))}</td>`).join("")}</tr>`).join("")}</tbody></table>`);
  }

  return `<div class="doc-paper"><h1 class="doc-title">${esc(cmd.title||"Document")}</h1>${blocks.join("")}</div>`;
}

function as_text_js(v) {
  if (v == null) return "";
  if (typeof v === "string") return v;
  if (Array.isArray(v)) return v.map(as_text_js).join("\n");
  if (typeof v === "object") return v.text || v.body || v.content || "";
  return String(v);
}

function renderSuggestions(scope, list) {
  const box = document.createElement("div");
  box.className = "suggests";
  list.forEach(txt => {
    const b = document.createElement("button");
    b.className = "suggest";
    b.textContent = txt;
    b.onclick = () => {
      const ta = $("#chatTA");
      if (ta) {
        ta.value = txt;
        onTaInput(ta, "chatSend");
        send("chat");
      }
    };
    box.appendChild(b);
  });
  scope.appendChild(box);
}

async function downloadDoc(cmd, btn) {
  const old = btn.textContent;
  btn.textContent = "...";
  btn.disabled = true;
  try {
    const r = await fetch(API + "/api/document", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(cmd)
    });
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    const blob = await r.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = (cmd.title || "genisi") + "." + cmd.format;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
    showToast(`${cmd.format.toUpperCase()} downloaded!`, "success");
  } catch (e) {
    showToast("Download error", "error");
  } finally {
    btn.textContent = old;
    btn.disabled = false;
  }
}

function downloadDataUrl(dataUrl, filename) {
  const a = document.createElement("a");
  a.href = dataUrl;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();
}

// ===================== TITLE GENERATION =====================
function maybeTitle(s) {
  const userCount = s.messages.filter(m => m.role === "user").length;
  if (userCount !== 1 && userCount !== 3) return;

  fetch(API + "/api/title", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ messages: s.messages })
  })
  .then(r => r.json())
  .then(j => {
    if (j.title) {
      s.title = j.title;
      save();
      buildRecents();
    }
  })
  .catch(() => {});
}

// ===================== INTERESTS LEARNING =====================
function learnInterests(text) {
  const words = (text || "").toLowerCase().match(/[\u0600-\u06FF\w]{4,}/g) || [];
  const stopWords = new Set(["this","that","with","please","about","what","when","where","how","ู‡ุฐุง","ู‡ุฐู‡","ุงู„ุชูŠ","ุงู„ุฐูŠ","ูƒูŠู","ู‡ู„","ู…ู†"]);
  words
    .filter(w => !stopWords.has(w))
    .slice(0, 3)
    .forEach(w => {
      if (!state.interests.includes(w)) state.interests.push(w);
    });
  state.interests = state.interests.slice(-30);
  save();
}

// ===================== TTS =====================
function stripForTTS(text) {
  return text
    .replace(/```[\s\S]*?```/g, "")
    .replace(/\{[\s\S]*?\}/g, "")
    .replace(/SUGGESTIONS:[\s\S]*$/, "")
    .replace(/[#*_`]/g, "")
    .trim();
}

async function speak(text) {
  if (!text.trim()) return;
  try {
    const r = await fetch(API + "/api/tts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text })
    });
    if (!r.ok || r.status === 204) throw new Error("TTS unavailable");
    const blob = await r.blob();
    new Audio(URL.createObjectURL(blob)).play();
  } catch (e) {
    // Fallback to browser TTS
    if (window.speechSynthesis) {
      const utt = new SpeechSynthesisUtterance(text);
      utt.lang = state.settings.lang === "ar" ? "ar-SA" : state.settings.lang === "fr" ? "fr-FR" : "en-US";
      speechSynthesis.speak(utt);
    }
  }
}

// ===================== MIC =====================
let recog = null;

function toggleMic(taId, btn) {
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
  if (!SR) {
    showToast(t("micUnsupported"), "error");
    return;
  }

  if (recog) {
    recog.stop();
    recog = null;
    btn.classList.remove("recording");
    return;
  }

  recog = new SR();
  recog.lang = state.settings.lang === "ar" ? "ar-SA" : state.settings.lang === "fr" ? "fr-FR" : "en-US";
  recog.continuous = false;
  recog.interimResults = true;

  btn.classList.add("recording");
  const base = ($("#" + taId) || {}).value || "";

  recog.onresult = e => {
    let tx = "";
    for (const r of e.results) tx += r[0].transcript;
    const ta = $("#" + taId);
    if (ta) {
      ta.value = (base ? base + " " : "") + tx;
      onTaInput(ta, taId === "homeTA" ? "homeSend" : "chatSend");
    }
  };

  recog.onend = () => {
    btn.classList.remove("recording");
    recog = null;
  };

  recog.onerror = () => {
    btn.classList.remove("recording");
    recog = null;
  };

  recog.start();
}

// ===================== CLEAR ALL =====================
function clearAll() {
  if (confirm(t("confirmClear"))) {
    localStorage.clear();
    location.reload();
  }
}

// ===================== TOAST =====================
function showToast(msg, type = "success") {
  const toast = $("#toast");
  if (!toast) return;
  toast.textContent = msg;
  toast.className = `toast ${type} show`;
  setTimeout(() => toast.classList.remove("show"), 3000);
}

// ===================== EVENT LISTENERS =====================
const ttsEl = $("#ttsAuto");
if (ttsEl) {
  ttsEl.addEventListener("change", e => {
    state.settings.ttsAuto = e.target.checked;
    save();
  });
}

// Auto theme on system change
matchMedia("(prefers-color-scheme:dark)").addEventListener("change", () => {
  if (state.settings.theme === "auto") applyTheme();
});

// ===================== START =====================
init();
</script>
</body>
</html>