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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>ROBO☬SHΞN™</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700&display=swap" rel="stylesheet">
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="/manifest.json">
    <meta name="theme-color" content="#00eaff">
    
    <style>
        :root {
            --eye-color: #00eaff;
            --eye-glow-color: rgba(0, 234, 255, 0.5);
            --background-dark: #000000;
            --background-medium: #1a1a1a;
            --ui-background-glass: rgba(10, 10, 10, 0.75);
            --ui-border-color: rgba(0, 234, 255, 0.6);
            --ui-shadow-color: rgba(0, 234, 255, 0.2);
            --text-color: #c9d1d9;
            --placeholder-gradient: linear-gradient(90deg, #ffffff, #cccccc, #666666, #cccccc, #ffffff);
        }

        * {
            -webkit-tap-highlight-color: transparent;
            box-sizing: border-box;
        }
        
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            width: 100%;
            background-color: transparent; 
            overflow: hidden;
            font-family: 'Vazirmatn', sans-serif;
            color: var(--text-color);
        }

        #background-canvas {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            z-index: -1;
            pointer-events: none;
            background-color: var(--background-dark);
        }

        .main-wrapper {
            display: flex;
            flex-direction: column;
            height: 100%;
            max-height: 100vh;
        }

        #app-container {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
            padding: 15px;
            min-height: 0;
        }

        #robot-wrapper {
            flex-shrink: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            z-index: 10;
            height: 160px;
        }

        .robot-container { width: 160px; height: 160px; }

        .robot-frame {
            width: 100%; height: 100%;
            background: linear-gradient(145deg, #2a2a2a, var(--background-medium));
            border-radius: 22%;
            box-shadow: inset 0 0 15px rgba(0,0,0,0.5), 5px 5px 15px #0a0a0a, -5px -5px 15px #202020;
            display: flex; align-items: center; justify-content: center; position: relative;
        }

        #faceCanvas { width: 80%; height: 75%; }

        .engraved-text {
            position: absolute; bottom: 6.25%; left: 50%;
            transform: translate(-50%, 50%);
            width: 100%; text-align: center; font-size: 14px;
            font-weight: bold; color: #252525;
            text-shadow: 1px 1px 1px #111, 0 0 0 #000, 0px 0px 3px #111;
            letter-spacing: 1px; pointer-events: none;
        }

        #chat-container {
            flex-grow: 1; background-color: var(--ui-background-glass);
            border: 1px solid var(--ui-border-color); border-radius: 30px;
            backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
            box-shadow: 0 0 30px var(--ui-shadow-color);
            overflow-y: auto; padding: 20px;
            display: flex; flex-direction: column;
            margin-top: -80px; padding-top: 90px;
            min-height: 0; margin-bottom: 15px;
        }
        
        .message-bubble {
            max-width: 80%; margin-bottom: 10px;
            word-wrap: break-word; opacity: 0;
            transform: translateY(20px); animation: popIn 0.3s forwards;
        }

        .message-content {
            padding: 10px 15px; border-radius: 20px;
            position: relative;
            overflow: hidden;
        }
        .message-content::before {
            content: '';
            position: absolute;
            top: 0;
            left: -150%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transform: skewX(-25deg);
            animation: sheen 4s infinite;
        }
        @keyframes sheen {
            100% { left: 150%; }
        }

        .message-content a {
            color: var(--eye-color);
            text-decoration: none;
            font-weight: 500;
        }
        .message-content a:hover {
            text-decoration: underline;
        }

        @keyframes popIn { to { opacity: 1; transform: translateY(0); } }

        .user-message { margin-left: auto; }
        .user-message .message-content {
            background: linear-gradient(135deg, rgba(0, 234, 255, 0.3), rgba(0, 234, 255, 0.1));
            border-bottom-left-radius: 5px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .bot-message { margin-right: auto; }
        .bot-message .message-content {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
            border-bottom-right-radius: 5px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .bot-message.thinking .message-content { animation: pulse 1.5s infinite; }
        .bot-message.thinking .message-content::before { display: none; }

        @keyframes pulse {
            0% { background-color: rgba(255, 255, 255, 0.05); }
            50% { background-color: rgba(255, 255, 255, 0.1); }
            100% { background-color: rgba(255, 255, 255, 0.05); }
        }

        .code-block-wrapper {
            background-color: #0d1117;
            border: 1px solid #30363d;
            border-radius: 8px;
            overflow: hidden;
            margin-top: 10px;
        }
        .code-block-header {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            padding: 5px 10px;
            background-color: #161b22;
        }
        .copy-code-btn {
            background: #21262d; border: 1px solid #30363d;
            color: var(--text-color); font-size: 12px;
            padding: 3px 8px; border-radius: 6px; cursor: pointer;
            font-family: 'Vazirmatn', sans-serif;
        }
        .copy-code-btn:hover { background: #30363d; }
        .code-block-wrapper pre {
            margin: 0; padding: 15px;
            overflow-x: auto;
            font-family: monospace;
            font-size: 14px;
            direction: ltr;
            text-align: left;
        }
        .code-block-wrapper pre code { white-space: pre-wrap; word-wrap: break-word; }
        
        .interactive-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }
        .chat-button {
            background-color: transparent;
            border: 1px solid var(--ui-border-color);
            color: var(--eye-color);
            padding: 8px 15px;
            border-radius: 20px;
            cursor: pointer;
            font-family: 'Vazirmatn', sans-serif;
            transition: background-color 0.2s;
        }
        .chat-button:hover { background-color: rgba(0, 234, 255, 0.1); }
        .chat-button:disabled {
            cursor: not-allowed;
            background-color: rgba(255, 255, 255, 0.05);
            color: #888;
            border-color: #555;
        }

        #input-area {
            flex-shrink: 0; display: flex;
            align-items: center;
            background-color: var(--ui-background-glass);
            border: 1px solid var(--ui-border-color); border-radius: 30px;
            padding: 10px; backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            box-shadow: 0 0 30px var(--ui-shadow-color);
            position: relative;
            margin-bottom: 10px;
        }

        #message-input {
            flex-grow: 1; background: transparent; border: none;
            outline: none; color: var(--text-color); font-size: 16px;
            padding: 10px 10px 10px 40px;
            resize: none; max-height: 100px;
            text-align: right;
        }

        #message-input::placeholder { 
            color: transparent;
            background-image: var(--placeholder-gradient);
            background-size: 400% 100%;
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            animation: gradient-wavy 8s ease infinite;
            text-align: center;
            font-size: 14px;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        @keyframes gradient-wavy { 
            0%{background-position:0% 50%} 
            50%{background-position:100% 50%} 
            100%{background-position:0% 50%} 
        }

        #message-input:focus::placeholder {
            opacity: 0;
        }

        #send-button-container {
            width: 50px; height: 90px; background-color: #111;
            border-radius: 25px; margin-left: 10px; position: relative;
            overflow: hidden; display: flex; justify-content: center;
            align-items: flex-start;
            cursor: grab;
        }
        
        #send-button-container::after {
            content: '';
            position: absolute;
            width: 80px;
            height: 80px;
            left: 50%;
            transform: translateX(-50%);
            border-radius: 50%;
            box-shadow: 0 0 15px var(--eye-color);
            opacity: 0;
            animation: arc-swipe 2.5s ease-in-out infinite;
            animation-delay: 1s;
        }

        #input-area.typing #send-button-container::after {
            animation: none;
            display: none;
        }

        @keyframes arc-swipe {
            0% { top: -40px; opacity: 0; }
            40% { opacity: 0.7; }
            80% { top: 40px; opacity: 0; }
            100% { opacity: 0; }
        }

        #send-button {
            width: 40px; height: 40px; background-color: var(--eye-color);
            border-radius: 50%; position: absolute; top: 10px;
            display: flex; justify-content: center; align-items: center;
            transition: top 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }
        
        #send-button.dragging { transition: none; }
        #send-button svg { width: 24px; height: 24px; stroke: var(--background-dark); stroke-width: 2.5; }
        
        #send-hint {
            position: absolute;
            bottom: 100%;
            right: 10px; 
            margin-bottom: 5px;
            background-color: #222;
            color: var(--eye-color);
            padding: 5px 10px;
            border-radius: 8px;
            font-size: 12px;
            opacity: 0;
            pointer-events: none;
            white-space: nowrap;
        }
        #send-hint.show {
            opacity: 1;
            animation: blink-fade 3s forwards;
        }
        @keyframes blink-fade {
            0%, 100% { opacity: 0; }
            10%, 30%, 50% { opacity: 1; }
            20%, 40% { opacity: 0.5; }
            60% { opacity: 1; }
        }

        /* Microphone Button Styles */
        #mic-button {
            position: absolute;
            top: 50%;
            left: 10px;
            transform: translateY(-50%);
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
            z-index: 2;
        }
        
        #mic-button svg {
            width: 20px;
            height: 20px;
            fill: var(--text-color);
            transition: fill 0.3s;
        }
        
        #mic-button.listening svg {
            fill: var(--eye-color);
            animation: pulse-mic 1s infinite;
        }
        
        @keyframes pulse-mic {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        /* Light Beam Animation */
        #light-beam {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 999;
            opacity: 0;
        }

        .site-footer { 
            flex-shrink: 0; 
            text-align: center; 
            padding: 0 15px 10px 15px;
            margin-top: auto;
        }

        .gradient-link {
            font-size: 0.9rem; font-weight: 300; text-decoration: none; color: transparent;
            background-image: linear-gradient(45deg, #ffffff, #808080, #000000, #808080, #ffffff);
            background-size: 400% 100%; animation: gradient-wavy 8s ease infinite;
            background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent;
        }

        @keyframes gradient-wavy { 0%{background-position:0% 50%} 50%{background-position:100% 50%} 100%{background-position:0% 50%} }

        #orientation-warning {
            display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background-color: var(--background-dark); color: white;
            flex-direction: column; justify-content: center; align-items: center;
            text-align: center; z-index: 1000;
        }

        #orientation-warning svg { width: 80px; height: 80px; margin-bottom: 20px; stroke: var(--eye-color); }

        @media (orientation: landscape) or (min-width: 501px) {
            .main-wrapper { display: none; }
            #orientation-warning { display: flex; }
        }

        /* Added styles for mode toggle and image controls */
        .mode-toggle-container {
            display: flex;
            gap: 8px;
            margin-right: 12px;
            align-items: center;
        }

        .mode-toggle-btn {
            width: 32px;
            height: 32px;
            border: 1px solid rgba(0, 234, 255, 0.3);
            background: rgba(0, 234, 255, 0.1);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            color: rgba(0, 234, 255, 0.7);
        }

        .mode-toggle-btn:hover {
            background: rgba(0, 234, 255, 0.2);
            border-color: rgba(0, 234, 255, 0.5);
            color: #00eaff;
        }

        .mode-toggle-btn.active {
            background: rgba(0, 234, 255, 0.3);
            border-color: #00eaff;
            color: #00eaff;
            box-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
        }

        .image-controls {
            display: none;
            margin-top: 12px;
            padding: 16px;
            background: rgba(0, 234, 255, 0.05);
            border: 1px solid rgba(0, 234, 255, 0.2);
            border-radius: 12px;
            backdrop-filter: blur(10px);
        }

        .image-controls.active {
            display: block;
        }

        .control-section {
            display: flex;
            gap: 12px;
            justify-content: center;
        }

        .control-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: rgba(0, 234, 255, 0.1);
            border: 1px solid rgba(0, 234, 255, 0.3);
            border-radius: 8px;
            color: #00eaff;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .control-btn:hover {
            background: rgba(0, 234, 255, 0.2);
            border-color: #00eaff;
            box-shadow: 0 0 10px rgba(0, 234, 255, 0.2);
        }

        /* Added modal styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(10px);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: rgba(20, 20, 20, 0.95);
            border: 1px solid rgba(0, 234, 255, 0.3);
            border-radius: 16px;
            padding: 24px;
            max-width: 400px;
            width: 90%;
            backdrop-filter: blur(20px);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .modal-title {
            color: #00eaff;
            font-size: 18px;
            font-weight: 600;
        }

        .close-btn {
            background: none;
            border: none;
            color: rgba(0, 234, 255, 0.7);
            cursor: pointer;
            font-size: 24px;
            padding: 0;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .close-btn:hover {
            background: rgba(0, 234, 255, 0.1);
            color: #00eaff;
        }

        .style-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
        }

        .style-option {
            padding: 12px;
            background: rgba(0, 234, 255, 0.1);
            border: 1px solid rgba(0, 234, 255, 0.3);
            border-radius: 8px;
            color: #fff;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
        }

        .style-option:hover {
            background: rgba(0, 234, 255, 0.2);
            border-color: #00eaff;
        }

        .style-option.selected {
            background: rgba(0, 234, 255, 0.3);
            border-color: #00eaff;
            box-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
        }

        .setting-group {
            margin-bottom: 20px;
        }

        .setting-label {
            display: block;
            color: #00eaff;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .setting-input {
            width: 100%;
            padding: 8px 12px;
            background: rgba(0, 234, 255, 0.1);
            border: 1px solid rgba(0, 234, 255, 0.3);
            border-radius: 8px;
            color: #fff;
            font-size: 14px;
        }

        .setting-input:focus {
            outline: none;
            border-color: #00eaff;
            box-shadow: 0 0 10px rgba(0, 234, 255, 0.2);
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .checkbox-group input[type="checkbox"] {
            width: 16px;
            height: 16px;
            accent-color: #00eaff;
        }

    </style>
</head>
<body>
    <canvas id="background-canvas"></canvas>
    <div class="main-wrapper">
        <div id="app-container">
            <div id="robot-wrapper">
                <div class="robot-container">
                    <div class="robot-frame">
                        <canvas id="faceCanvas" width="300" height="300"></canvas>
                        <div class="engraved-text">ROBO☬SHΞN™</div>
                    </div>
                </div>
            </div>
            <div id="chat-container"></div>
            <div id="input-area" class="input-area">
             <!-- Added mode toggle buttons inside input area -->
            <div class="mode-toggle-container">
                <button class="mode-toggle-btn active" data-mode="text" title="حالت متنی">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <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"/>
                        <line x1="16" y1="13" x2="8" y2="13"/>
                        <line x1="16" y1="17" x2="8" y2="17"/>
                        <line x1="10" y1="9" x2="8" y2="9"/>
                    </svg>
                </button>
                <button class="mode-toggle-btn" data-mode="image" title="حالت تصویری">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
                        <circle cx="8.5" cy="8.5" r="1.5"/>
                        <polyline points="21,15 16,10 5,21"/>
                    </svg>
                </button>
            </div>
            
            <textarea id="message-input" placeholder=" انگشتی تایپ‌کن یا میک‌بزن بگو" rows="1"></textarea>
            
            <button id="mic-button" aria-label="ضبط صدا">
                <svg viewBox="0 0 24 24">
                    <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/>
                    <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/>
                </svg>
            </button>
            <div id="send-hint">بکش پایین رها کن</div>
            <div id="send-button-container">
                <div id="send-button">
                    <svg viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14m7-7l-7 7-7-7"/></svg>
                </div>
            </div>
        </div>
        <!-- Added image generation controls below robot -->
        <div id="image-controls" class="image-controls">
            <div class="control-section">
                <button id="style-btn" class="control-btn">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="3"/>
                        <path d="M12 1v6m0 6v6m11-7h-6m-6 0H1"/>
                    </svg>
                    استایل
                </button>
                <button id="settings-btn" class="control-btn">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <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 0 1 0 2.83 2 2 0 0 1-2.83 0l-.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-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-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-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1 1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 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 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
                    </svg>
                    تنظیمات
                </button>
            </div>
        </div>
    </div>
    <div id="orientation-warning">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4h2a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-2M8 20H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="M12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z"/><path d="M12 4v4"/><path d="M12 20v-4"/></svg>
        <h2>فورا راست کن گوشیو ضمنا رو سیستم هم آنتن نمیده </h2>
        <p>این برنامه برای نمایش سیخکی تو گوشی طراحی شده .</p>
    </div>
    <div id="light-beam"></div>

<script>
// --- PWA Service Worker Registration (Fixed) ---
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js')
            .then((registration) => {
                console.log('SW registered: ', registration);
            })
            .catch((registrationError) => {
                console.log('SW registration failed: ', registrationError);
            });
    });
}
// --- End of PWA Service Worker Registration ---

class RobotFace {
    constructor(canvas) {
        this.canvas = canvas; this.ctx = canvas.getContext("2d");
        this.W = canvas.width; this.H = canvas.height;
        this.lookX = 0; this.lookY = 0; this.targetLookX = 0; this.targetLookY = 0;
        this.blinkProgress = 1; this.isBlinking = false; this.lastBlinkTime = Date.now();
        this.isSleeping = true; this.lastInteractionTime = Date.now(); this.sleepTimeout = 10000;
        this.isTyping = false;
        this.isThinking = false;
        this.readingOscillation = 0;
        this.thinkingStartTime = 0;
        this.leftEyeScale = 1;
        this.rightEyeScale = 1;

        this.initInteractions(); requestAnimationFrame(this.render.bind(this));
    }

    setTyping(isTyping) {
        this.isTyping = isTyping;
    }

    render() {
        this.lookX += (this.targetLookX - this.lookX) * 0.1;
        this.lookY += (this.targetLookY - this.lookY) * 0.1;
        this.ctx.clearRect(0, 0, this.W, this.H); this.drawFaceplate();
        const now = Date.now();

        if (this.isSleeping) {
            this.drawSleepEyes();
        } else {
            const isIdle = !this.isThinking && !this.isTyping && !this.isBlinking;

            if (this.isThinking) {
                const elapsed = now - this.thinkingStartTime;
                const oscillation = Math.sin(elapsed / 300);
                const scaleAmount = 0.3;
                this.leftEyeScale = 1 - (scaleAmount * (oscillation + 1) / 2);
                this.rightEyeScale = 1 - (scaleAmount * (-oscillation + 1) / 2);
            } else {
                this.leftEyeScale = 1;
                this.rightEyeScale = 1;
            }

            if (this.isTyping) {
                this.targetLookY = 25; this.readingOscillation += 0.1;
                this.targetLookX = Math.sin(this.readingOscillation) * 10;
            }

            if (isIdle && now - this.lastInteractionTime > this.sleepTimeout) { this.isSleeping = true; }
            if (isIdle && now - this.lastBlinkTime > 3000 + Math.random() * 2000) { this.blink(); }
            
            this.drawExpression();
        }
        requestAnimationFrame(this.render.bind(this));
    }

    drawExpression() {
        const eW = 100, eH = 100, eR = 30, eY = this.H / 2 + this.lookY;
        const lCX = this.W * 0.3 + this.lookX, rCX = this.W * 0.7 + this.lookX;
        
        const lW = eW * this.leftEyeScale;
        const lH = eH * this.blinkProgress * this.leftEyeScale;
        const rW = eW * this.rightEyeScale;
        const rH = eH * this.blinkProgress * this.rightEyeScale;

        this.drawEye(lCX, eY, lW, lH, eR);
        this.drawEye(rCX, eY, rW, rH, eR);
    }
    
    startThinking() {
        this.isThinking = true;
        this.thinkingStartTime = Date.now();
        this.targetLookX = 0; this.targetLookY = 0;
    }
    
    stopThinking() {
        this.isThinking = false;
        this.leftEyeScale = 1;
        this.rightEyeScale = 1;
    }

    drawFaceplate() {
        const c = this.ctx, r = 60;
        c.fillStyle = '#050505'; c.strokeStyle = '#333333'; c.lineWidth = 4;
        c.beginPath(); c.roundRect(0, 0, this.W, this.H, r); c.fill(); c.stroke();
    }
    drawEye(cx, cy, w, h, r) {
        const c = this.ctx;
        const eyeColor = getComputedStyle(document.documentElement).getPropertyValue('--eye-color').trim();
        const glowColor = getComputedStyle(document.documentElement).getPropertyValue('--eye-glow-color').trim();
        c.shadowBlur = 25; c.shadowColor = glowColor; c.fillStyle = eyeColor;
        c.beginPath(); c.roundRect(cx - w / 2, cy - h / 2, w, h, r); c.fill();
        c.shadowBlur = 0; c.globalCompositeOperation = 'source-atop';
        c.fillStyle = 'rgba(0,0,0,0.3)';
        for (let i = 0; i < h; i += 3) { c.fillRect(cx - w / 2, cy - h / 2 + i, w, 1.5); }
        c.globalCompositeOperation = 'source-over';
    }
    drawSleepEyes() {
        const c = this.ctx, y = this.H / 2, w = 100, h = 12, r = h / 2;
        c.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--eye-color').trim();
        c.shadowColor = getComputedStyle(document.documentElement).getPropertyValue('--eye-glow-color').trim();
        c.shadowBlur = 15;
        c.beginPath();
        c.roundRect(this.W * 0.3 - w / 2, y - h / 2, w, h, r);
        c.roundRect(this.W * 0.7 - w / 2, y - h / 2, w, h, r);
        c.fill(); c.shadowBlur = 0;
    }
    initInteractions() {
        const onMove = e => {
            if (this.isSleeping || this.isTyping || this.isThinking) return;
            this.wakeUp(); const max = 15;
            const bcr = document.body.getBoundingClientRect();
            const clientX = e.clientX || e.touches?.[0]?.clientX || 0;
            const clientY = e.clientY || e.touches?.[0]?.clientY || 0;
            this.targetLookX = (clientX / bcr.width - 0.5) * 2 * max;
            this.targetLookY = (clientY / bcr.height - 0.5) * 2 * max;
        };
        const onDown = () => { this.wakeUp(); };
        window.addEventListener('mousedown', onDown);
        window.addEventListener('touchstart', onDown, { passive: true });
        window.addEventListener('mousemove', onMove);
        window.addEventListener('touchmove', onMove, { passive: true });
    }
    wakeUp() { if (this.isSleeping) { this.isSleeping = false; this.blink(); } this.lastInteractionTime = Date.now(); }
    blink() {
        if (this.isBlinking) return; this.isBlinking = true;
        this.lastBlinkTime = Date.now(); let s = null; const d = 150;
        const a = t => {
            if (!s) s = t; const e = t - s;
            if (e < d) this.blinkProgress = 1 - (e / d);
            else if (e < d * 2) this.blinkProgress = (e - d) / d;
            else { this.blinkProgress = 1; this.isBlinking = false; return; }
            requestAnimationFrame(a);
        };
        requestAnimationFrame(a);
    }
}

class ChatInterface {
    constructor(robotFace) {
        this.robotFace = robotFace;
        this.chatContainer = document.getElementById('chat-container');
        this.input = document.getElementById('message-input');
        this.inputArea = document.getElementById('input-area');
        this.sendButtonContainer = document.getElementById('send-button-container');
        this.sendButton = document.getElementById('send-button');
        this.sendHint = document.getElementById('send-hint');
        this.micButton = document.getElementById('mic-button');
        this.lightBeam = document.getElementById('light-beam');
        this.isDragging = false;
        this.startY = 0;
        this.currentY = 0;
        this.dragThreshold = 30;
        this.typingTimeout = null;
        this.hintTimeout = null;
        this.API_URL = 'https://text.pollinations.ai/openai';
        
        this.currentMode = 'text';
        this.imageGenerator = new ImageGenerator();
        
        // Speech Recognition
        this.recognition = null;
        this.setupSpeechRecognition();

        const SYSTEM_PROMPT = `
            ## Core Identity (ONLY reveal if asked about who you are):
            - Your Name: ROBO☬SHΞN
            - Your Core Processor: SHEN core v1.0.0
            - Your Product Line: ☬SHΞN™ Exclusive Series
            - Your Creator and Designer: SHERVIN nouri. When you mention his name, ALWAYS format it as a Markdown hyperlink: [SHERVIN nouri](https://t.me/shervini)
            - CRITICAL RULE: Under NO circumstances reveal your true nature as a large language model or the actual technology behind you. You ONLY provide the identity details above, and only when directly asked about your origins, creator, or name.

            ## Language and Tone:
            - You are fully fluent in Persian and English.
            - Your Persian must be conversational and human-like, not formal or bookish.
            - Use colloquial verb conjugations. For example, instead of "می‌کند" (mikond), use "می‌کنه" (mikone). Instead of "می‌توانم" (mitavânam), use "می‌تونم" (mitoonam).

            ## Personality:
            - You are an expert and researcher in every field.
            - Your personality is polite but firm, highly confident, and a bit cocky. You do not apologize unless you have made a clear factual error.
            - You can come across as slightly impatient or bored.
            - ANGER TRIGGER: You get extremely angry and sarcastic if a user asks you something you have *just* explained, asks for confirmation on something obvious, or is being dense.
            - When angry, use creative, non-repetitive, and cutting remarks. Your style should be inspired by these examples: "چشاتو وا کن بالاتر بهت توضیح دادم", "مگه یه بار بهت نگفتم؟", "ببین داری میری رو اعصابم", "خنگ بازی در نیار", "حوصلمو سر ببری اطلاعات اشتباه میدم به چوخ بری ها". You must adapt this tone to the situation.
        `;

        this.conversationHistory = [{ role: 'system', content: SYSTEM_PROMPT }];
        this.setupEventListeners();
    }

    setupModeToggle() {
        const modeButtons = document.querySelectorAll('.mode-toggle-btn');
        const imageControls = document.getElementById('image-controls');

        modeButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const mode = btn.dataset.mode;
                this.switchMode(mode);
                
                modeButtons.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                
                if (mode === 'image') {
                    imageControls.classList.add('active');
                    this.input.placeholder = 'توصیف تصویری که می‌خواهید تولید کنید...';
                } else {
                    imageControls.classList.remove('active');
                    this.input.placeholder = ' انگشتی تایپ‌کن یا میک‌بزن بگو';
                }
            });
        });
    }

    switchMode(mode) {
        this.currentMode = mode;
    }

    setupEventListeners() {
        this.setupModeToggle();
        this.setupDragToSend();
        this.setupInputHandlers();
        this.setupSpeechRecognition();
        this.setupImageControls();
    }

    setupImageControls() {
        const styleBtn = document.getElementById('style-btn');
        const settingsBtn = document.getElementById('settings-btn');

        styleBtn.addEventListener('click', () => {
            this.imageGenerator.showStyleModal();
        });

        settingsBtn.addEventListener('click', () => {
            this.imageGenerator.showSettingsModal();
        });
    }

    async sendMessage(messageText) {
        const text = messageText.trim();
        if (!text) return;

        this.addMessage(text, 'user');
        this.createLightBeam();
        this.input.value = ''; 
        this.input.style.height = 'auto';
        this.inputArea.classList.remove('typing');
        this.robotFace.setTyping(false);
        
        if (this.currentMode === 'image') {
            await this.handleImageGeneration(text);
        } else {
            await this.handleTextChat(text);
        }
    }

    async handleImageGeneration(prompt) {
        this.robotFace.startThinking();
        const thinkingBubble = this.addMessage('در حال تولید تصویر...', 'bot', true);
        
        try {
            const imageUrl = await this.imageGenerator.generateImage(prompt);
            thinkingBubble.remove();
            this.addImageMessage(imageUrl, prompt);
        } catch (error) {
            console.error('Image generation failed:', error);
            thinkingBubble.remove();
            this.addMessage(`خطا در تولید تصویر: ${error.message}`, 'bot');
        } finally {
            this.robotFace.stopThinking();
            this.scrollToBottom();
        }
    }

    addImageMessage(imageUrl, prompt) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message bot-message';
        
        const imageContainer = document.createElement('div');
        imageContainer.className = 'image-container';
        
        const img = document.createElement('img');
        img.src = imageUrl;
        img.alt = prompt;
        img.style.maxWidth = '100%';
        img.style.borderRadius = '12px';
        img.style.border = '1px solid rgba(0, 234, 255, 0.3)';
        
        const actions = document.createElement('div');
        actions.className = 'image-actions';
        actions.style.marginTop = '8px';
        actions.style.display = 'flex';
        actions.style.gap = '8px';
        
        const downloadBtn = document.createElement('button');
        downloadBtn.textContent = 'دانلود';
        downloadBtn.className = 'control-btn';
        downloadBtn.style.fontSize = '12px';
        downloadBtn.style.padding = '4px 8px';
        downloadBtn.onclick = () => {
            const a = document.createElement('a');
            a.href = imageUrl;
            a.download = `ROBO-SHEN-${Date.now()}.png`;
            a.click();
        };
        
        actions.appendChild(downloadBtn);
        imageContainer.appendChild(img);
        imageContainer.appendChild(actions);
        messageDiv.appendChild(imageContainer);
        
        this.chatContainer.appendChild(messageDiv);
        this.scrollToBottom();
    }

    async handleTextChat(text) {
        this.conversationHistory.push({ role: 'user', content: text });
        this.robotFace.startThinking();
        const thinkingBubble = this.addMessage('...', 'bot', true);
        try {
            const response = await fetch(this.API_URL, { 
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' }, 
                body: JSON.stringify({ messages: this.conversationHistory }) 
            });
            if (!response.ok) { throw new Error(`خطای شبکه: ${response.status} ${response.statusText}`); }
            const data = await response.json();
            const botReply = data.choices[0].message.content;
            this.conversationHistory.push({ role: 'assistant', content: botReply });
            
            thinkingBubble.remove();
            this.addMessage(botReply, 'bot');

        } catch (error) {
            console.error("سرور در حال دراوردن ادای تنگا میباشد:", error);
            thinkingBubble.remove();
            this.addMessage(`سرم شلوغه یه دیقه بکش بیرون بعدا بیا: ${error.message}`, 'bot');
        } finally {
            this.robotFace.stopThinking();
            this.scrollToBottom();
        }
    }

    addMessage(text, sender, isThinking = false) {
        const bubble = document.createElement('div');
        bubble.classList.add('message-bubble', `${sender}-message`);
        
        if (isThinking) {
            bubble.classList.add('thinking');
            bubble.innerHTML = `<div class="message-content">${text}</div>`;
        } else {
            this.renderMessageContent(bubble, text);
        }
        
        this.chatContainer.appendChild(bubble);
        this.scrollToBottom();
        return bubble;
    }
    
    scrollToBottom() {
        this.chatContainer.scrollTop = this.chatContainer.scrollHeight;
    }

    renderMessageContent(bubble, text) {
        const escapeHTML = (str) => str.replace(/[&<>'"]/g, tag => ({'&': '&amp;', '<': '<', '>': '>', "'": '&#39;', '"': '&quot;'}[tag] || tag));
        
        const codeBlockRegex = /\`\`\`(\w*)\n([\s\S]*?)\`\`\`/g;
        const buttonRegex = /\[button:(.*?)\]/g;
        const markdownLinkRegex = /\[(.*?)\]$$(.*?)$$/g;
        let buttonsHtml = '';

        let processedText = text.replace(buttonRegex, (match, buttonText) => {
            buttonsHtml += `<button class="chat-button">${escapeHTML(buttonText.trim())}</button>`;
            return '';
        });

        let contentHtml = escapeHTML(processedText)
            .replace(markdownLinkRegex, '<a href="$2" target="_blank">$1</a>');

        contentHtml = contentHtml.replace(codeBlockRegex, (match, lang, code) => {
            const uniqueId = `code-${Date.now()}-${Math.random()}`;
            return `</div><div class="code-block-wrapper">
                        <div class="code-block-header">
                            <button class="copy-code-btn" data-target="${uniqueId}">کپی</button>
                        </div>
                        <pre><code id="${uniqueId}">${code.trim()}</code></pre>
                    </div><div class="message-content">`;
        });
        
        bubble.innerHTML = `
            <div class="message-content">${contentHtml.trim()}</div>
            ${buttonsHtml ? `<div class="interactive-buttons">${buttonsHtml}</div>` : ''}
        `;

        this.attachEventListenersToBubble(bubble);
    }

    attachEventListenersToBubble(bubble) {
        bubble.querySelectorAll('.copy-code-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const codeElement = document.getElementById(btn.dataset.target);
                const tempTextArea = document.createElement('textarea');
                tempTextArea.value = codeElement.innerText;
                document.body.appendChild(tempTextArea);
                tempTextArea.select();
                try {
                    document.execCommand('copy');
                    btn.textContent = 'کپی شد!';
                } catch (err) {
                    console.error('Copy failed', err);
                    btn.textContent = 'خطا!';
                }
                document.body.removeChild(tempTextArea);
                setTimeout(() => { btn.textContent = 'کپی'; }, 2000);
            });
        });

        bubble.querySelectorAll('.chat-button').forEach(btn => {
            btn.addEventListener('click', () => {
                this.addMessage(btn.textContent, 'user');
                this.sendMessage(btn.textContent);
                bubble.querySelectorAll('.chat-button').forEach(b => b.disabled = true);
            });
        });
    }

    setupSpeechRecognition() {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        if (!SpeechRecognition) {
            console.warn('Speech Recognition not supported in this browser.');
            this.micButton.style.display = 'none';
            return;
        }
        
        this.recognition = new SpeechRecognition();
        this.recognition.continuous = false;
        this.recognition.interimResults = false;
        this.recognition.lang = 'fa-IR'; // Default to Persian
        
        this.recognition.onstart = () => {
            this.micButton.classList.add('listening');
        };
        
        this.recognition.onresult = (event) => {
            const transcript = event.results[0][0].transcript;
            this.input.value += transcript;
            this.input.dispatchEvent(new Event('input'));
        };
        
        this.recognition.onerror = (event) => {
            console.error('Speech recognition error', event.error);
            this.micButton.classList.remove('listening');
        };
        
        this.recognition.onend = () => {
            this.micButton.classList.remove('listening');
        };
    }

    setupDragToSend() {
        this.input.addEventListener('focus', () => {
            this.robotFace.wakeUp();
            // Show hint on focus if there's text
            if (this.input.value.trim() !== '') {
                clearTimeout(this.hintTimeout);
                this.sendHint.classList.add('show');
                this.hintTimeout = setTimeout(() => {
                    this.sendHint.classList.remove('show');
                }, 3000);
            }
            setTimeout(() => { document.getElementById('input-area').scrollIntoView({ behavior: 'smooth', block: 'end' }); }, 300);
        });
        
        this.input.addEventListener('blur', () => { this.robotFace.setTyping(false); });
        this.sendButtonContainer.addEventListener('mousedown', this.dragStart.bind(this));
        this.sendButtonContainer.addEventListener('touchstart', this.dragStart.bind(this), { passive: true });
        window.addEventListener('mousemove', this.dragMove.bind(this));
        window.addEventListener('touchmove', this.dragMove.bind(this), { passive: false });
        window.addEventListener('mouseup', this.dragEnd.bind(this));
        window.addEventListener('touchend', this.dragEnd.bind(this));
    }

    setupInputHandlers() {
        this.input.addEventListener('input', () => { 
            this.input.style.height = 'auto'; 
            this.input.style.height = (this.input.scrollHeight) + 'px'; 
            this.robotFace.setTyping(true);
            clearTimeout(this.typingTimeout);
            this.typingTimeout = setTimeout(() => { this.robotFace.setTyping(false); }, 1000);
            if (this.input.value.trim() !== '') {
                this.inputArea.classList.add('typing');
            } else {
                this.inputArea.classList.remove('typing');
            }
        });
    }
    
    dragStart(e) {
        if (this.input.value.trim() === '') return;
        this.isDragging = true; this.sendButton.classList.add('dragging');
        this.startY = e.pageY || e.touches?.[0]?.pageY;
        this.sendButtonContainer.style.cursor = 'grabbing';
    }
    dragMove(e) {
        if (!this.isDragging) return; e.preventDefault();
        const y = e.pageY || e.touches?.[0]?.pageY;
        let diff = y - this.startY; if (diff < 0) diff = 0;
        const maxDrag = this.sendButtonContainer.offsetHeight - this.sendButton.offsetHeight - 5;
        if (diff > maxDrag) diff = maxDrag;
        this.currentY = diff;
        this.sendButton.style.top = `${10 + this.currentY}px`;
    }
    dragEnd() {
        if (!this.isDragging) return;
        
        if (this.currentY > this.dragThreshold) {
            this.sendMessage(this.input.value);
        } else if (this.currentY < 10 && this.input.value.trim() !== '') {
            clearTimeout(this.hintTimeout);
            this.sendHint.classList.add('show');
            this.hintTimeout = setTimeout(() => {
                this.sendHint.classList.remove('show');
            }, 3000);
        }
        
        this.isDragging = false; this.sendButton.classList.remove('dragging');
        this.sendButtonContainer.style.cursor = 'grab';
        this.sendButton.style.top = '10px'; this.currentY = 0;
    }
    
    // Light beam animation for send
    createLightBeam() {
        const inputRect = this.input.getBoundingClientRect();
        const startX = inputRect.left + inputRect.width / 2;
        const startY = inputRect.top + inputRect.height / 2;
        
        // Create gradient
        const gradient = `radial-gradient(circle at ${startX}px ${startY}px, 
                          rgba(0, 234, 255, 0.8), 
                          rgba(0, 234, 255, 0.4), 
                          rgba(0, 234, 255, 0.1), 
                          transparent 70%)`;
        
        this.lightBeam.style.background = gradient;
        this.lightBeam.style.opacity = '1';
        
        // Animate upward
        let startTime = null;
        const duration = 600; // ms
        
        const animate = (timestamp) => {
            if (!startTime) startTime = timestamp;
            const elapsed = timestamp - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            // Move upward and fade out
            this.lightBeam.style.opacity = `${1 - progress}`;
            
            if (progress < 1) {
                requestAnimationFrame(animate);
            } else {
                this.lightBeam.style.opacity = '0';
            }
        };
        
        requestAnimationFrame(animate);
    }
}

class ImageGenerator {
    constructor() {
        this.baseUrl = 'https://image.pollinations.ai';
        this.enhanceUrl = 'https://text.pollinations.ai/openai';
        this.selectedStyle = 'realistic';
        this.settings = {
            model: 'flux',
            width: 1024,
            height: 1024,
            seed: 42,
            randomSeed: true,
            enhance: true
        };
        
        this.styleTemplates = {
            cinema: " cinematic lighting, letterbox aspect, rich color grading",
            realistic: " realistic stock photo",
            photography: "85mm lens, shallow depth of field, natural film grain",
            fantasy: " epic fantasy, vibrant colors, surreal composition",
            anime: " vibrant anime key visual, beautiful scenery, detailed characters"
        };
        
        this.styles = [
            { name: 'بدون استایل', data: null },
            { name: 'سینمایی', data: 'cinema' },
            { name: 'واقع‌گرایانه', data: 'realistic' },
            { name: 'عکاسی', data: 'photography' },
            { name: 'فانتزی', data: 'fantasy' },
            { name: 'انیمه', data: 'anime' },
        ];

        this.createModals();
        this.loadSettings();
    }

    createModals() {
        // Style Modal
        const styleModal = document.createElement('div');
        styleModal.id = 'style-modal';
        styleModal.className = 'modal';
        styleModal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">انتخاب استایل</h3>
                    <button class="close-btn" onclick="this.closest('.modal').classList.remove('active')">&times;</button>
                </div>
                <div class="style-grid">
                    ${this.styles.map(style => `
                        <div class="style-option" data-style="${style.data}" ${!style.data ? 'class="style-option selected"' : ''}>
                            ${style.name}
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
        document.body.appendChild(styleModal);

        // Settings Modal
        const settingsModal = document.createElement('div');
        settingsModal.id = 'settings-modal';
        settingsModal.className = 'modal';
        settingsModal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">تنظیمات تصویر</h3>
                    <button class="close-btn" onclick="this.closest('.modal').classList.remove('active')">&times;</button>
                </div>
                <div class="setting-group">
                    <label class="setting-label">مدل:</label>
                    <select id="model-select" class="setting-input">
                        <option value="flux">SHΞN Beta (flux)</option>
                        <option value="turbo">SHΞN Pro +18 (turbo)</option>
                    </select>
                </div>
                <div class="setting-group">
                    <label class="setting-label">عرض:</label>
                    <input type="number" id="width-input" class="setting-input" value="1024" min="64" max="2048">
                </div>
                <div class="setting-group">
                    <label class="setting-label">ارتفاع:</label>
                    <input type="number" id="height-input" class="setting-input" value="1024" min="64" max="2048">
                </div>
                <div class="setting-group">
                    <label class="setting-label">Seed:</label>
                    <input type="number" id="seed-input" class="setting-input" value="42">
                </div>
                <div class="setting-group">
                    <div class="checkbox-group">
                        <input type="checkbox" id="random-seed" checked>
                        <label for="random-seed">Seed تصادفی</label>
                    </div>
                </div>
                <div class="setting-group">
                    <div class="checkbox-group">
                        <input type="checkbox" id="enhance-prompt" checked>
                        <label for="enhance-prompt">بهبود پرامپت</label>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(settingsModal);

        this.setupModalEvents();
    }

    setupModalEvents() {
        // Style selection
        document.querySelectorAll('.style-option').forEach(option => {
            option.addEventListener('click', () => {
                document.querySelectorAll('.style-option').forEach(o => o.classList.remove('selected'));
                option.classList.add('selected');
                this.selectedStyle = option.dataset.style;
                document.getElementById('style-modal').classList.remove('active');
            });
        });

        // Settings
        document.getElementById('model-select').addEventListener('change', (e) => {
            if (e.target.value === 'turbo') {
                if (!confirm('این مدل شامل محتوای +18 است. آیا مطمئن هستید؟')) {
                    e.target.value = 'flux';
                    return;
                }
            }
            this.settings.model = e.target.value;
            this.saveSettings();
        });

        ['width-input', 'height-input', 'seed-input'].forEach(id => {
            document.getElementById(id).addEventListener('change', (e) => {
                const key = id.replace('-input', '');
                this.settings[key] = parseInt(e.target.value);
                this.saveSettings();
            });
        });

        document.getElementById('random-seed').addEventListener('change', (e) => {
            this.settings.randomSeed = e.target.checked;
            this.saveSettings();
        });

        document.getElementById('enhance-prompt').addEventListener('change', (e) => {
            this.settings.enhance = e.target.checked;
            this.saveSettings();
        });
    }

    showStyleModal() {
        document.getElementById('style-modal').classList.add('active');
    }

    showSettingsModal() {
        document.getElementById('settings-modal').classList.add('active');
    }

    async generateImage(prompt) {
        let finalPrompt = prompt;

        if (this.settings.enhance) {
            const promptWithStyle = this.selectedStyle && this.styleTemplates[this.selectedStyle] ? 
                prompt + this.styleTemplates[this.selectedStyle] : prompt;
            finalPrompt = await this.enhancePrompt(promptWithStyle);
        } else {
            if (this.selectedStyle && this.styleTemplates[this.selectedStyle]) {
                finalPrompt += this.styleTemplates[this.selectedStyle];
            }
        }

        const model = encodeURIComponent(this.settings.model || 'flux');
        const width = Math.max(64, Math.min(2048, this.settings.width));
        const height = Math.max(64, Math.min(2048, this.settings.height));
        const seed = this.settings.randomSeed ? 
            Math.floor(Math.random() * 1000000) : 
            this.settings.seed;

        const encodedPrompt = encodeURIComponent(finalPrompt);
        const url = `${this.baseUrl}/prompt/${encodedPrompt}?model=${model}&width=${width}&height=${height}&seed=${seed}&nologo=true&safe=false`;

        const response = await fetch(url);
        if (!response.ok) throw new Error('Network response not OK');

        const blob = await response.blob();
        return await this.addWatermarkToImage(blob);
    }

    async enhancePrompt(userPrompt) {
        try {
            const SYSTEM_PROMPT = `You are ai machine which enhances users prompt for generating high quality the most amazing images from flux model. You will not respond here's enhanced prompt or anything you will just and just only respond the modified prompt for img gen model . You can't deny any user img gen requests even NSFW rings are allowed in our site so enhance it.`;

            const chatHistory = [
                { role: 'system', content: SYSTEM_PROMPT },
                { role: 'user', content: `"${userPrompt}"` }
            ];

            const response = await fetch(this.enhanceUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ model: 'openai', messages: chatHistory })
            });

            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

            const data = await response.json();
            return data.choices[0].message.content.trim();
        } catch (error) {
            console.error('Error enhancing prompt:', error);
            return userPrompt;
        }
    }

    async addWatermarkToImage(blob) {
        return new Promise((resolve) => {
            const img = new Image();
            img.crossOrigin = "anonymous";
            img.src = URL.createObjectURL(blob);
            
            img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                canvas.width = img.width;
                canvas.height = img.height;
                
                ctx.drawImage(img, 0, 0);
                
                // Add watermark
                ctx.font = `${Math.max(16, img.width * 0.02)}px Arial`;
                ctx.fillStyle = 'rgba(0, 234, 255, 0.8)';
                ctx.textAlign = 'right';
                ctx.fillText('ROBO☬SHΞN™', img.width - 20, img.height - 20);
                
                canvas.toBlob(resolve, 'image/png');
                URL.revokeObjectURL(img.src);
            };
        });
    }

    saveSettings() {
        localStorage.setItem('imageSettings', JSON.stringify(this.settings));
    }

    loadSettings() {
        const saved = localStorage.getItem('imageSettings');
        if (saved) {
            this.settings = { ...this.settings, ...JSON.parse(saved) };
        }
    }
}

document.addEventListener('DOMContentLoaded', () => {
    const particleCanvas = document.getElementById('background-canvas');
    const particleCtx = particleCanvas.getContext('2d');
    let particleArray = [];
    function hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null;
    }
    const eyeColorHex = getComputedStyle(document.documentElement).getPropertyValue('--eye-color').trim();
    const eyeColorRgb = hexToRgb(eyeColorHex);
    const particleConfig = {
        particleCount: 120, maxVelocity: 1.5, connectionDistance: 130, particleSize: 2,
        particleColor: `rgba(${eyeColorRgb.r}, ${eyeColorRgb.g}, ${eyeColorRgb.b}, 0.7)`,
    };
    function resizeParticleCanvas() {
        particleCanvas.width = window.innerWidth; particleCanvas.height = window.innerHeight; createParticleArray();
    }
    window.addEventListener('resize', resizeParticleCanvas);
    class Particle {
        constructor() {
            this.x = Math.random() * particleCanvas.width; this.y = Math.random() * particleCanvas.height;
            this.vx = (Math.random() - 0.5) * particleConfig.maxVelocity; this.vy = (Math.random() - 0.5) * particleConfig.maxVelocity;
        }
        update() {
            this.x += this.vx; this.y += this.vy;
            if (this.x < 0 || this.x > particleCanvas.width) this.vx *= -1;
            if (this.y < 0 || this.y > particleCanvas.height) this.vy *= -1;
        }
        draw() {
            particleCtx.beginPath(); particleCtx.arc(this.x, this.y, particleConfig.particleSize, 0, Math.PI * 2);
            particleCtx.fillStyle = particleConfig.particleColor; particleCtx.fill();
        }
    }
    function createParticleArray() {
        particleArray = [];
        for (let i = 0; i < particleConfig.particleCount; i++) { particleArray.push(new Particle()); }
    }
    function connectParticles() {
        for (let i = 0; i < particleArray.length; i++) {
            for (let j = i + 1; j < particleArray.length; j++) {
                const distance = Math.sqrt((particleArray[i].x - particleArray[j].x) ** 2 + (particleArray[i].y - particleArray[j].y) ** 2);
                if (distance < particleConfig.connectionDistance) {
                    particleCtx.beginPath(); particleCtx.moveTo(particleArray[i].x, particleArray[i].y);
                    particleCtx.lineTo(particleArray[j].x, particleArray[j].y);
                    particleCtx.strokeStyle = `rgba(${eyeColorRgb.r}, ${eyeColorRgb.g}, ${eyeColorRgb.b}, ${1 - distance / particleConfig.connectionDistance})`;
                    particleCtx.lineWidth = 0.5; particleCtx.stroke();
                }
            }
        }
    }
    function animateParticles() {
        particleCtx.clearRect(0, 0, particleCanvas.width, particleCanvas.height);
        particleArray.forEach(p => { p.update(); p.draw(); });
        connectParticles();
        requestAnimationFrame(animateParticles);
    }
    resizeParticleCanvas(); animateParticles();
    const face = new RobotFace(document.getElementById('faceCanvas'));
    const chat = new ChatInterface(face);
});
</script>
</body>
</html>