File size: 89,169 Bytes
420fede
 
 
 
 
365872b
420fede
 
 
6c7a26a
365872b
6c7a26a
 
365872b
6c7a26a
 
365872b
 
6c7a26a
a173d7c
6c7a26a
 
365872b
 
 
 
 
 
8937563
365872b
6c7a26a
 
365872b
cfc4d00
08c0585
 
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8937563
 
 
 
 
e296870
365872b
cfc4d00
365872b
6c7a26a
365872b
8937563
 
 
365872b
 
 
 
8937563
 
 
 
380bb68
365872b
 
 
 
 
 
4cfe10c
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380bb68
54244d0
 
365872b
 
 
54244d0
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380bb68
365872b
 
e296870
365872b
 
 
 
 
 
 
 
 
 
 
 
 
fb69e3f
 
 
 
 
 
365872b
 
380bb68
365872b
 
8937563
365872b
 
 
 
 
e296870
365872b
 
 
 
 
 
 
 
 
 
 
 
e296870
 
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54244d0
61aad51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54244d0
 
61aad51
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54244d0
365872b
e296870
365872b
 
e296870
 
365872b
e296870
 
fb69e3f
e296870
365872b
61aad51
e296870
365872b
 
61aad51
e296870
365872b
 
e296870
 
365872b
e296870
 
365872b
e296870
365872b
61aad51
365872b
 
54244d0
 
365872b
f3c1c82
54244d0
 
 
f3c1c82
54244d0
 
365872b
 
54244d0
365872b
 
54244d0
365872b
61aad51
54244d0
e296870
365872b
54244d0
e296870
61aad51
 
54244d0
 
61aad51
 
 
54244d0
61aad51
 
 
 
 
e296870
365872b
 
 
 
 
fb69e3f
365872b
fb69e3f
54244d0
f3c1c82
54244d0
 
365872b
420fede
 
 
365872b
6c7a26a
365872b
 
6c7a26a
 
 
8937563
 
 
365872b
8937563
 
 
db70610
365872b
 
420fede
 
365872b
 
 
a173d7c
365872b
 
 
 
 
420fede
365872b
 
 
420fede
 
365872b
 
 
 
 
420fede
365872b
 
 
 
 
 
 
 
 
 
 
 
 
54244d0
 
 
 
 
 
365872b
e296870
 
420fede
365872b
 
 
 
 
6c7a26a
365872b
 
 
 
380bb68
365872b
 
 
 
 
 
 
380bb68
 
 
365872b
 
 
 
 
 
 
 
 
 
a173d7c
365872b
 
 
fb69e3f
 
 
 
380bb68
365872b
 
 
 
 
 
 
 
 
 
 
 
 
a173d7c
420fede
 
 
54244d0
61aad51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54244d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e296870
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e296870
365872b
e296870
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e296870
420fede
365872b
 
 
 
f3c1c82
365872b
 
61aad51
365872b
61aad51
365872b
61aad51
365872b
 
54244d0
365872b
61aad51
365872b
 
61aad51
 
 
 
 
 
 
 
 
365872b
 
 
 
61aad51
 
 
365872b
 
 
61aad51
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61aad51
 
 
 
 
 
f3c1c82
61aad51
365872b
 
 
 
54244d0
 
 
 
 
 
 
 
 
 
 
 
61aad51
365872b
61aad51
 
f3c1c82
61aad51
 
 
 
db70610
 
61aad51
 
 
 
 
 
 
 
 
db70610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61aad51
 
365872b
54244d0
365872b
 
 
 
 
 
 
 
 
 
 
f3c1c82
 
 
 
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
e296870
365872b
 
 
 
 
 
 
 
420fede
365872b
 
 
 
 
 
420fede
365872b
 
 
420fede
 
365872b
420fede
365872b
 
 
 
420fede
365872b
 
 
420fede
365872b
 
 
420fede
365872b
 
 
420fede
365872b
 
 
 
420fede
365872b
 
 
 
420fede
365872b
420fede
365872b
 
420fede
 
365872b
 
 
 
 
 
 
 
420fede
 
 
365872b
420fede
 
 
365872b
 
 
 
420fede
 
 
365872b
 
 
db70610
365872b
 
420fede
365872b
 
 
 
 
 
e296870
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54244d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365872b
 
 
 
 
 
54244d0
365872b
 
 
 
 
 
 
 
 
 
8937563
365872b
 
8937563
 
 
 
365872b
8937563
 
 
 
 
 
365872b
8937563
 
 
 
 
365872b
 
8937563
 
365872b
 
 
 
420fede
365872b
 
 
 
420fede
e296870
365872b
 
 
 
 
 
 
 
 
 
 
 
e296870
6c7a26a
f3c1c82
 
 
 
 
365872b
 
f3c1c82
365872b
 
 
 
 
 
 
 
 
 
 
 
 
e296870
f3c1c82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365872b
 
e296870
365872b
 
 
e296870
365872b
 
e296870
 
365872b
 
 
 
 
 
 
 
 
 
e296870
365872b
420fede
 
f3c1c82
08c0585
 
 
 
365872b
 
f3c1c82
 
365872b
08c0585
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54244d0
365872b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a173d7c
365872b
 
 
08c0585
365872b
 
420fede
365872b
f3c1c82
365872b
 
 
420fede
e296870
365872b
f3c1c82
365872b
 
 
e296870
 
365872b
 
 
 
380bb68
365872b
 
380bb68
365872b
380bb68
365872b
380bb68
365872b
380bb68
365872b
e296870
365872b
380bb68
365872b
6c7a26a
 
365872b
6c7a26a
365872b
6c7a26a
 
 
 
365872b
6c7a26a
 
420fede
 
e296870
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
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>استودیو جامع ساخت تصویر هوش مصنوعی</title>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --app-font: 'Vazirmatn', sans-serif;
            --app-bg: #F0F2F5;
            --panel-bg: #FFFFFF;
            --panel-border: #EAEFF7;
            --input-bg: #F8F9FC;
            --input-border: #E1E7EF;
            --text-primary: #1A202C;
            --text-secondary: #4A5568;
            --text-tertiary: #718096;
            --accent-primary: #4A6CFA;
            --accent-primary-hover: #3553D6;
            --accent-primary-glow: rgba(74, 108, 250, 0.25);
            --accent-secondary: #0FD4A8;
            --premium-gold: #FFC107;
            --danger-color: #E53E3E;
            
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.08);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            --shadow-xl: 0 20px 25px -5px rgba(26, 32, 44, 0.07), 0 8px 10px -6px rgba(26, 32, 44, 0.05);
            --radius-card: 20px;
            --radius-btn: 14px;
            --radius-input: 12px;
            --radius-sm: 10px;
            --transition-smooth: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }

        body { 
            font-family: var(--app-font); 
            background-color: var(--app-bg); 
            color: var(--text-primary); 
            display: flex; 
            justify-content: center; 
            min-height: 100vh;
            padding: 2rem 1rem;
        }

        .container { 
            max-width: 820px; 
            width: 100%; 
            display: flex; 
            flex-direction: column; 
            gap: 1.5rem; 
        }

        @keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes core-pulse { 0%, 100% { transform: scale(0.95); box-shadow: 0 0 25px var(--accent-primary-glow); } 50% { transform: scale(1.05); box-shadow: 0 0 50px rgba(74, 108, 250, 0.5); } }
        @keyframes ring-rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes background-pan { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } }
        @keyframes badge-fade-in { from { opacity: 0; transform: translateY(-10px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } }

        /* Header Style */
        header { position: relative; text-align: center; margin-bottom: 2.5rem; padding: 2rem 0; animation: fadeIn 0.8s 0.1s ease-out backwards; overflow: hidden; }
        #neural-network-canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; opacity: 0.7; }
        .header-content { position: relative; z-index: 2; }
        
        .ai-orb-container { width: 150px; height: 150px; margin: 0 auto 1rem; position: relative; display: flex; align-items: center; justify-content: center; }
        .orb-background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(ellipse at center, rgba(74, 108, 250, 0.15) 0%, transparent 70%), linear-gradient(45deg, rgba(15, 212, 168, 0.05), rgba(74, 108, 250, 0.05)); border-radius: 50%; animation: background-pan 12s ease-in-out infinite; background-size: 200% 200%; }
        .orb-core { width: 60px; height: 60px; border-radius: 50%; background: radial-gradient(circle, #394A7A 0%, #1A202C 70%); box-shadow: 0 0 25px var(--accent-primary-glow); display: flex; align-items: center; justify-content: center; position: relative; z-index: 2; animation: core-pulse 4s ease-in-out infinite; border: 1px solid rgba(74, 108, 250, 0.3); }
        
        .image-icon { width: 28px; height: 28px; color: var(--accent-secondary); filter: drop-shadow(0 0 8px rgba(15, 212, 168, 0.7)); transition: var(--transition-smooth); }
        .orb-core:hover .image-icon { transform: scale(1.1); color: #fff; filter: drop-shadow(0 0 12px rgba(15, 212, 168, 1)); }
        
        .orb-ring { position: absolute; top: 50%; left: 50%; border-style: solid; border-color: transparent; border-radius: 50%; z-index: 1; mix-blend-mode: screen; }
        .orb-ring.one { width: 100px; height: 100px; margin-top: -50px; margin-left: -50px; border-width: 2px; border-top-color: var(--accent-primary); border-right-color: var(--accent-primary); animation: ring-rotate 8s linear infinite; filter: blur(1px); }
        .orb-ring.two { width: 120px; height: 120px; margin-top: -60px; margin-left: -60px; border-width: 1px; border-bottom-color: var(--accent-secondary); animation: ring-rotate 10s linear infinite reverse; }
        .orb-ring.three { width: 140px; height: 140px; margin-top: -70px; margin-left: -70px; border-width: 2px; border-left-color: rgba(255, 255, 255, 0.5); border-right-color: rgba(255, 255, 255, 0.5); animation: ring-rotate 12s linear infinite; filter: blur(1px); opacity: 0.5; }
        
        h1 { font-size: 2.2rem; font-weight: 800; margin: 0 0 0.5rem 0; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .subtitle { font-size: 1.05rem; color: var(--text-secondary); margin: 0; }

        /* Badge */
        #subscription-status-badge { display: none; padding: 6px 16px; border-radius: 20px; font-size: 0.85em; font-weight: 700; margin-top: 1rem; display: inline-block; animation: badge-fade-in 0.6s 0.5s ease-out backwards;}
        #subscription-status-badge.free-badge { background: #64748b; color: white; box-shadow: 0 2px 8px rgba(100, 116, 139, 0.3); }
        #subscription-status-badge.paid-badge { background: linear-gradient(45deg, #FFC107, #ffca2c); color: #333; box-shadow: 0 4px 10px rgba(255, 193, 7, 0.3); }

        /* Control Panel */
        .control-panel {
            background: var(--panel-bg);
            border-radius: var(--radius-card);
            padding: 2rem;
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--panel-border);
            display: flex;
            flex-direction: column;
            gap: 2rem;
            animation: fadeIn 0.6s ease-out 0.2s both;
        }

        .section-title { font-size: 1.05rem; font-weight: 700; color: var(--text-primary); margin-bottom: 1rem; display: flex; align-items: center; gap: 8px; }
        .section-title svg { width: 22px; height: 22px; color: var(--accent-primary); }

        /* Textarea & Prompt Helper Button */
        textarea { width: 100%; padding: 1.2rem; border-radius: var(--radius-input); border: 2px solid var(--input-border); background-color: var(--input-bg); color: var(--text-primary); font-family: var(--app-font); font-size: 1.05rem; transition: var(--transition-smooth); min-height: 120px; resize: vertical; margin-bottom: 0.5rem; }
        textarea:focus { outline: none; border-color: var(--accent-primary); box-shadow: 0 0 0 4px var(--accent-primary-glow); background-color: #fff; }
        textarea:disabled { opacity: 0.7; cursor: not-allowed; }

        .prompt-helper-button { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; padding: 12px; font-size: 0.95rem; font-weight: 700; color: var(--accent-primary); background-color: transparent; border: 2px dashed var(--input-border); border-radius: var(--radius-input); cursor: pointer; transition: var(--transition-smooth); font-family: inherit; }
        .prompt-helper-button:hover { background-color: var(--input-bg); border-color: var(--accent-primary); transform: translateY(-1px); }

        /* Ratio Selector */
        .ratio-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem; }
        .ratio-btn { background: var(--input-bg); border: 2px solid var(--input-border); border-radius: var(--radius-input); padding: 1rem 0.5rem; color: var(--text-secondary); font-size: 0.9rem; font-weight: 700; cursor: pointer; transition: var(--transition-smooth); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; }
        .ratio-btn:hover { border-color: var(--accent-primary); transform: translateY(-3px); }
        .ratio-btn.active { background: #fff; border-color: var(--accent-primary); color: var(--accent-primary); box-shadow: 0 0 0 3px var(--accent-primary-glow); }
        
        .ratio-icon-box { background-color: var(--panel-bg); border: 2px solid var(--text-tertiary); border-radius: 4px; transition: var(--transition-smooth); display:flex; align-items:center; justify-content:center;}
        .ratio-btn.active .ratio-icon-box { border-color: var(--accent-primary); background-color: var(--accent-primary-glow); color: var(--accent-primary); }
        .icon-1-1 { width: 28px; height: 28px; }
        .icon-16-9 { width: 40px; height: 22px; }
        .icon-9-16 { width: 22px; height: 40px; }
        .icon-custom { width: 34px; height: 25px; border-style: dashed !important; color: var(--text-tertiary); }

        /* Model Selector Grid (Square) */
        .model-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; }
        .model-card { 
            position: relative; 
            border-radius: var(--radius-sm); 
            overflow: hidden; 
            cursor: pointer; 
            border: 2px solid var(--input-border); 
            aspect-ratio: 1 / 1; 
            height: auto;
            transition: var(--transition-smooth);
            background-color: var(--input-bg);
        }
        .model-card:hover { border-color: var(--text-tertiary); }
        .model-card.active { border-color: var(--accent-primary); box-shadow: 0 0 15px rgba(74, 108, 250, 0.4); }
        .model-card.active::after { content: ''; position: absolute; inset: 0; border: 2px solid var(--accent-primary); border-radius: calc(var(--radius-sm) - 2px); pointer-events: none; }
        
        .model-image { width: 100%; height: 100%; background-size: cover; background-position: center; transition: transform 0.5s; opacity: 0.6; }
        .model-card:hover .model-image, .model-card.active .model-image { transform: scale(1.1); opacity: 1; }
        
        .model-name { position: absolute; bottom: 0; left: 0; width: 100%; padding: 8px 6px; background: linear-gradient(to top, rgba(0,0,0,0.9), transparent); color: #fff; font-size: 0.9rem; font-weight: 700; text-align: center; text-shadow: 0 1px 2px rgba(0,0,0,0.8); pointer-events: none; }

        /* Buttons & Info */
        .big-send-btn { display: flex; align-items: center; justify-content: center; gap: 0.75rem; width: 100%; padding: 1.2rem; font-size: 1.3rem; font-weight: 800; background: linear-gradient(95deg, var(--accent-secondary) 0%, var(--accent-primary) 100%); color: #fff; border: none; border-radius: var(--radius-btn); cursor: pointer; transition: all 0.3s ease; box-shadow: 0 6px 15px -3px var(--accent-primary-glow); }
        .big-send-btn svg { width: 26px; height: 26px; filter: drop-shadow(0 0 5px rgba(255,255,255,0.4)); }
        .big-send-btn:hover:not(:disabled) { transform: translateY(-4px) scale(1.01); box-shadow: 0 10px 20px -4px var(--accent-primary-glow); }
        .big-send-btn:disabled { background: var(--text-tertiary); cursor: not-allowed; box-shadow: none; opacity: 0.7; transform: none; }

        .credit-info { font-size: 0.95rem; color: var(--text-tertiary); text-align: center; margin-bottom: 1rem; font-weight: 600; background: var(--input-bg); padding: 10px; border-radius: var(--radius-input); border: 1px solid var(--input-border); display: none; }
        .upgrade-btn { display: none; width: 100%; margin-bottom: 1rem; padding: 1rem; background: linear-gradient(90deg, #FFD54F, var(--premium-gold)); border: none; border-radius: var(--radius-btn); color: #212529; font-weight: 800; font-size: 1.1rem; cursor: pointer; text-align: center; font-family: inherit; box-shadow: 0 6px 15px rgba(255, 193, 7, 0.3); transition: transform 0.3s; }
        .upgrade-btn:hover { transform: translateY(-3px); }

        /* Result Area */
        #image-result-container { display: flex; width: 100%; flex-direction: column; align-items: center; gap: 1rem; margin-top: 1rem; padding-top: 2rem; border-top: 1px solid var(--panel-border); animation: fadeIn 0.5s ease-out; }
        
        .empty-placeholder { width: 400px; max-width: 100%; height: 300px; border: 2px dashed var(--input-border); border-radius: 20px; background-color: transparent; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; }
        .empty-placeholder svg { color: var(--text-tertiary); margin-bottom: 15px; opacity: 0.5; width: 48px; height: 48px; }
        .empty-placeholder p { color: var(--text-tertiary); font-size: 0.95rem; font-weight: 600; margin: 0; }

        .generated-image-box { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 1rem; }
        .generated-image-box img { max-width: 100%; border-radius: var(--radius-input); border: 1px solid var(--panel-border); box-shadow: var(--shadow-lg); }
        
        .image-meta { display: flex; gap: 15px; justify-content: center; background: var(--input-bg); padding: 8px 20px; border-radius: 20px; font-size: 0.85rem; font-weight: 600; color: var(--text-secondary); border: 1px solid var(--input-border); }
        .image-meta span { display: flex; align-items: center; gap: 5px; }
        
        .download-btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; width: 100%; max-width: 300px; padding: 0.9rem; background: var(--accent-primary); color: #fff; border: none; border-radius: var(--radius-btn); font-family: inherit; font-weight: 700; cursor: pointer; transition: var(--transition-smooth); text-decoration: none; box-shadow: 0 4px 10px rgba(74, 108, 250, 0.3); }
        .download-btn:hover { background: var(--accent-primary-hover); transform: translateY(-3px); box-shadow: 0 6px 15px rgba(74, 108, 250, 0.4); }

        /* --- TV Loading Animation --- */
        .generator-container { position: relative; width: 400px; max-width: 100%; height: 300px; border: 2px solid #38bdf8; border-radius: 20px; overflow: hidden; box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); animation: pulse-loader 5s infinite cubic-bezier(0.4, 0, 0.6, 1); background-color: #161b22; color: #f0f6fc; margin: 0 auto; }
        @keyframes pulse-loader { 0% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } 50% { box-shadow: 0 0 60px rgba(56, 189, 248, 0.7); } 100% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } }
        .noise-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect width="100" height="100" fill="none"/><filter id="noise"><feTurbulence type="fractalNoise" baseFrequency="0.5" numOctaves="4" stitchTiles="stitch"/></filter><rect width="100%" height="100%" filter="url(%23noise)" opacity="0.6"/></svg>') repeat; opacity: 1; animation: fade-noise 7s infinite ease-in-out; } 
        @keyframes fade-noise { 0% { opacity: 1; filter: blur(5px); } 30% { opacity: 0.8; filter: blur(2px); } 100% { opacity: 0; filter: blur(0px); } }
        .sketch-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter: grayscale(1) contrast(1.5) blur(3px); opacity: 0; animation: reveal-sketch 7s infinite ease-in-out; } 
        @keyframes reveal-sketch { 0% { opacity: 0; } 20% { opacity: 1; } 60% { opacity: 0.5; } 100% { opacity: 0; } }
        .building-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter: blur(15px); opacity: 0; animation: denoise-color 7s infinite ease-in-out; } 
        @keyframes denoise-color { 0% { opacity: 0; } 40% { opacity: 0.6; filter: blur(5px); } 100% { opacity: 1; filter: blur(0px); } }
        .pixel-grid { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: repeating-linear-gradient(0deg, transparent 0 1px, rgba(255,255,255,0.1) 1px 2px), repeating-linear-gradient(90deg, transparent 0 1px, rgba(255,255,255,0.1) 1px 2px); opacity: 1; animation: dissolve-grid 7s infinite ease-in-out; } 
        @keyframes dissolve-grid { 0% { opacity: 1; } 70% { opacity: 0.5; } 100% { opacity: 0; } }
        .particles { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(circle, rgba(56, 189, 248, 0.2) 0%, transparent 50%); animation: flow-particles 7s infinite cubic-bezier(0.4, 0, 0.6, 1); } 
        @keyframes flow-particles { 0% { transform: translate(0, 0) scale(1); opacity: 0.5; } 50% { transform: translate(10px, -15px) scale(1.05); opacity: 0.8; } 100% { transform: translate(0, 0) scale(1); opacity: 0.5; } }
        .text-overlay { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); font-size: 20px; font-weight: 700; text-shadow: 0 0 20px rgba(56, 189, 248, 0.8); animation: glow-text 7s infinite ease-in-out; font-family: var(--app-font); width: 90%; text-align: center;} 
        @keyframes glow-text { 0% { opacity: 0.7; } 50% { opacity: 1; } 100% { opacity: 0.7; } }
        .progress-bar { position: absolute; bottom: 0; left: 0; width: 0%; height: 6px; background: linear-gradient(to right, #38bdf8, #bb86fc, #facc15); transition: width 0.3s linear; }

        /* --- Modal Styles for Prompts --- */
        .alpha-modal-backdrop { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background-color: rgba(26, 32, 44, 0.6); z-index: 1000; display: flex; align-items: center; justify-content: center; opacity: 0; animation: fadeInBackdrop 0.3s forwards; }
        .alpha-modal-content { background-color: var(--panel-bg); border-radius: var(--radius-card); box-shadow: var(--shadow-xl); width: 90%; max-width: 500px; max-height: 90vh; display: flex; flex-direction: column; position: relative; padding: 25px; opacity: 0; transform: translateY(-20px) scale(0.95); animation: fadeInModal 0.3s 0.1s forwards; border: 1px solid var(--panel-border);}
        .alpha-modal-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--panel-border); padding-bottom: 15px; margin-bottom: 15px; }
        .alpha-modal-header h2 { font-size: 1.25rem; font-weight: 800; color: var(--accent-primary); }
        .alpha-modal-close-btn { background-color: transparent; border: none; font-size: 2rem; line-height: 1; color: var(--text-tertiary); cursor: pointer; transition: color 0.3s; }
        .alpha-modal-close-btn:hover { color: var(--danger-color); }
        .alpha-modal-body { overflow-y: auto; flex-grow: 1; padding-left: 10px; margin-left: -10px; }
        .alpha-modal-body::-webkit-scrollbar { width: 6px; }
        .alpha-modal-body::-webkit-scrollbar-track { background: var(--input-bg); border-radius: 4px; }
        .alpha-modal-body::-webkit-scrollbar-thumb { background: var(--input-border); border-radius: 4px; }
        .alpha-modal-body::-webkit-scrollbar-thumb:hover { background: var(--text-tertiary); }
        .alpha-modal-footer { padding-top: 15px; margin-top: 15px; border-top: 1px solid var(--panel-border); text-align: center; }
        
        .prompt-category-item, .prompt-item { display: flex; align-items: center; justify-content: space-between; background-color: var(--input-bg); padding: 12px 15px; border-radius: var(--radius-input); border: 1px solid var(--input-border); margin-bottom: 10px; cursor: pointer; transition: var(--transition-smooth); }
        .prompt-category-item:hover, .prompt-item:hover { border-color: var(--accent-primary); background-color: #fff; transform: translateY(-2px); box-shadow: var(--shadow-md); }
        .prompt-category-item { font-weight: 700; color: var(--text-secondary); }
        .prompt-item .prompt-text-container { display: flex; flex-direction: column; align-items: flex-start; text-align: right; flex-grow: 1; }
        .prompt-item .prompt-text { font-weight: 700; font-size: 0.95rem; color: var(--text-primary); direction: ltr; text-align: left; align-self: flex-start; }
        .prompt-item .persian-translation { font-size: 0.85rem; color: var(--text-tertiary); margin-top: 4px;}
        
        .pagination-container { display: flex; justify-content: center; gap: 10px; margin-top: 15px; align-items: center; }
        .pagination-button, .alpha-modal-footer .modal-action-button { padding: 8px 16px; border-radius: var(--radius-sm); font-size: 0.9rem; font-weight: 700; cursor: pointer; font-family: inherit; transition: var(--transition-smooth); box-shadow: var(--shadow-sm); }
        .pagination-button { background-color: var(--accent-primary); color: #fff; border: none; }
        .pagination-button:hover { background-color: var(--accent-primary-hover); transform: translateY(-1px); }
        .pagination-button:disabled { background-color: var(--input-border); color: var(--text-tertiary); cursor: not-allowed; transform: none; box-shadow: none;}
        .alpha-modal-footer .modal-action-button { background-color: var(--input-bg); color: var(--text-secondary); border: 1px solid var(--input-border); }
        .alpha-modal-footer .modal-action-button:hover { background-color: #fff; border-color: var(--text-secondary); color: var(--text-primary); }
        
        @keyframes fadeInBackdrop { from { opacity: 0; } to { opacity: 1; } }
        @keyframes fadeInModal { from { opacity: 0; transform: translateY(-20px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } }

        /* --- Custom Dialogs (Confirm & Input) --- */
        .confirm-modal-backdrop {
            position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
            background-color: rgba(26, 32, 44, 0.7); z-index: 3000;
            display: flex; align-items: center; justify-content: center;
            opacity: 0; animation: fadeInBackdrop 0.3s forwards;
            backdrop-filter: blur(5px);
        }
        .confirm-modal-content {
            background: var(--panel-bg); border-radius: var(--radius-card); padding: 25px;
            width: 90%; max-width: 400px; text-align: center; box-shadow: var(--shadow-xl);
            transform: scale(0.9); animation: popIn 0.3s forwards; border: 1px solid var(--panel-border);
        }
        @keyframes popIn { to { transform: scale(1); opacity: 1; } }
        .confirm-icon {
            width: 60px; height: 60px; color: var(--danger-color); margin: 0 auto 15px;
            background: rgba(229, 62, 62, 0.1); border-radius: 50%; display: flex; align-items: center; justify-content: center;
        }
        .confirm-title { font-size: 1.2rem; font-weight: 800; color: var(--text-primary); margin-bottom: 10px; }
        .confirm-message { font-size: 0.95rem; color: var(--text-secondary); margin-bottom: 25px; line-height: 1.6; }
        .confirm-actions { display: flex; gap: 10px; justify-content: center; }
        .confirm-btn { flex: 1; padding: 12px; border-radius: var(--radius-btn); font-weight: 700; font-size: 1rem; cursor: pointer; border: none; transition: var(--transition-smooth); font-family: inherit; }
        .btn-cancel { background: var(--input-bg); color: var(--text-secondary); border: 1px solid var(--input-border); }
        .btn-cancel:hover { background: #e2e8f0; color: var(--text-primary); }
        .btn-danger { background: var(--danger-color); color: white; box-shadow: 0 4px 10px rgba(229,62,62,0.3); }
        .btn-danger:hover { background: #C53030; transform: translateY(-2px); box-shadow: 0 6px 15px rgba(229,62,62,0.4); }
        .btn-primary-action { background: var(--accent-primary); color: white; box-shadow: 0 4px 10px rgba(74, 108, 250, 0.3); }
        .btn-primary-action:hover { background: var(--accent-primary-hover); transform: translateY(-2px); box-shadow: 0 6px 15px rgba(74, 108, 250, 0.4); }

        /* --- History Section Styles --- */
        .history-section {
            margin-top: 1rem;
            padding-top: 2rem;
            border-top: 1px solid var(--panel-border);
            display: none;
            animation: fadeIn 0.5s ease-out;
        }
        .history-header {
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;
        }
        .history-header h3 {
            font-size: 1.1rem; font-weight: 700; color: var(--text-primary); display: flex; align-items: center; gap: 8px;
        }
        .history-header h3 svg { width: 22px; height: 22px; color: var(--accent-primary); }
        .danger-btn {
            background: var(--input-bg); color: var(--danger-color); border: 1px solid var(--danger-color);
            padding: 6px 14px; border-radius: var(--radius-sm); font-family: inherit; font-weight: 700; cursor: pointer; transition: var(--transition-smooth); font-size: 0.85rem;
        }
        .danger-btn:hover { background: var(--danger-color); color: #fff; }
        
        .history-grid {
            display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;
        }
        .history-item {
            background: var(--input-bg); border: 1px solid var(--input-border); border-radius: var(--radius-sm);
            overflow: hidden; display: flex; flex-direction: column; transition: transform 0.3s;
        }
        .history-item:hover {
            transform: translateY(-3px); box-shadow: var(--shadow-md); border-color: var(--text-tertiary);
        }
        .history-item img {
            width: 100%; height: 200px; object-fit: cover; cursor: pointer; border-bottom: 1px solid var(--input-border);
        }
        .history-details {
            padding: 12px; display: flex; flex-direction: column; gap: 10px; flex-grow: 1; overflow: hidden;
        }
        .history-prompt {
            font-size: 0.85rem; color: var(--text-primary); font-weight: 600;
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis; direction: auto; text-align: right;
        }
        .history-meta {
            font-size: 0.75rem; color: var(--text-tertiary); display: flex; justify-content: space-between; font-weight: 600; background: var(--panel-bg); padding: 4px 8px; border-radius: 6px; border: 1px solid var(--panel-border);
        }
        .history-delete-btn {
            margin-top: auto; padding: 6px; background: transparent; color: var(--danger-color); border: 1px dashed var(--danger-color); border-radius: 6px; cursor: pointer; font-family: inherit; font-size: 0.8rem; font-weight: 600; transition: var(--transition-smooth);
        }
        .history-delete-btn:hover {
            background: var(--danger-color); color: white; border-style: solid;
        }

        /* --- Image View Modal & Toolbar --- */
        .image-view-modal {
            position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
            background-color: rgba(26, 32, 44, 0.95); z-index: 2000;
            display: flex; flex-direction: column; align-items: center;
            opacity: 0; animation: fadeInBackdrop 0.3s forwards;
            overflow-y: auto;
            padding: 40px 20px;
        }
        .image-view-wrapper {
            margin: auto;
            display: flex; flex-direction: column; align-items: center; gap: 12px;
            width: 100%; max-width: 800px; position: relative;
        }
        .image-view-modal img {
            max-width: 100%; border-radius: var(--radius-card); box-shadow: 0 0 30px rgba(0,0,0,0.5); object-fit: contain;
        }
        .image-view-close {
            position: fixed; top: 20px; right: 20px; background: rgba(255,255,255,0.15); border: 2px solid rgba(255,255,255,0.3);
            color: white; font-size: 1.5rem; cursor: pointer; width: 45px; height: 45px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center; transition: all 0.3s; z-index: 2002;
            backdrop-filter: blur(5px);
        }
        .image-view-close:hover {
            background: rgba(255,255,255,0.3); border-color: white; transform: scale(1.1);
        }
        
        .image-view-toolbar {
            width: 100%; display: flex; gap: 15px; justify-content: center;
            background: rgba(0,0,0,0.7); padding: 12px 20px; border-radius: 20px; backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.1);
        }
        .iv-action-btn {
            background: var(--accent-primary); color: white; border: none; padding: 10px 18px; border-radius: var(--radius-btn);
            font-family: inherit; font-weight: 700; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; transition: all 0.2s; font-size: 0.95rem; box-shadow: 0 4px 10px rgba(0,0,0,0.3);
        }
        .iv-action-btn:hover { background: var(--accent-primary-hover); transform: translateY(-3px); box-shadow: 0 6px 15px rgba(0,0,0,0.4); }
        .iv-action-btn svg { width: 20px; height: 20px; }
        .iv-btn-copy { background: #4A5568; }
        .iv-btn-copy:hover { background: #2D3748; }

        @media (max-width: 650px) {
            .model-grid { gap: 10px; }
            .ratio-grid { grid-template-columns: repeat(2, 1fr); }
            h1 { font-size: 1.8rem; }
            .generator-container { height: 250px; } 
            .empty-placeholder { height: 250px; }
            .text-overlay { font-size: 16px; }
            .history-item img { height: 140px; }
            
            .image-view-modal { padding: 60px 15px 30px; } 
            .image-view-toolbar { flex-direction: row; flex-wrap: wrap; padding: 10px; border-radius: 15px; gap: 10px;}
            .iv-action-btn { flex: 1; min-width: 130px; font-size: 0.85rem; padding: 10px 12px;}
        }
    </style>
</head>
<body>

    <div class="container">
        
        <!-- Header -->
        <header>
            <canvas id="neural-network-canvas"></canvas>
            <div class="header-content">
                <div class="ai-orb-container">
                    <div class="orb-background"></div>
                    <div class="orb-core">
                        <svg class="image-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/></svg>
                    </div>
                    <div class="orb-ring one"></div><div class="orb-ring two"></div><div class="orb-ring three"></div>
                </div>
                <h1>استودیو ساخت تصاویر آلفا</h1>
                <p class="subtitle">ایده‌های خود را به بهترین تصاویر خیره‌کننده تبدیل کنید</p>
                <div id="subscription-status-badge">درحال بررسی...</div>
            </div>
        </header>

        <!-- Control Panel -->
        <div class="control-panel">
            
            <!-- 1. Input & Prompts -->
            <div>
                <div class="section-title">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
                    ۱. ایده خود را بنویسید
                </div>
                
                <textarea id="prompt-input" placeholder="تصویر رویایی خود را با جزئیات توصیف کنید..."></textarea>
                <button id="promptHelperBtn" class="prompt-helper-button">💡 افزودن سبک به تصویر (پرامپت ها)</button>
            </div>

            <!-- 2. Ratio Selection -->
            <div>
                <div class="section-title">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 9V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h4"/><rect x="12" y="13" width="10" height="8" rx="2"/><path d="M17 12v-1a2 2 0 0 0-2-2h-1"/></svg>
                    ۲. ابعاد تصویر
                </div>
                <div class="ratio-grid" id="ratio-selector">
                    <button class="ratio-btn active" data-ratio="1:1" data-name="۱:۱ مربع">
                        <div class="ratio-icon-box icon-1-1"></div>
                        <span>۱:۱ مربع</span>
                    </button>
                    <button class="ratio-btn" data-ratio="16:9" data-name="۱۶:۹ افقی">
                        <div class="ratio-icon-box icon-16-9"></div>
                        <span>۱۶:۹ افقی</span>
                    </button>
                    <button class="ratio-btn" data-ratio="9:16" data-name="۹:۱۶ استوری">
                        <div class="ratio-icon-box icon-9-16"></div>
                        <span>۹:۱۶ استوری</span>
                    </button>
                    <!-- Custom Size Button -->
                    <button class="ratio-btn" data-ratio="custom" data-name="اندازه دلخواه">
                        <div class="ratio-icon-box icon-custom">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>
                        </div>
                        <span>اندازه دلخواه</span>
                    </button>
                </div>
            </div>

            <!-- 3. Model Selection -->
            <div>
                <div class="section-title">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
                    ۳. مدل هوش مصنوعی
                </div>
                <div class="model-grid" id="model-selector">
                    <div class="model-card active" data-action="generate-flux" data-name="Flux Pro">
                        <div class="model-image" style="background-image: url('https://app.puzzley.net/uploads/user/Jydo/Gpt4/pro.webp');"></div>
                        <div class="model-name">Flux Pro</div>
                    </div>
                    <div class="model-card" data-action="generate-midjourney" data-name="Midjourney">
                        <div class="model-image" style="background-image: url('https://app.puzzley.net/uploads/user/Jydo/%D9%87%D9%88%D8%B4%20%D9%85%D8%B5%D9%86%D9%88%D8%B9%DB%8C/Midjourney_Emblem.png');"></div>
                        <div class="model-name">Midjourney</div>
                    </div>
                    <div class="model-card" data-action="generate-cartoon" data-name="Cartoon 3D">
                        <div class="model-image" style="background-image: url('https://app.puzzley.net/uploads/user/Jydo/Ghibli/image%20(28).webp');"></div>
                        <div class="model-name">Cartoon 3D</div>
                    </div>
                </div>
            </div>

            <!-- Generate Buttons -->
            <div>
                <div id="credit-info" class="credit-info">درحال بررسی اعتبار...</div>
                <button id="upgrade-button" class="upgrade-btn">⭐️ ارتقا به نسخه نامحدود</button>

                <button id="send-btn" class="big-send-btn">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
                    ساخت تصویر جادویی
                </button>
            </div>

            <!-- Result Container -->
            <div id="image-result-container">
                <div class="empty-placeholder">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
                    <p>تصویر شما در این کادر ظاهر می‌شود</p>
                </div>
            </div>
            
            <!-- History Section -->
            <div id="history-section" class="history-section">
                <div class="history-header">
                    <h3>
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18.7 8l-5.1 5.2-2.8-2.7L7 14.3"/></svg>
                        سابقه تصاویر ساخته شده
                    </h3>
                    <button id="clear-history-btn" class="danger-btn">حذف همه</button>
                </div>
                <div id="history-grid" class="history-grid"></div>
            </div>
            
        </div>
    </div>

    <script>
        // --- توابع پاپ‌آپ سفارشی (تاییدیه حذف و اندازه دلخواه) ---
        function showCustomConfirm(title, message, onConfirm) {
            const backdrop = document.createElement('div');
            backdrop.className = 'confirm-modal-backdrop';
            
            const content = document.createElement('div');
            content.className = 'confirm-modal-content';
            
            content.innerHTML = `
                <div class="confirm-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"></path><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
                </div>
                <div class="confirm-title">${title}</div>
                <div class="confirm-message">${message}</div>
                <div class="confirm-actions">
                    <button class="confirm-btn btn-cancel" id="confirm-cancel">انصراف</button>
                    <button class="confirm-btn btn-danger" id="confirm-ok">تایید و حذف</button>
                </div>
            `;
            
            backdrop.appendChild(content);
            document.body.appendChild(backdrop);
            
            const close = () => {
                backdrop.style.opacity = '0';
                setTimeout(() => backdrop.remove(), 300);
            };
            
            backdrop.querySelector('#confirm-cancel').onclick = close;
            backdrop.querySelector('#confirm-ok').onclick = () => {
                onConfirm();
                close();
            };
            backdrop.onclick = (e) => {
                if(e.target === backdrop) close();
            }
        }

        let userCustomWidth = 1024;
        let userCustomHeight = 1024;

        function showCustomSizeModal(onConfirm) {
            const backdrop = document.createElement('div');
            backdrop.className = 'confirm-modal-backdrop';
            
            const content = document.createElement('div');
            content.className = 'confirm-modal-content';
            
            content.innerHTML = `
                <div class="confirm-icon" style="color: var(--accent-primary); background: var(--accent-primary-glow);">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:32px;height:32px;"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><path d="M3 9h18"></path><path d="M9 21V9"></path></svg>
                </div>
                <div class="confirm-title">اندازه دلخواه تصویر</div>
                <div class="confirm-message">ابعاد مورد نظر خود را وارد کنید (بین ۲۵۶ تا ۲۰۴۸)</div>
                <div style="display:flex; gap:10px; margin-bottom: 20px; flex-direction:row-reverse;">
                    <div style="flex:1;">
                        <label style="display:block; font-size:0.85rem; margin-bottom:5px; color:var(--text-secondary); font-weight:bold;">عرض (Width)</label>
                        <input type="number" id="inp-width" value="${userCustomWidth}" min="256" max="2048" style="width:100%; padding:10px; border-radius:10px; border:2px solid var(--input-border); font-family:inherit; text-align:center; font-weight:bold; font-size:1.1rem; outline:none;">
                    </div>
                    <div style="flex:1;">
                        <label style="display:block; font-size:0.85rem; margin-bottom:5px; color:var(--text-secondary); font-weight:bold;">ارتفاع (Height)</label>
                        <input type="number" id="inp-height" value="${userCustomHeight}" min="256" max="2048" style="width:100%; padding:10px; border-radius:10px; border:2px solid var(--input-border); font-family:inherit; text-align:center; font-weight:bold; font-size:1.1rem; outline:none;">
                    </div>
                </div>
                <div class="confirm-actions">
                    <button class="confirm-btn btn-cancel" id="size-cancel">انصراف</button>
                    <button class="confirm-btn btn-primary-action" id="size-ok">تایید اندازه</button>
                </div>
            `;
            
            backdrop.appendChild(content);
            document.body.appendChild(backdrop);
            
            const inputs = backdrop.querySelectorAll('input');
            inputs.forEach(inp => {
                inp.addEventListener('focus', () => inp.style.borderColor = 'var(--accent-primary)');
                inp.addEventListener('blur', () => inp.style.borderColor = 'var(--input-border)');
            });

            const close = () => {
                backdrop.style.opacity = '0';
                setTimeout(() => backdrop.remove(), 300);
            };
            
            backdrop.querySelector('#size-cancel').onclick = close;
            
            backdrop.querySelector('#size-ok').onclick = () => {
                const w = parseInt(backdrop.querySelector('#inp-width').value);
                const h = parseInt(backdrop.querySelector('#inp-height').value);
                if(w >= 256 && w <= 2048 && h >= 256 && h <= 2048) {
                    userCustomWidth = w;
                    userCustomHeight = h;
                    onConfirm(w, h);
                    close();
                } else {
                    alert('لطفا مقادیری بین ۲۵۶ تا ۲۰۴۸ وارد کنید.');
                }
            };

            backdrop.onclick = (e) => {
                if(e.target === backdrop) close();
            }
        }

        // --- مدیریت دیتابیس تصاویر (IndexedDB) ---
        const dbName = 'ImageStudioDB';
        const storeName = 'ImageHistory';
        let db;

        function initDB() {
            return new Promise((resolve, reject) => {
                const request = indexedDB.open(dbName, 1);
                request.onerror = event => reject(event.target.error);
                request.onsuccess = event => {
                    db = event.target.result;
                    resolve(db);
                };
                request.onupgradeneeded = event => {
                    db = event.target.result;
                    if (!db.objectStoreNames.contains(storeName)) {
                        db.createObjectStore(storeName, { keyPath: 'id', autoIncrement: true });
                    }
                };
            });
        }

        async function saveToHistory(blob, prompt, model, ratio) {
            if (!db) await initDB();
            return new Promise((resolve, reject) => {
                const transaction = db.transaction([storeName], 'readwrite');
                const store = transaction.objectStore(storeName);
                const newItem = {
                    blob: blob,
                    prompt: prompt,
                    model: model,
                    ratio: ratio,
                    timestamp: Date.now()
                };
                store.add(newItem);

                const countReq = store.count();
                countReq.onsuccess = () => {
                    if (countReq.result > 50) {
                        const extra = countReq.result - 50;
                        const cursorReq = store.openCursor();
                        let deletedCount = 0;
                        cursorReq.onsuccess = e => {
                            const cursor = e.target.result;
                            if (cursor && deletedCount < extra) {
                                store.delete(cursor.primaryKey);
                                deletedCount++;
                                cursor.continue();
                            }
                        };
                    }
                };
                transaction.oncomplete = () => {
                    loadHistory();
                    resolve();
                };
                transaction.onerror = e => reject(e.target.error);
            });
        }

        async function loadHistory() {
            if (!db) await initDB();
            return new Promise((resolve, reject) => {
                const transaction = db.transaction([storeName], 'readonly');
                const store = transaction.objectStore(storeName);
                const request = store.getAll();
                request.onsuccess = e => {
                    const items = e.target.result;
                    items.sort((a, b) => b.timestamp - a.timestamp);
                    renderHistory(items);
                    resolve(items);
                };
                request.onerror = e => reject(e.target.error);
            });
        }

        function renderHistory(items) {
            const historySection = document.getElementById('history-section');
            const grid = document.getElementById('history-grid');
            grid.innerHTML = '';
            
            if (items.length === 0) {
                historySection.style.display = 'none';
                return;
            }
            
            historySection.style.display = 'block';
            
            items.forEach(item => {
                const blobUrl = URL.createObjectURL(item.blob);
                const safeTitle = item.prompt.replace(/"/g, '&quot;');
                const div = document.createElement('div');
                div.className = 'history-item';

                div.innerHTML = `
                    <img src="${blobUrl}" alt="History Image" title="برای مشاهده کلیک کنید">
                    <div class="history-details">
                        <div class="history-prompt" dir="auto" title="${safeTitle}">${item.prompt}</div>
                        <div class="history-meta">
                            <span>${item.model}</span>
                            <span dir="ltr">${item.ratio}</span>
                        </div>
                        <button class="history-delete-btn">حذف تصویر</button>
                    </div>
                `;
                
                div.querySelector('img').addEventListener('click', () => {
                    viewHistoryImage(blobUrl, item.prompt);
                });
                
                div.querySelector('.history-delete-btn').addEventListener('click', () => {
                    deleteHistoryItem(item.id);
                });

                grid.appendChild(div);
            });
        }

        window.deleteHistoryItem = function(id) {
            showCustomConfirm('حذف از سابقه', 'آیا از حذف دائمی این تصویر از حافظه مرورگر خود اطمینان دارید؟', async () => {
                if (!db) await initDB();
                const transaction = db.transaction([storeName], 'readwrite');
                const store = transaction.objectStore(storeName);
                store.delete(id);
                transaction.oncomplete = () => loadHistory();
            });
        };

        async function deleteAllHistory() {
            if (!db) await initDB();
            return new Promise((resolve, reject) => {
                const transaction = db.transaction([storeName], 'readwrite');
                const store = transaction.objectStore(storeName);
                store.clear();
                transaction.oncomplete = () => {
                    loadHistory();
                    resolve();
                };
            });
        }

        document.getElementById('clear-history-btn').addEventListener('click', () => {
            showCustomConfirm('حذف تمام تصاویر', 'آیا از پاک کردن تمامی ۵۰ تصویر آخر از سابقه مطمئن هستید؟ این عمل غیرقابل بازگشت است.', () => {
                deleteAllHistory();
            });
        });

        // نمایش عکس بزرگ همراه با نوار ابزار در زیر آن (با پاس دادن به متد اصلی)
        window.viewHistoryImage = function(url, promptText) {
            const modal = document.createElement('div');
            modal.className = 'image-view-modal';
            modal.innerHTML = `
                <button class="image-view-close" onclick="this.parentElement.remove()">×</button>
                <div class="image-view-wrapper" onclick="event.stopPropagation()">
                    <img src="${url}" alt="Full Image" class="full-view-img">
                    <div class="image-view-toolbar">
                        <button class="iv-action-btn iv-btn-copy" id="btn-copy-prompt">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
                            کپی پرامپت
                        </button>
                        <button class="iv-action-btn" id="btn-download-img">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                            دانلود تصویر
                        </button>
                    </div>
                </div>
            `;
            
            modal.querySelector('#btn-download-img').onclick = () => {
                window.triggerDownload(url);
            };
            
            const copyBtn = modal.querySelector('#btn-copy-prompt');
            copyBtn.onclick = () => {
                // --- شروع کد اصلاح شده برای کپی کردن ---
                const showSuccess = () => {
                    const originalHtml = copyBtn.innerHTML;
                    copyBtn.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg> کپی شد!`;
                    copyBtn.style.background = 'var(--accent-secondary)';
                    copyBtn.style.color = '#1A202C';
                    setTimeout(() => {
                        copyBtn.innerHTML = originalHtml;
                        copyBtn.style.background = '';
                        copyBtn.style.color = '';
                    }, 2000);
                };

                const fallbackCopy = () => {
                    const textArea = document.createElement("textarea");
                    textArea.value = promptText;
                    textArea.style.position = "fixed"; 
                    textArea.style.top = "-9999px";
                    textArea.style.left = "-9999px";
                    document.body.appendChild(textArea);
                    textArea.focus();
                    textArea.select();
                    try {
                        document.execCommand('copy');
                        showSuccess();
                    } catch (err) {
                        console.error('Fallback copy failed', err);
                    }
                    document.body.removeChild(textArea);
                };

                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(promptText).then(showSuccess).catch(fallbackCopy);
                } else {
                    fallbackCopy();
                }
                // --- پایان کد اصلاح شده ---
            };

            modal.onclick = (e) => {
                if(e.target === modal) modal.remove();
            };
            document.body.appendChild(modal);
        };


        // --- سیستم اعتبار و شناسایی کاربر ---
        let userSubscriptionStatus = 'free';
        let userFingerprint = null;
        let countdownInterval = null;
        let isResultProcessed = false; 
        let fakeProgressInterval = null;
        
        let activePollTimer = null; // برای مدیریت تایمر ساخت عکس در پس زمینه
        let activeTimeoutTimer = null; // برای مدیریت هشدار دو دقیقه‌ای
        
        const PREMIUM_PAGE_ID = '1149636'; 

        async function getBrowserFingerprint() { 
            const components = [navigator.userAgent, navigator.language, screen.width + 'x' + screen.height, new Date().getTimezoneOffset(), "canvas-test"]; 
            const fingerprintString = components.join('---'); 
            let hash = 0; 
            for (let i = 0; i < fingerprintString.length; i++) { hash = ((hash << 5) - hash) + fingerprintString.charCodeAt(i); hash |= 0; } 
            return 'fp_img_' + Math.abs(hash).toString(16); 
        }

        function isUserPaid(userObject) { 
            return userObject?.isLogin && userObject.accessible_pages?.some(p => p == PREMIUM_PAGE_ID); 
        }

        function updateUIForSubscriptionStatus(status) { 
            userSubscriptionStatus = status; 
            const creditInfoDiv = document.getElementById('credit-info'); 
            const upgradeBtn = document.getElementById('upgrade-button'); 
            const sendBtn = document.getElementById('send-btn'); 
            const badge = document.getElementById('subscription-status-badge'); 
            
            badge.style.display = 'inline-block';
            
            if (status === 'paid') { 
                badge.textContent = 'کاربر ویژه (نامحدود)'; 
                badge.className = 'paid-badge'; 
                creditInfoDiv.style.display = 'none'; 
                upgradeBtn.style.display = 'none'; 
                sendBtn.disabled = false; 
                if(countdownInterval) clearInterval(countdownInterval); 
            } else { 
                badge.textContent = 'کاربر رایگان'; 
                badge.className = 'free-badge'; 
                checkFreeUserCredit(); 
            } 
        }

        async function checkFreeUserCredit() { 
            if (!userFingerprint || userSubscriptionStatus === 'paid') return; 
            const creditInfoDiv = document.getElementById('credit-info'); 
            const upgradeBtn = document.getElementById('upgrade-button'); 
            const sendBtn = document.getElementById('send-btn'); 
            try { 
                const response = await fetch('/api/check-image-credit', { 
                    method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) 
                }); 
                const result = await response.json(); 
                
                creditInfoDiv.style.display = 'block'; 
                
                if (result.limit_reached) { 
                    sendBtn.disabled = true; 
                    upgradeBtn.style.display = 'block'; 
                    startCountdown(result.reset_timestamp); 
                } else { 
                    sendBtn.disabled = false; 
                    upgradeBtn.style.display = 'none'; 
                    if(countdownInterval) clearInterval(countdownInterval); 
                    creditInfoDiv.innerHTML = `شما <b>${result.credits_remaining}</b> اعتبار ساخت تصویر برای امروز دارید.`; 
                } 
            } catch (error) { 
                creditInfoDiv.textContent = "خطا در ارتباط با سیستم اعتبار."; 
                sendBtn.disabled = true; 
            } 
        }

        function startCountdown(resetTimestamp) { 
            if (countdownInterval) clearInterval(countdownInterval); 
            const creditInfoDiv = document.getElementById('credit-info'); 
            const updateTimer = () => { 
                const timeLeft = Math.max(0, resetTimestamp - (Date.now() / 1000)); 
                if (timeLeft === 0) { 
                    clearInterval(countdownInterval); 
                    creditInfoDiv.textContent = 'در حال شارژ اعتبارات...'; 
                    setTimeout(checkFreeUserCredit, 2000); return; 
                } 
                const h = Math.floor(timeLeft / 3600); 
                const m = Math.floor((timeLeft % 3600) / 60); 
                creditInfoDiv.innerHTML = `<span style="color:var(--danger-color)">اعتبار امروز تمام شد.</span> زمان شارژ مجدد: ${h} ساعت و ${m} دقیقه`; 
            }; 
            updateTimer(); countdownInterval = setInterval(updateTimer, 60000); 
        }

        window.addEventListener('message', (event) => { 
            if (event.data?.type === 'USER_DATA_RESPONSE') { 
                if (event.data.error || !event.data.payload) { updateUIForSubscriptionStatus('free'); return; } 
                try { 
                    const userObject = JSON.parse(event.data.payload); 
                    updateUIForSubscriptionStatus(isUserPaid(userObject) ? 'paid' : 'free'); 
                } catch (e) { updateUIForSubscriptionStatus('free'); } 
            } 
        });

        document.addEventListener('DOMContentLoaded', async () => { 
            userFingerprint = await getBrowserFingerprint(); 
            parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*'); 
            document.getElementById('upgrade-button').addEventListener('click', () => { parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM' }, '*'); });
            initDB().then(() => loadHistory()).catch(e => console.error("Database init error:", e));
        });

        // --- بخش انتخاب‌ها ---
        const promptInput = document.getElementById('prompt-input');
        const sendBtn = document.getElementById('send-btn');
        const imageResultContainer = document.getElementById('image-result-container');
        const modelSelector = document.getElementById('model-selector');
        const ratioSelector = document.getElementById('ratio-selector');
        
        let selectedModelAction = 'generate-flux';
        let selectedModelName = 'Flux Pro';
        let selectedRatio = '1:1';
        let selectedRatioName = '۱:۱ مربع';

        modelSelector.addEventListener('click', (e) => {
            const card = e.target.closest('.model-card');
            if (!card) return;
            modelSelector.querySelectorAll('.model-card').forEach(c => c.classList.remove('active'));
            card.classList.add('active');
            selectedModelAction = card.dataset.action;
            selectedModelName = card.dataset.name;
        });

        ratioSelector.addEventListener('click', (e) => {
            const btn = e.target.closest('.ratio-btn');
            if (!btn) return;
            
            if (btn.dataset.ratio === 'custom') {
                showCustomSizeModal((w, h) => {
                    ratioSelector.querySelectorAll('.ratio-btn').forEach(c => c.classList.remove('active'));
                    btn.classList.add('active');
                    selectedRatio = 'custom';
                    selectedRatioName = `${w}x${h} دلخواه`;
                    btn.querySelector('span').textContent = `${w}x${h} دلخواه`;
                });
            } else {
                ratioSelector.querySelectorAll('.ratio-btn').forEach(c => c.classList.remove('active'));
                btn.classList.add('active');
                selectedRatio = btn.dataset.ratio;
                selectedRatioName = btn.dataset.name;
                
                const customBtn = ratioSelector.querySelector('[data-ratio="custom"]');
                if(customBtn) customBtn.querySelector('span').textContent = 'اندازه دلخواه';
            }
        });

        const getDimensions = (ratio) => {
            switch (ratio) {
                case '9:16': return { width: 768, height: 1344 };
                case '16:9': return { width: 1344, height: 768 };
                case 'custom': return { width: userCustomWidth, height: userCustomHeight };
                case '1:1': default: return { width: 1024, height: 1024 };
            }
        };

        window.triggerDownload = function(url) {
            parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: url }, '*');
        };

        // --- توابع نوار پیشرفت ---
        function startFakeProgress(targetSeconds) {
            clearInterval(fakeProgressInterval);
            const pb = document.getElementById('tv-progress-bar');
            if (!pb) return;
            let currentProg = 0;
            const intervalMs = 200; 
            const increment = 100 / (targetSeconds * 1000 / intervalMs);
            
            pb.style.width = '0%';
            fakeProgressInterval = setInterval(() => {
                currentProg += increment;
                if(currentProg > 98) {
                    clearInterval(fakeProgressInterval);
                    currentProg = 98;
                }
                pb.style.width = `${currentProg}%`;
            }, intervalMs);
        }

        function finishFakeProgress() {
            clearInterval(fakeProgressInterval);
            const pb = document.getElementById('tv-progress-bar');
            if(pb) pb.style.width = '100%';
        }

        // --- پردازش درخواست ---
        sendBtn.addEventListener('click', async () => {
            const userPrompt = promptInput.value.trim();
            if (!userPrompt) { promptInput.focus(); return; }

            const forbiddenWords = ["sex", "sexy", "porn", "nude", "erotic", "سکس", "سکسی", "پورن", "شهوانی", "برهنه", "لخت"];
            if (forbiddenWords.some(word => userPrompt.toLowerCase().includes(word))) {
                alert("متن ورودی شما حاوی کلمات نامناسب است. لطفاً آن را اصلاح کنید.");
                return;
            }

            if (userSubscriptionStatus !== 'paid') {
                try {
                    const response = await fetch('/api/check-image-credit', { 
                        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ fingerprint: userFingerprint }) 
                    });
                    const result = await response.json();
                    if (result.limit_reached) {
                        updateUIForSubscriptionStatus('free');
                        alert("محدودیت ساخت عکس امروز شما به پایان رسیده است.");
                        return;
                    }
                } catch (err) { alert("عدم ارتباط با سیستم اعتبار."); return; }
            }
            
            // پاک کردن تایمرهای اجرای قبلی در صورت وجود (درخواست جدید)
            if (activePollTimer) clearInterval(activePollTimer);
            if (activeTimeoutTimer) clearTimeout(activeTimeoutTimer);

            // قفل کردن دکمه و ورودی (بدون انیمیشن چرخان)
            sendBtn.disabled = true;
            promptInput.disabled = true;
            sendBtn.innerHTML = `در حال پردازش تصویر...`;
            
            // نمایش لودر پیشرفته
            imageResultContainer.innerHTML = `
                <div class="generator-container">
                    <div class="noise-layer"></div>
                    <div class="sketch-layer"></div>
                    <div class="building-layer"></div>
                    <div class="pixel-grid"></div>
                    <div class="particles"></div>
                    <div class="text-overlay">در حال پردازش و خلق تصویر...</div>
                    <div class="progress-bar" id="tv-progress-bar"></div>
                </div>
            `;

            // راه‌اندازی تایمر هشدار 2 دقیقه‌ای (120000 میلی‌ثانیه)
            activeTimeoutTimer = setTimeout(() => {
                if (isResultProcessed) return;
                
                const tvContainer = document.querySelector('.generator-container');
                if (tvContainer) {
                    let warnDiv = document.getElementById('timeout-warning-msg');
                    if (!warnDiv) {
                        warnDiv = document.createElement('div');
                        warnDiv.id = 'timeout-warning-msg';
                        warnDiv.style.cssText = "color: var(--danger-color); font-size: 0.95rem; font-weight: 700; text-align: center; margin-top: 15px; padding: 12px; background: rgba(229, 62, 62, 0.1); border-radius: 12px; border: 1px solid rgba(229, 62, 62, 0.3); width: 100%; max-width: 400px; animation: fadeIn 0.5s; line-height: 1.6;";
                        tvContainer.parentNode.insertBefore(warnDiv, tvContainer.nextSibling);
                    }
                    
                    if (selectedRatio === 'custom') {
                        warnDiv.innerHTML = '⏳ پردازش تصویر با اندازه دلخواه بیش از حد طولانی شد.<br>ممکن است اندازه وارد شده نامعتبر باشد یا سرور شلوغ است.<br>می‌توانید اندازه را تغییر داده و مجدداً تلاش کنید.';
                    } else {
                        warnDiv.innerHTML = '⏳ پردازش تصویر بیش از حد طولانی شد.<br>ممکن است سرور شلوغ باشد. می‌توانید مجدداً تلاش کنید.';
                    }
                    
                    // آزاد کردن دکمه بدون قطع کردن فرآیند ساخت قبلی
                    sendBtn.disabled = false;
                    promptInput.disabled = false;
                    sendBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg> تلاش مجدد`;
                }
            }, 120000);

            // راه‌اندازی تایمر پیشرفت
            const targetSeconds = selectedModelAction === 'generate-flux' ? 40 : 50;
            startFakeProgress(targetSeconds);

            isResultProcessed = false; 
            const currentModelName = selectedModelName;
            const currentRatioName = selectedRatioName;

            const dims = getDimensions(selectedRatio);
            let finalPrompt = userPrompt;

            try {
                const res = await fetch('/api/generate', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ 
                        prompt: finalPrompt,
                        width: dims.width, 
                        height: dims.height,
                        action_name: selectedModelAction 
                    })
                });
                
                const data = await res.json();
                
                if (data.status === 'success') {
                    activePollTimer = setInterval(async () => {
                        try {
                            const statusRes = await fetch(`/api/status/${data.run_id}`);
                            const statusData = await statusRes.json();
                            
                            if (statusData.status === 'ready' && !isResultProcessed) {
                                isResultProcessed = true;
                                clearInterval(activePollTimer);
                                clearTimeout(activeTimeoutTimer);
                                finishFakeProgress();
                                
                                if (userSubscriptionStatus === 'free') { 
                                    try { 
                                        await fetch('/api/use-image-credit', { 
                                            method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) 
                                        }); 
                                        checkFreeUserCredit(); 
                                    } catch (e) { console.error("Error using credit", e); } 
                                }

                                const absoluteUrl = window.location.origin + statusData.url;
                                imageResultContainer.innerHTML = `
                                    <div style="font-weight: bold; margin-bottom: 5px; color: var(--accent-primary); text-align:center;">تصویر شما آماده شد! امیدوارم لذت ببرید. 🎨</div>
                                    <div class="generated-image-box">
                                        <img src="${statusData.url}" alt="تصویر تولید شده توسط هوش مصنوعی" onload="this.scrollIntoView({behavior: 'smooth', block: 'center'})">
                                        
                                        <div class="image-meta">
                                            <span>
                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
                                                ${currentModelName}
                                            </span>
                                            <span>|</span>
                                            <span dir="ltr">
                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="3" y1="9" x2="21" y2="9"></line><line x1="9" y1="21" x2="9" y2="9"></line></svg>
                                                ${currentRatioName}
                                            </span>
                                        </div>

                                        <button class="download-btn" onclick="triggerDownload('${absoluteUrl}')">
                                            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                                            دانلود مستقیم تصویر
                                        </button>
                                    </div>
                                `;

                                // ذخیره فایل عکس در IndexedDB
                                try {
                                    const imgRes = await fetch(statusData.url);
                                    if(imgRes.ok) {
                                        const blob = await imgRes.blob();
                                        await saveToHistory(blob, finalPrompt, currentModelName, currentRatioName);
                                    }
                                } catch(e) {
                                    console.error('Failed to save history', e);
                                }
                                
                                sendBtn.disabled = false;
                                promptInput.disabled = false;
                                sendBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg> ساخت تصویر جادویی`;
                            }
                        } catch(e) { console.error('Polling error', e); }
                    }, 3500);
                } else {
                    clearInterval(fakeProgressInterval);
                    clearTimeout(activeTimeoutTimer);
                    imageResultContainer.innerHTML = `<div style="color: var(--danger-color); font-weight:bold; text-align:center;">خطا: متاسفانه در ارسال درخواست به سرور مشکلی پیش آمد.</div>`;
                    sendBtn.disabled = false; promptInput.disabled = false;
                    sendBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg> ساخت تصویر جادویی`;
                }
            } catch (e) {
                clearInterval(fakeProgressInterval);
                clearTimeout(activeTimeoutTimer);
                imageResultContainer.innerHTML = `<div style="color: var(--danger-color); font-weight:bold; text-align:center;">خطا در برقراری ارتباط با سرور.</div>`;
                sendBtn.disabled = false; promptInput.disabled = false;
                sendBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg> ساخت تصویر جادویی`;
            }
        });

        // --- بخش کمک‌یار پرامپت ---
        const promptHelperBtn = document.getElementById('promptHelperBtn');
        let activeModal = null; let currentPromptListPage = 1; const promptsPageSize = 10;
        
        const promptsData = { "lighting": [{"text": "Cinematic lighting", "translation": "نورپردازی سینمایی"}, {"text": "Soft lighting", "translation": "نورپردازی نرم"}, {"text": "Softbox lighting", "translation": "نورپردازی با سافت‌باکس"}, {"text": "Bright lighting", "translation": "نورپردازی روشن"}, {"text": "Ambient lighting", "translation": "نورپردازی محیطی"}, {"text": "Silhouetted", "translation": "سایه‌دار"}, {"text": "Flat lighting", "translation": "نورپردازی تخت"}, {"text": "Backlit Volumetric lighting", "translation": "نورپردازی حجمی پس‌زمینه"}], "special_lighting": [{"text": "Neon", "translation": "نئون"}, {"text": "Holographic", "translation": "هولوگرافیک"}, {"text": "Glow", "translation": "تابان"}, {"text": "Bioluminescent", "translation": "زیست‌تاب"}, {"text": "Rimlight", "translation": "نور حاشیه‌ای"}, {"text": "Silhouetted", "translation": "سایه‌دار"}], "details_quality": [{"text": "Ultra photoreal", "translation": "فوق‌العاده واقع‌گرایانه"}, {"text": "Intricate details", "translation": "جزئیات پیچیده"}, {"text": "Photorealistic", "translation": "فوتورئالیستی"}, {"text": "Hyper detailed", "translation": "بسیار جزئیات‌دار"}, {"text": "Ultra detailed", "translation": "فوق‌العاده جزئیات‌دار"}, {"text": "Extremely detailed", "translation": "بسیار پرجزئیات"}, {"text": "4K", "translation": "4K"}, {"text": "8K", "translation": "8K"}, {"text": "Super resolution", "translation": "وضوح فوق‌العاده"}, {"text": "High resolution", "translation": "وضوح بالا"}], "punk": [{"text": "Steampunk", "translation": "استیم‌پانک"}, {"text": "Cloudpunk", "translation": "کلودپانک"}, {"text": "Cyberpunk", "translation": "سایبرپانک"}, {"text": "Forestpunk", "translation": "فورست‌پانک"}, {"text": "Decopunk", "translation": "دکوپانک"}, {"text": "Atompunk", "translation": "اتم‌پانک"}, {"text": "Dieselpunk", "translation": "دیزل‌پانک"}, {"text": "Biopunk", "translation": "بیوپانک"}, {"text": "Dinopunk", "translation": "دینوپانک"}, {"text": "Cassettepunk", "translation": "کاست‌پانک"}, {"text": "Dollupunk", "translation": "دالاپانک"}, {"text": "Catholicpunk", "translation": "کاتولیک‌پانک"}, {"text": "Clockpunk", "translation": "کلاک‌پانک"}], "landscape": [{"text": "Surreal landscape", "translation": "منظره سورئال"}, {"text": "Unreal landscape", "translation": "منظره غیرواقعی"}, {"text": "Fantasy landscape", "translation": "منظره فانتزی"}, {"text": "Sci-fi landscape", "translation": "منظره علمی-تخیلی"}, {"text": "Desert landscape", "translation": "منظره بیابانی"}, {"text": "Tropical paradise", "translation": "بهشت گرمسیری"}, {"text": "Rainforest scenery", "translation": "منظره جنگل بارانی"}, {"text": "Expansive mountain range", "translation": "زنجیره کوهستانی گسترده"}], "colors": [{"text": "Retro colors", "translation": "رنگ‌های رترو"}, {"text": "Vivid colors", "translation": "رنگ‌های زنده"}, {"text": "Pastel colors", "translation": "رنگ‌های پاستلی"}, {"text": "Neon colors", "translation": "رنگ‌های نئونی"}, {"text": "Earthy tones", "translation": "رنگ‌های خاکی"}, {"text": "Primary colors", "translation": "رنگ‌های اصلی"}, {"text": "Monochromatic colors", "translation": "رنگ‌های تک‌رنگ"}, {"text": "Jewel tones", "translation": "رنگ‌های جواهری"}], "artist_style": [{"text": "in the style of Leonardo da Vinci", "translation": "به سبک لئوناردو داوینچی"}, {"text": "in the style of Michelangelo", "translation": "به سبک میکل‌آنجلو"}, {"text": "in the style of Rembrandt", "translation": "به سبک رامبراند"}, {"text": "in the style of Vermeer", "translation": "به سبک ورمیر"}, {"text": "in the style of Claude Monet", "translation": "به سبک کلود مونه"}, {"text": "in the style of Vincent van Gogh", "translation": "به سبک ونسان ون گوگ"}, {"text": "in the style of Pablo Picasso", "translation": "به سبک پابلو پیکاسو"}, {"text": "in the style of Salvador Dalí", "translation": "به سبک سالوادور دالی"}, {"text": "in the style of Andy Warhol", "translation": "به سبک اندی وارهول"}, {"text": "in the style of Frida Kahlo", "translation": "به سبک فریدا کالو"}], "iranian_art_identity": [{"text": "Persian Carpet Weaving style", "translation": "سبک قالی‌بافی ایرانی"}, {"text": "Persian Tilework style", "translation": "سبک کاشی‌کاری ایرانی"}, {"text": "Persian Miniature Painting style", "translation": "سبک نگارگری ایرانی"}, {"text": "Persian Calligraphy style", "translation": "سبک خوشنویسی ایرانی"}, {"text": "Traditional Persian Textiles", "translation": "منسوجات سنتی ایرانی"}, {"text": "Persian Woodcarving (Monabatkari)", "translation": "منبت‌کاری ایرانی"}, {"text": "Persian Mirrorwork (Aine-kari)", "translation": "آینه‌کاری ایرانی"}, {"text": "Termeh Weaving style", "translation": "سبک بافت ترمه"}, {"text": "Qajar art style", "translation": "سبک هنر قاجار"}], "iranian_set_design": [{"text": "Modern Tehran vibe", "translation": "حال و هوای مدرن تهران"}, {"text": "Esfahan architectural vibe", "translation": "حال و هوای معماری اصفهان"}, {"text": "Shiraz garden atmosphere", "translation": "فضای باغ شیراز"}, {"text": "Yazd desert city look", "translation": "نمای شهر کویری یزد"}, {"text": "Traditional Persian house interior", "translation": "فضای داخلی خانه سنتی ایرانی"}, {"text": "Persian empire aesthetic", "translation": "زیبایی‌شناسی امپراتوری پارس"}, {"text": "Sassanian art influence", "translation": "تحت تأثیر هنر ساسانی"}] };
        const promptCategoryNames = { "lighting": "نورپردازی 💡", "special_lighting": "نورپردازی خاص ✨", "details_quality": "جزئیات و کیفیت 🔍", "punk": "سبک‌های پانک 🎸", "landscape": "منظره 🌄", "colors": "رنگ‌ها 🎨", "artist_style": "به سبک هنرمندان 🖌️", "iranian_art_identity": "هویت هنری ایرانی 🏺", "iranian_set_design": "فضاسازی ایرانی 🏙️" };
        
        function createAlphaModal(title, bodyHtml, footerButtons = []) { if (activeModal) activeModal.remove(); const backdrop = document.createElement('div'); backdrop.className = 'alpha-modal-backdrop'; const modalContent = document.createElement('div'); modalContent.className = 'alpha-modal-content'; modalContent.innerHTML = `<div class="alpha-modal-header"><h2>${title}</h2><button class="alpha-modal-close-btn">×</button></div><div class="alpha-modal-body">${bodyHtml}</div>`; if (footerButtons.length > 0) { const footer = document.createElement('div'); footer.className = 'alpha-modal-footer'; footerButtons.forEach(btnConfig => { const button = document.createElement('button'); button.textContent = btnConfig.text; button.className = 'modal-action-button'; button.onclick = (e) => { e.preventDefault(); btnConfig.onclick(); }; footer.appendChild(button); }); modalContent.appendChild(footer); } backdrop.appendChild(modalContent); document.body.appendChild(backdrop); activeModal = backdrop; backdrop.querySelector('.alpha-modal-close-btn').onclick = () => activeModal.remove(); backdrop.onclick = (e) => { if (e.target === backdrop) activeModal.remove(); }; return modalContent; }
        
        function insertPromptIntoTextarea(text) { const currentValue = promptInput.value.trim(); promptInput.value = currentValue === '' ? text : `${currentValue}, ${text}`; promptInput.focus(); if (activeModal) { activeModal.remove(); activeModal = null; } }
        
        function showPromptCategoriesNotification() { let contentHtml = ''; for (const categoryKey in promptCategoryNames) { contentHtml += `<div class="prompt-category-item" data-category-key="${categoryKey}">${promptCategoryNames[categoryKey]}</div>`; } const modalElement = createAlphaModal('دسته‌بندی پرامپت‌ها', contentHtml); modalElement.querySelectorAll('.prompt-category-item').forEach(item => { item.addEventListener('click', function() { showPromptListNotification(this.dataset.categoryKey); }); }); }
        
        function showPromptListNotification(categoryKey) { currentPromptListPage = 1; const prompts = promptsData[categoryKey]; const categoryName = promptCategoryNames[categoryKey].replace(/<[^>]*>/g, ''); const totalPages = Math.ceil(prompts.length / promptsPageSize); const renderPage = () => { let listHtml = ''; const start = (currentPromptListPage - 1) * promptsPageSize; const end = start + promptsPageSize; prompts.slice(start, end).forEach(prompt => { listHtml += `<div class="prompt-item" data-prompt-text="${prompt.text}"><div class="prompt-text-container"><div class="prompt-text">${prompt.text}</div><div class="persian-translation">${prompt.translation}</div></div></div>`; }); let paginationHtml = ''; if (totalPages > 1) { paginationHtml = `<div class="pagination-container"><button class="pagination-button" id="prevPageBtn" ${currentPromptListPage === 1 ? 'disabled' : ''}> قبلی </button><span class="page-info">${currentPromptListPage} از ${totalPages}</span><button class="pagination-button" id="nextPageBtn" ${currentPromptListPage === totalPages ? 'disabled' : ''}> بعدی </button></div>`; } return listHtml + paginationHtml; }; const modalElement = createAlphaModal(`پرامپت‌های ${categoryName}`, renderPage(), [{ text: 'بازگشت به دسته‌بندی‌ها', onclick: showPromptCategoriesNotification }]); const updateAndRebind = () => { modalElement.querySelector('.alpha-modal-body').innerHTML = renderPage(); bindListEvents(); }; const bindListEvents = () => { modalElement.querySelectorAll('.prompt-item').forEach(item => { item.onclick = () => insertPromptIntoTextarea(item.dataset.promptText); }); const prevBtn = modalElement.querySelector('#prevPageBtn'); const nextBtn = modalElement.querySelector('#nextPageBtn'); if (prevBtn) prevBtn.onclick = () => { if (currentPromptListPage > 1) { currentPromptListPage--; updateAndRebind(); }}; if (nextBtn) nextBtn.onclick = () => { if (currentPromptListPage < totalPages) { currentPromptListPage++; updateAndRebind(); }}; }; bindListEvents(); }

        promptHelperBtn.addEventListener('click', (e) => { e.preventDefault(); showPromptCategoriesNotification(); });

        // انیمیشن شبکه عصبی هدر
        document.addEventListener('DOMContentLoaded', () => {
            const canvas = document.getElementById('neural-network-canvas');
            if(!canvas) return; const header = canvas.parentElement; const ctx = canvas.getContext('2d');
            let particles = []; const particleCount = 20; const maxDistance = 100;
            const particleColor = '#4A6CFA'; const lineColor = '#8A94A6';
            function resizeCanvas() { canvas.width = header.clientWidth; canvas.height = header.clientHeight; init(); }
            class Particle { constructor() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.vx = (Math.random() - 0.5) * 0.3; this.vy = (Math.random() - 0.5) * 0.3; this.radius = 1.2; } update() { this.x += this.vx; this.y += this.vy; if (this.x < 0 || this.x > canvas.width) this.vx *= -1; if (this.y < 0 || this.y > canvas.height) this.vy *= -1; } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = particleColor; ctx.fill(); } }
            function init() { particles = []; for (let i = 0; i < particleCount; i++) { particles.push(new Particle()); } }
            function connectParticles() { for (let i = 0; i < particles.length; i++) { for (let j = i + 1; j < particles.length; j++) { const dx = particles[i].x - particles[j].x; const dy = particles[i].y - particles[j].y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < maxDistance) { ctx.beginPath(); ctx.moveTo(particles[i].x, particles[i].y); ctx.lineTo(particles[j].x, particles[j].y); ctx.strokeStyle = lineColor; ctx.lineWidth = 0.2; ctx.globalAlpha = 1 - distance / maxDistance; ctx.stroke(); } } } ctx.globalAlpha = 1; }
            function animate() { if(!ctx) return; ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(particle => { particle.update(); particle.draw(); }); connectParticles(); requestAnimationFrame(animate); }
            window.addEventListener('resize', resizeCanvas); resizeCanvas(); animate();
        });
    </script>
</body>
</html>