File size: 59,213 Bytes
a7a7dd0
 
 
 
 
195bdde
a7a7dd0
bbd4657
0fe4746
 
 
 
 
 
 
 
 
 
 
 
a7a7dd0
0fe4746
e3f9a6f
0fe4746
e3f9a6f
 
0fe4746
 
e3f9a6f
0fe4746
 
 
 
 
 
 
 
bbd4657
 
0fe4746
 
 
 
 
 
bbd4657
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3f9a6f
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2a9a42
7d8e006
e8e5e61
 
f2a9a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fe4746
 
 
 
 
 
 
 
 
 
195bdde
0fe4746
f2a9a42
a7a7dd0
 
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
d2c0e44
0fe4746
 
 
 
 
 
 
e3f9a6f
 
0fe4746
 
 
 
 
 
 
 
e3f9a6f
0fe4746
a7a7dd0
e3f9a6f
 
0fe4746
 
 
 
 
 
 
 
 
 
d2c0e44
0fe4746
 
 
 
 
 
 
e3f9a6f
 
0fe4746
 
 
 
 
 
 
 
e3f9a6f
0fe4746
a7a7dd0
 
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7a7dd0
 
0fe4746
 
 
 
 
 
 
 
 
 
a7a7dd0
 
 
0fe4746
a7a7dd0
 
0fe4746
 
 
 
e3f9a6f
f2a9a42
 
 
 
 
 
 
 
 
 
 
1144230
f2a9a42
 
 
 
 
 
 
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7a7dd0
 
 
 
e3f9a6f
44c217a
c6e11a8
a7a7dd0
e3f9a6f
 
 
f2a9a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc6a8a2
f2a9a42
064442f
 
f2a9a42
e8e5e61
f2a9a42
064442f
f2a9a42
064442f
e8e5e61
 
 
 
f2a9a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2a9a42
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbd4657
 
 
 
0fe4746
bbd4657
 
 
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
a7a7dd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fe4746
 
a7a7dd0
 
0fe4746
 
 
 
 
 
 
 
a7a7dd0
0fe4746
a7a7dd0
0fe4746
 
a7a7dd0
 
0fe4746
a7a7dd0
e3f9a6f
a7a7dd0
 
 
 
0fe4746
 
a7a7dd0
0fe4746
 
 
 
e3f9a6f
0fe4746
 
e3f9a6f
 
 
a7a7dd0
 
 
 
 
 
 
 
0fe4746
a7a7dd0
 
 
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
c6e11a8
0fe4746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6e11a8
 
 
 
 
 
 
 
 
 
 
 
 
bf00ad5
c6e11a8
 
 
 
 
 
 
 
 
 
 
 
 
 
e3f9a6f
c6e11a8
 
 
 
e3f9a6f
 
0fe4746
e3f9a6f
 
 
 
 
 
 
0fe4746
e3f9a6f
0fe4746
 
e3f9a6f
 
 
 
 
0fe4746
e3f9a6f
 
a7a7dd0
 
bbd4657
e3f9a6f
44c217a
a7a7dd0
 
44c217a
 
 
 
a7a7dd0
e3f9a6f
 
44c217a
e3f9a6f
c6e11a8
 
 
 
e3f9a6f
 
 
0fe4746
e3f9a6f
f2a9a42
 
 
 
 
e3f9a6f
 
 
 
44c217a
e3f9a6f
44c217a
e3f9a6f
 
a7a7dd0
44c217a
a7a7dd0
44c217a
a7a7dd0
 
44c217a
 
a7a7dd0
e3f9a6f
 
0fe4746
e3f9a6f
 
497b630
0fe4746
e3f9a6f
 
 
4144338
e3f9a6f
 
 
0fe4746
c6e11a8
 
 
 
e3f9a6f
 
 
a7a7dd0
 
e3f9a6f
4144338
a7a7dd0
4144338
a7a7dd0
 
 
 
 
 
 
 
0fe4746
a7a7dd0
0fe4746
a7a7dd0
 
 
f2a9a42
 
 
 
 
 
 
 
 
1030414
 
 
 
c6e11a8
 
 
 
44c217a
 
1030414
e3f9a6f
 
0fe4746
c6e11a8
 
 
 
 
a7a7dd0
497b630
e3f9a6f
a7a7dd0
497b630
e3f9a6f
a7a7dd0
497b630
a7a7dd0
90cdedc
 
 
 
e3f9a6f
 
a7a7dd0
 
 
 
 
e3f9a6f
a7a7dd0
 
 
 
 
 
 
 
 
 
 
0fe4746
a7a7dd0
 
e3f9a6f
0fe4746
e3f9a6f
 
 
0fe4746
 
 
 
 
 
 
e3f9a6f
0fe4746
 
 
 
 
e50a89c
0fe4746
e3f9a6f
 
e50a89c
 
e3f9a6f
e50a89c
e3f9a6f
 
e50a89c
e3f9a6f
 
 
 
0fe4746
e3f9a6f
 
 
 
 
 
0fe4746
e3f9a6f
a7a7dd0
 
0fe4746
f2a9a42
 
 
 
 
 
 
 
 
 
a7a7dd0
 
 
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
<!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>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800;900&display=swap');

        :root {
            --app-font: 'Vazirmatn', sans-serif; --app-bg: #F8F9FC; --panel-bg: #FFFFFF;
            --panel-border: #EAEFF7; --input-bg: #F6F8FB; --input-border: #E1E7EF;
            --text-primary: #1A202C; --text-secondary: #626F86; --text-tertiary: #8A94A6;
            --accent-primary: #4A6CFA; --accent-primary-hover: #3553D6; --accent-primary-glow: rgba(74, 108, 250, 0.25);
            --accent-secondary: #0FD4A8; --accent-secondary-hover: #0DA986; --accent-secondary-glow: rgba(15, 212, 168, 0.2);
            --shadow-sm: 0 1px 2px 0 rgba(26, 32, 44, 0.03); --shadow-md: 0 4px 6px -1px rgba(26, 32, 44, 0.05), 0 2px 4px -2px rgba(26, 32, 44, 0.04);
            --shadow-lg: 0 10px 15px -3px rgba(26, 32, 44, 0.06), 0 4px 6px -4px rgba(26, 32, 44, 0.05);
            --shadow-xl: 0 20px 25px -5px rgba(26, 32, 44, 0.07), 0 8px 10px -6px rgba(26, 32, 44, 0.05);
            --radius-card: 24px; --radius-btn: 14px; --radius-input: 12px;
            --transition-smooth: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
        }

        @keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes rotate-loader-orbital { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes orbit-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes satellite-pulse-1 { from { transform: scale(0.7) translateX(-50%); opacity: 0.6; } to { transform: scale(1.1) translateX(-50%); opacity: 1; } }
        @keyframes satellite-pulse-2 { from { transform: scale(0.7) translateY(-50%); opacity: 0.6; } to { transform: scale(1.1) translateY(-50%); opacity: 1; } }
        @keyframes float { 0%, 100% { transform: translateY(0px); } 50% { transform: translateY(-10px); } }
        @keyframes slideInUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }

        html { scroll-behavior: smooth; }
        body {
            font-family: var(--app-font); direction: rtl; background-color: var(--app-bg);
            color: var(--text-primary); font-size: 16px; line-height: 1.8; margin: 0;
            padding: 2.5rem 1rem; min-height: 100vh; display: flex; justify-content: center;
            align-items: flex-start; overflow-x: hidden;
            background-image: radial-gradient(var(--text-tertiary) 0.5px, transparent 0.5px);
            background-size: 20px 20px; background-position: -10px -10px;
        }
        .app-container { max-width: 680px; width: 95%; margin: 0 auto; }

        .app-header { padding: 0.5rem 0 2.5rem 0; text-align: center; margin-bottom: 1.5rem; animation: fadeIn 0.8s 0.2s ease-out backwards; }
        .app-header h1 { font-size: 2.5em; font-weight: 900; margin: 0 0 0.8rem 0; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: -1px; }
        .app-header p { font-size: 1.05em; color: var(--text-secondary); margin-top: 0; opacity: 0.9; font-weight: 400; line-height: 1.7; }
        
        .main-content { position:relative; padding: 3rem; background-color: var(--panel-bg); border-radius: var(--radius-card); box-shadow: var(--shadow-xl); border: 1px solid var(--panel-border); animation: fadeIn 0.8s 0.4s ease-out backwards; }
        
        .form-group { margin-bottom: 2.2rem; }
        label { display: flex; align-items: center; gap: 0.75rem; font-weight: 700; color: var(--text-primary); font-size: 1.1em; margin-bottom: 1rem; }
        label .label-icon { width: 24px; height: 24px; color: var(--accent-primary); }
        
        .generate-btn { display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%; padding: 1.1rem 1.5rem; font-size: 1.25em; 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 12px -3px var(--accent-primary-glow), 0 6px 12px -3px var(--accent-secondary-glow); }
        .generate-btn:hover:not(:disabled) { transform: translateY(-5px) scale(1.02); box-shadow: 0 8px 20px -4px var(--accent-primary-glow), 0 8px 20px -4px var(--accent-secondary-glow); }
        .generate-btn:disabled { background: var(--text-tertiary); cursor: not-allowed; box-shadow: none; color: var(--text-secondary); transform: none; }
        .generate-btn .spinner { width: 20px; height: 20px; border: 3px solid rgba(255, 255, 255, 0.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.8s linear infinite; display: none;}
        
        .upload-area { border: 2px dashed var(--input-border); border-radius: var(--radius-input); padding: 2rem; text-align: center; cursor: pointer; transition: var(--transition-smooth); background-color: var(--input-bg); }
        .upload-area:hover, .upload-area.drag-over { border-color: var(--accent-primary); background-color: #fff; box-shadow: 0 0 15px var(--accent-primary-glow); }
        .upload-icon svg { width: 48px; height: 48px; color: var(--accent-primary); margin-bottom: 1rem; stroke-width: 1.5; opacity: 0.8; }
        .upload-area p { margin: 0; color: var(--text-secondary); font-weight: 500; }
        .upload-area p strong { color: var(--text-primary); }
        
        .file-preview-el { display: none; align-items: center; justify-content: space-between; padding: 1rem 1.2rem; background-color: var(--input-bg); border-radius: var(--radius-input); margin-top: 1rem; animation: fadeIn 0.3s; border: 1px solid var(--panel-border); }
        .file-info-el { display: flex; align-items: center; gap: 1rem; overflow: hidden; }
        .file-info-el img { width: 60px; height: 60px; border-radius: 12px; object-fit: cover; border: 2px solid var(--panel-border); flex-shrink: 0; }
        .file-info-el span { font-weight: 600; color: var(--text-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .remove-file-btn { background: none; border: none; color: var(--text-tertiary); cursor: pointer; font-size: 1.8rem; transition: all 0.2s; flex-shrink: 0; line-height: 1; padding: 0 0.5rem; }
        .remove-file-btn:hover { color: #e53e3e; transform: scale(1.1); }

        .output-section { margin-top: 3rem; display: flex; align-items: center; justify-content: center; flex-direction: column; min-height: 220px; position: relative; box-sizing: border-box; padding: 2rem; background-color: var(--input-bg); border-radius: var(--radius-card); border: 2px dashed var(--input-border); box-shadow: var(--shadow-sm) inset; transition: var(--transition-smooth); }
        .output-section.has-content { background-color: var(--panel-bg); border: 1px solid var(--panel-border); box-shadow: var(--shadow-lg); padding: 1rem; min-height: auto; }
        .status-message { font-weight: 500; color: var(--text-secondary); text-align: center; font-size: 1.1em; line-height: 1.9; }
        
        .loading-animation-wrapper { display: none; flex-direction: column; align-items: center; justify-content: center; gap: 1.8rem; width: 100%; }
        .orbital-loader { width: 110px; height: 110px; position: relative; animation: rotate-loader-orbital 10s linear infinite; }
        .orbit { position: absolute; top: 50%; left: 50%; border: 2px dashed rgba(74, 108, 250, 0.35); border-radius: 50%; transform-origin: center center; }
        .orbit:nth-child(1) { width: 65px; height: 65px; margin: -32.5px 0 0 -32.5px; animation: orbit-spin 3.8s linear infinite; }
        .orbit:nth-child(2) { width: 95px; height: 95px; margin: -47.5px 0 0 -47.5px; animation: orbit-spin 4.8s linear infinite reverse; }
        .orbit .satellite { position: absolute; width: 10px; height: 10px; border-radius: 50%; background-color: var(--accent-primary); box-shadow: 0 0 8px var(--accent-primary), 0 0 12px var(--accent-secondary); }
        .orbit:nth-child(1) .satellite { top: 50%; left: -5px; background-color: var(--accent-secondary); animation: satellite-pulse-2 1.4s 0.2s ease-in-out infinite alternate; }
        .orbit:nth-child(2) .satellite { bottom: -5px; right: 50%; animation: satellite-pulse-1 1.4s 0.4s ease-in-out infinite alternate;}
        .loading-text { font-size: 1.2em; font-weight: 700; color: var(--text-primary); text-align: center; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        
        #result-content { display: none; width: 100%; text-align: center; animation: fadeIn 0.5s ease-out; }
        #result-content h2 { color: var(--text-primary); border-bottom: 2px solid var(--panel-border); padding-bottom: 1rem; margin-bottom: 1rem; font-size: 1.5em; }
        #result-image { max-width: 100%; border-radius: var(--radius-card); border: 2px solid var(--accent-secondary); padding: 5px; box-shadow: var(--shadow-lg); cursor: pointer; transition: transform 0.2s ease; }
        #result-image:hover { transform: scale(1.02); }
        
        #result-content a.download-btn {
            display: none; align-items: center; justify-content: center; gap: 10px;
            margin-top: 1.5rem; padding: 0.9rem 1.8rem; font-size: 1.1em; font-weight: 700;
            background: linear-gradient(95deg, var(--accent-primary) 0%, var(--accent-secondary) 100%);
            color: #fff; border: none; border-radius: var(--radius-btn); cursor: pointer;
            transition: var(--transition-smooth);
            box-shadow: 0 5px 10px -2px var(--accent-primary-glow), 0 5px 10px -2px var(--accent-secondary-glow);
            text-decoration: none;
        }
        #result-content a.download-btn:hover {
            transform: translateY(-4px) scale(1.03);
            box-shadow: 0 7px 18px -3px var(--accent-primary-glow), 0 7px 18px -3px var(--accent-secondary-glow);
        }
        #result-content a.download-btn svg { width: 20px; height: 20px; }

        .status-message.error { color: #c53030; font-weight: 600; }

        :root {
            --guide-bg: rgba(255, 255, 255, 0.98);
            --guide-border: rgba(102, 126, 234, 0.2);
            --guide-text-title: #2d3748;
            --guide-text-body: #4a5568;
            --guide-accent: #667eea;
            --primary-gradient-guide: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient-guide: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
            --radius-md-guide: 12px;
            --radius-lg-guide: 20px;
        }
        .ip-reset-guide-container {
            text-align: right; background: var(--guide-bg); backdrop-filter: blur(10px); padding: 40px; border-radius: var(--radius-lg-guide);
            box-shadow: var(--shadow-xl); border: 1px solid var(--guide-border); animation: slideInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) both;
            width: 100%; position: relative; overflow: hidden; box-sizing: border-box;
        }
        .ip-reset-guide-container::before {
            content: ''; position: absolute; top: 0; left: 0; right: 0; height: 5px; background: var(--primary-gradient-guide);
        }
        .guide-header { display: flex; align-items: center; margin-bottom: 30px; }
        .guide-header-icon { width: 60px; height: 60px; margin-left: 20px; animation: float 3s ease-in-out infinite; }
        .guide-header h2 { font-size: 1.5rem; color: var(--guide-text-title); font-weight: 700; margin: 0; }
        .guide-header p { color: var(--guide-text-body); font-size: 0.8rem; margin-top: 5px; margin-bottom: 0; }
        .guide-content { font-size: 0.95rem; color: var(--guide-text-body); line-height: 1.8; }
        .info-card { background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border: 1px solid rgba(102, 126, 234, 0.2); border-radius: var(--radius-md-guide); padding: 20px; margin: 20px 0; position: relative; overflow: hidden; }
        .info-card p { font-size: 0.85rem; line-height: 1.7; margin: 0; }
        .info-card::before { content: ''; position: absolute; top: 0; right: 0; width: 4px; height: 100%; background: var(--primary-gradient-guide); }
        .info-card-header { display: flex; align-items: center; margin-bottom: 12px; }
        .info-card-icon { width: 24px; height: 24px; margin-left: 12px; }
        .info-card-title { font-weight: 600; color: var(--guide-text-title); font-size: 1rem; }
        .summary-section { margin-top: 25px; padding: 20px; border-radius: var(--radius-md-guide); background: linear-gradient(135deg, #56ab2f15 0%, #a8e06315 100%); border: 1px solid rgba(86, 171, 47, 0.2); position: relative; overflow: hidden; }
        .summary-section::before { content: ''; position: absolute; top: 0; right: 0; width: 4px; height: 100%; background: var(--success-gradient-guide); }
        .summary-header { display: flex; align-items: center; margin-bottom: 10px; }
        .summary-icon { width: 24px; height: 24px; margin-left: 10px; }
        .summary-title { font-weight: 600; color: #2f5a33; font-size: 1rem; }
        .summary-text { color: #2f5a33; font-size: 0.9rem; line-height: 1.7; }
        .video-button-container { text-align: center; margin: 25px 0 10px 0; }
        .elegant-video-button { display: inline-flex; align-items: center; justify-content: center; padding: 7px 18px; background-color: #f0f2f5; color: var(--guide-accent); border: 1px solid #e2e8f0; text-decoration: none; border-radius: var(--radius-md-guide); font-weight: 600; font-size: 0.8rem; cursor: pointer; font-family: inherit; transition: all 0.3s ease; box-shadow: var(--shadow-sm); }
        .elegant-video-button:hover { background: var(--primary-gradient-guide); color: white; border-color: transparent; transform: translateY(-2px); box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3); }
        .elegant-video-button-icon { width: 16px; height: 16px; margin-left: 8px; fill: currentColor; }
        .guide-actions { display: flex; gap: 15px; margin-top: 30px; padding-top: 25px; border-top: 1px solid #e2e8f0; }
        .action-button { padding: 14px 24px; border: none; border-radius: var(--radius-md-guide); font-size: 0.95rem; font-weight: 600; cursor: pointer; flex: 1; transition: var(--transition-smooth); position: relative; overflow: hidden; display: flex; align-items: center; justify-content: center; }
        .action-button-icon { width: 20px; height: 20px; margin-right: 0; margin-left: 8px; }
        .back-button { background: white; color: var(--guide-text-body); border: 2px solid #e2e8f0; flex: 0.4; }
        .back-button:hover { background: #f7fafc; border-color: var(--guide-accent); transform: translateY(-2px); box-shadow: var(--shadow-md); }
        .retry-button { background: var(--primary-gradient-guide); color: white; flex: 0.6; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3); }
        .retry-button:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4); }

        .fullscreen-modal {
            display: none; position: fixed; z-index: 1000; top: 0; left: 0;
            width: 100%; height: 100%; background-color: rgba(26, 32, 44, 0.9);
            justify-content: center; align-items: center; animation: fadeIn 0.3s ease;
        }
        .fullscreen-image {
            max-width: 90%; max-height: 90%; object-fit: contain;
            border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        }
        .close-fullscreen {
            position: absolute; top: 20px; right: 35px; color: #fff; font-size: 40px;
            font-weight: bold; cursor: pointer; transition: color 0.2s, transform 0.2s;
        }
        .close-fullscreen:hover { color: var(--text-tertiary); transform: scale(1.1); }

        /* --- استایل‌های جدید مودال و نشانگر عضویت --- */
        #subscription-status-badge { display: none; padding: 6px 16px; border-radius: 20px; font-size: 0.9em; font-weight: 700; margin-top: 1.25rem; letter-spacing: 0.5px; animation: fadeIn 0.6s 0.5s ease-out backwards; user-select: none; transition: transform 0.2s ease, opacity 0.2s ease; }
        #subscription-status-badge.free-badge { background: linear-gradient(45deg, #6c757d, #495057); color: white; box-shadow: 0 4px 10px rgba(108, 117, 125, 0.3); cursor: pointer; }
        #subscription-status-badge.free-badge:hover { transform: scale(1.05); opacity: 0.95; }
        #subscription-status-badge.paid-badge { background: linear-gradient(45deg, #FFC107, #ffca2c); color: #333; box-shadow: 0 4px 10px rgba(255, 193, 7, 0.3); }

        .modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(26, 32, 44, 0.5); backdrop-filter: blur(8px); z-index: 1000; animation: modal-fade-in 0.3s ease-out; }
        .modal-overlay.active { display: flex; align-items: center; justify-content: center; }
        .modal-content { background-color: var(--panel-bg); padding: 2.5rem; border-radius: var(--radius-card); box-shadow: var(--shadow-xl); border: 1px solid var(--panel-border); width: 90%; max-width: 450px; text-align: center; position: relative; animation: modal-zoom-in 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        .modal-icon { width: 60px; height: 60px; margin: 0 auto 1.5rem; background: rgba(74, 108, 250, 0.1); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--accent-primary); }
        .modal-icon svg { width: 32px; height: 32px; }
        .modal-title { font-size: 1.3rem; font-weight: 700; color: var(--text-primary); margin: 0 0 1rem 0; }
        .modal-text { font-size: 0.95rem; color: var(--text-secondary); line-height: 1.7; margin: 0 0 2rem 0; }
        .modal-buttons { display: flex; gap: 1rem; width: 100%; }
        .modal-button { flex: 1; padding: 0.8rem 1.5rem; background: var(--accent-primary); color: white; border: none; border-radius: var(--radius-btn); font-family: var(--app-font); font-weight: 600; font-size: 1rem; cursor: pointer; transition: var(--transition-smooth); }
        .modal-button:hover { background: var(--accent-primary-hover); transform: translateY(-2px); }
        .modal-button.secondary { background: var(--input-bg); color: var(--text-secondary); border: 1px solid var(--input-border); }
        .modal-button.secondary:hover { background-color: var(--panel-border); color: var(--text-primary); }

        @keyframes modal-fade-in { from { opacity: 0; } to { opacity: 1; } }
        @keyframes modal-zoom-in { from { transform: scale(0.9); } to { transform: scale(1); } }

        @media (max-width: 600px) {
            body { padding: 1.5rem 1rem; }
            .main-content { padding: 1.5rem; }
            .app-header h1 { font-size: 2em; }
        }
    </style>
</head>
<body>
    <div class="app-container">
        <header class="app-header">
            <h1>تعویض چهره آلفا</h1>
            <p>چهره جدید را آپلود کرده و آن را با حفظ ژست و نورپردازی به صورت یکپارچه بر روی بدن و محیط تصویر دوم قرار دهید.</p>
            <div id="subscription-status-badge" style="display:none; margin-top: 1.25rem;"></div>
        </header>

        <main class="main-content" id="main-content">
            <form onsubmit="return false;">
                
                <!-- بارگذاری تصویر اول (چهره مرجع) -->
                <div class="form-group">
                    <label>
                        <span class="label-icon">
                            <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>
                        </span>
                        تصویر اول (تصویر شما/ Reference Face)
                    </label>
                    <label class="upload-area" id="upload-area-ref">
                        <div class="upload-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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="17 8 12 3 7 8"></polyline>
                                <line x1="12" y1="3" x2="12" y2="15"></line>
                            </svg>
                        </div>
                        <p>عکس چهره جدید را اینجا بکشید یا برای <strong>انتخاب فایل</strong> کلیک کنید</p>
                    </label>
                    <input type="file" id="reference_face" accept="image/*" style="display: none;">
                    
                    <div id="ref-file-preview" class="file-preview-el">
                        <div class="file-info-el">
                            <img id="ref-image-preview" src="#" alt="پیش‌نمایش چهره" />
                            <span id="ref-file-name"></span>
                        </div>
                        <button type="button" class="remove-file-btn" id="remove-ref-btn" title="حذف فایل">×</button>
                    </div>
                </div>

                <!-- بارگذاری تصویر دوم (بدنه و هدف اصلی) -->
                <div class="form-group">
                    <label>
                        <span class="label-icon">
                            <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>
                        </span>
                        تصویر دوم (تصویر مدل/ Target Image)
                    </label>
                    <label class="upload-area" id="upload-area-target">
                        <div class="upload-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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="17 8 12 3 7 8"></polyline>
                                <line x1="12" y1="3" x2="12" y2="15"></line>
                            </svg>
                        </div>
                        <p>عکس بدن و پس‌زمینه را اینجا بکشید یا برای <strong>انتخاب فایل</strong> کلیک کنید</p>
                    </label>
                    <input type="file" id="target_image" accept="image/*" style="display: none;">
                    
                    <div id="target-file-preview" class="file-preview-el">
                        <div class="file-info-el">
                            <img id="target-image-preview" src="#" alt="پیش‌نمایش هدف" />
                            <span id="target-file-name"></span>
                        </div>
                        <button type="button" class="remove-file-btn" id="remove-target-btn" title="حذف فایل">×</button>
                    </div>
                </div>
                
                <button type="submit" id="submit-btn" class="generate-btn">
                    <span class="btn-text">✨ تعویض چهره کن!</span>
                    <div class="spinner"></div>
                </button>
            </form>

            <div id="output-section" class="output-section">
                <div id="status-message" class="status-message">نتیجه تعویض چهره شما در اینجا نمایش داده خواهد شد.</div>
                
                <div id="loading-animation" class="loading-animation-wrapper">
                    <div class="orbital-loader">
                        <div class="orbit"><div class="satellite"></div></div>
                        <div class="orbit"><div class="satellite"></div></div>
                    </div>
                    <p id="loading-text" class="loading-text"></p>
                </div>

                <div id="result-content">
                    <h2>تصویر تولید شده نهایی:</h2>
                    <img id="result-image" src="#" alt="تصویر تعویض چهره شده" />
                    <a href="#" id="download-btn" class="download-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="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>
                        <span>دانلود تصویر</span>
                    </a>
                </div>
            </div>
        </main>
    </div>

    <div id="fullscreen-modal" class="fullscreen-modal">
        <span id="close-fullscreen" class="close-fullscreen">&times;</span>
        <img id="fullscreen-image" class="fullscreen-image" src="#" alt="نمایش تمام صفحه">
    </div>

    <!-- مودال اتمام اعتبار روزانه برای کاربران رایگان -->
    <div class="modal-overlay" id="limit-modal">
        <div class="modal-content">
            <div class="modal-icon" style="color: #FFC107; background: rgba(255, 193, 7, 0.1);">
                <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">
                    <circle cx="12" cy="12" r="10"></circle>
                    <line x1="12" y1="9" x2="12" y2="13"></line>
                    <line x1="12" y1="17" x2="12.01" y2="17"></line>
                </svg>
            </div>
            <h3 class="modal-title">محدودیت استفاده روزانه</h3>
            <p class="modal-text">کاربر گرامی، در نسخه رایگان شما مجاز به انجام روزانه <b>۱ تغییر چهره</b> هستید.<br><br>برای استفاده نامحدود، از این بخش و همه بخش های برنامه می‌توانید حساب خود را ارتقا دهید.</p>
            <div class="modal-buttons">
                <button class="modal-button secondary" id="close-limit-modal">بستن</button>
                <button class="modal-button" id="upgrade-limit-modal" style="background: linear-gradient(95deg, var(--accent-secondary) 0%, var(--accent-primary) 100%);">⭐️ ارتقا به نسخه نامحدود</button>
            </div>
        </div>
    </div>

    <script type="module">
        const mainContent = document.getElementById('main-content');
        
        const referenceFaceInput = document.getElementById('reference_face');
        const uploadAreaRef = document.getElementById('upload-area-ref');
        const refFilePreview = document.getElementById('ref-file-preview');
        const refImagePreview = document.getElementById('ref-image-preview');
        const refFileNameSpan = document.getElementById('ref-file-name');
        const removeRefBtn = document.getElementById('remove-ref-btn');

        const targetImageInput = document.getElementById('target_image');
        const uploadAreaTarget = document.getElementById('upload-area-target');
        const targetFilePreview = document.getElementById('target-file-preview');
        const targetImagePreview = document.getElementById('target-image-preview');
        const targetFileNameSpan = document.getElementById('target-file-name');
        const removeTargetBtn = document.getElementById('remove-target-btn');

        const submitBtn = document.getElementById('submit-btn');
        const btnText = submitBtn.querySelector('.btn-text');
        const btnSpinner = submitBtn.querySelector('.spinner');
        const outputSection = document.getElementById('output-section');
        const statusMessage = document.getElementById('status-message');
        const loadingAnimation = document.getElementById('loading-animation');
        const loadingText = document.getElementById('loading-text');
        const resultContent = document.getElementById('result-content');
        const resultImage = document.getElementById('result-image');
        const downloadBtn = document.getElementById('download-btn');
        const fullscreenModal = document.getElementById('fullscreen-modal');
        const fullscreenImage = document.getElementById('fullscreen-image');
        const closeFullscreenBtn = document.getElementById('close-fullscreen');
        
        let refFile = null;
        let targetFile = null;
        let currentRunId = '';
        let pollInterval = null;
        let emptyActionCounter = 0;
        let activePollRunId = '';
        let timeoutTimer = null;

        let computedWidth = 1024;
        let computedHeight = 1024;

        // متغیرهای هویت‌سنجی و وضعیت پرداخت
        let userSubscriptionStatus = 'free';
        let userFingerprint = 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_' + 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 subscriptionBadge = document.getElementById('subscription-status-badge');
            if (!subscriptionBadge) return;

            if (status === 'paid') {
                subscriptionBadge.innerHTML = 'نسخه نامحدود';
                subscriptionBadge.className = 'paid-badge';
                subscriptionBadge.onclick = null; // برای نسخه نامحدود کلیک غیرفعال است
                subscriptionBadge.style.cursor = 'default';
            } else {
                subscriptionBadge.innerHTML = 'نسخه رایگان (ارتقا)';
                subscriptionBadge.className = 'free-badge';
                subscriptionBadge.style.cursor = 'pointer';
                
                // قابلیت کلیک روی کل سطح کپسول/دکمه برای ارتقا به نسخه نامحدود
                subscriptionBadge.onclick = (e) => {
                    e.preventDefault();
                    parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM' }, '*');
                };
            }
            subscriptionBadge.style.display = 'inline-block';
        }

        // دریافت تعداد استفاده‌های روز جاری
        function getDailyUsage() {
            if (!userFingerprint) return 0;
            const today = new Date().toDateString();
            const storedDate = localStorage.getItem(`swap_date_${userFingerprint}`);
            if (storedDate !== today) {
                return 0;
            }
            return parseInt(localStorage.getItem(`swap_count_${userFingerprint}`) || '0', 10);
        }

        // افزایش شمارنده استفاده روزانه
        function incrementDailyUsage() {
            if (!userFingerprint) return;
            const today = new Date().toDateString();
            localStorage.setItem(`swap_date_${userFingerprint}`, today);
            const currentUsage = getDailyUsage();
            localStorage.setItem(`swap_count_${userFingerprint}`, (currentUsage + 1).toString());
        }

        // رویدادهای مودال اتمام اعتبار روزانه
        document.getElementById('close-limit-modal').addEventListener('click', () => {
            document.getElementById('limit-modal').classList.remove('active');
        });
        document.getElementById('upgrade-limit-modal').addEventListener('click', () => {
            parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM' }, '*');
        });
        document.getElementById('limit-modal').addEventListener('click', (e) => {
            if (e.target === document.getElementById('limit-modal')) {
                document.getElementById('limit-modal').classList.remove('active');
            }
        });

        // دریافت ارتباطات از سمت والد
        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');
                }
            }
        });

        const GPU_QUOTA_ERROR_HTML = `
        <div class="ip-reset-guide-container">
            <div class="guide-header"><svg class="guide-header-icon" viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <defs><lineargradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" style="stop-color: #667eea; stop-opacity: 1;"></stop><stop offset="100%" style="stop-color: #764ba2; stop-opacity: 1;"></stop></lineargradient></defs> <circle cx="50" cy="50" r="45" fill="url(#grad1)" opacity="0.1"></circle><circle cx="50" cy="50" r="35" fill="none" stroke="url(#grad1)" stroke-width="2" opacity="0.3"></circle><path d="M35 50 L45 60 L65 40" stroke="url(#grad1)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"></path><circle cx="65" cy="35" r="8" fill="#fee140"></circle><path d="M62 35 L68 35 M65 32 L65 38" stroke="white" stroke-width="2" stroke-linecap="round"></path> </svg>
                <div>
                    <h2>یک قدم تا ساخت تصاویر جدید</h2>
                    <p>نیازمند تغییر نقطه دستیابی</p>
                </div>
            </div>
            <div class="guide-content">
                <div class="info-card">
                    <div class="info-card-header"><svg class="info-card-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" fill="#667eea" opacity="0.2"></path><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="#667eea" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> <span class="info-card-title">راه حل سریع</span></div>
                    <p>طبق ویدیو آموزشی پایین بین نقطه دستیابی جابجا شوید تلاش مجدد بزنید تا تصاویر مجدداً تولید بشه.</p>
                </div>
                <div class="summary-section">
                    <div class="summary-header"><svg class="summary-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="#56ab2f" opacity="0.2"></circle><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" stroke="#56ab2f" stroke-width="2"></path><path d="M9 12l2 2 4-4" stroke="#56ab2f" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> <span class="summary-title">خلاصه راهنما</span></div>
                    <div class="summary-text">هربار که این صفحه را مشاهده کردید: از اینترنت سیمکارت استفاده کنید، VPN را خاموش کرده و طبق ویدیو آموزشی پایین نقطه دستیابی رو تغییر دهید. «تلاش مجدد» کلیک کنید. با این روش ساده می‌توانید به صورت نامحدود تصویر بسازید! ☘️</div>
                </div>
                <div class="video-button-container"><button id="tutorialLinkBtn" class="elegant-video-button"> <svg class="elegant-video-button-icon" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg> <span>دیدن ویدیو آموزشی استفاده نامحدود</span> </button></div>
            </div>
            <div class="guide-actions">
                <button class="action-button back-button"> <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> <span>بازگشت</span> </button>
                <button class="action-button retry-button"> <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M23 4v6h-6M1 20v-6h6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> <span>تلاش مجدد</span> </button>
            </div>
        </div>`;

        const setUIState = (state) => {
            submitBtn.disabled = state === 'loading';
            if (state === 'loading') {
                btnText.style.display = 'none';
                btnSpinner.style.display = 'inline-block';
                outputSection.classList.remove('has-content');
                
                outputSection.style.padding = '';
                outputSection.style.border = '';
                outputSection.style.background = '';
                statusMessage.style.display = 'none';
                statusMessage.classList.remove('error');
                statusMessage.innerHTML = 'نتیجه تعویض چهره شما در اینجا نمایش داده خواهد شد.';
                
                resultContent.style.display = 'none';
                loadingAnimation.style.display = 'flex';
            } else { 
                btnText.style.display = 'inline-block';
                btnSpinner.style.display = 'none';
                btnText.textContent = "✨ تعویض چهره کن!";
                if (state !== 'idle') {
                    loadingAnimation.style.display = 'none';
                    outputSection.classList.add('has-content');
                }
            }
        };

        function calculateDimensions(imgWidth, imgHeight) {
            let aspect_ratio = imgWidth / imgHeight;
            let new_width, new_height;

            if (aspect_ratio >= 1) {
                new_width = 1024;
                new_height = Math.floor(1024 / aspect_ratio);
            } else {
                new_height = 1024;
                new_width = Math.floor(1024 * aspect_ratio);
            }

            new_width = Math.round(new_width / 8) * 8;
            new_height = Math.round(new_height / 8) * 8;

            new_width = Math.max(256, Math.min(1024, new_width));
            new_height = Math.max(256, Math.min(1024, new_height));

            return { width: new_width, height: new_height };
        }

        const handleRefSelect = (file) => {
            if (file && file.type.startsWith('image/')) {
                refFile = file;
                const reader = new FileReader();
                reader.onload = (e) => { refImagePreview.src = e.target.result; };
                reader.readAsDataURL(refFile);
                refFileNameSpan.textContent = file.name;
                uploadAreaRef.style.display = 'none';
                refFilePreview.style.display = 'flex';
            } else {
                refFile = null;
                alert("لطفاً یک فایل تصویر معتبر برای چهره جدید انتخاب کنید.");
            }
        };

        const handleTargetSelect = (file) => {
            if (file && file.type.startsWith('image/')) {
                targetFile = file;
                const reader = new FileReader();
                reader.onload = (e) => {
                    const img = new Image();
                    img.onload = () => {
                        const dims = calculateDimensions(img.width, img.height);
                        computedWidth = dims.width;
                        computedHeight = dims.height;
                    };
                    img.src = e.target.result;
                    targetImagePreview.src = e.target.result;
                };
                reader.readAsDataURL(targetFile);
                targetFileNameSpan.textContent = file.name;
                uploadAreaTarget.style.display = 'none';
                targetFilePreview.style.display = 'flex';
            } else {
                targetFile = null;
                alert("لطفاً یک فایل تصویر معتبر برای پس‌زمینه انتخاب کنید.");
            }
        };

        async function uploadFileToDocker(file, suffix) {
            const formData = new FormData();
            const ext = file.name.split('.').pop().toLowerCase();
            formData.append('run_id', `${currentRunId}_${suffix}`);
            formData.append('ext', ext);
            formData.append('file', file);

            const response = await fetch('/api/webhook/upload', { method: 'POST', body: formData });
            if (!response.ok) throw new Error("خطا در آپلود فایل.");
            return ext;
        }

        uploadAreaRef.addEventListener('click', () => referenceFaceInput.click());
        referenceFaceInput.addEventListener('change', (e) => handleRefSelect(e.target.files[0]));
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadAreaRef.addEventListener(eventName, e => { e.preventDefault(); e.stopPropagation(); }, false);
        });
        ['dragenter', 'dragover'].forEach(eventName => uploadAreaRef.addEventListener(eventName, () => uploadAreaRef.classList.add('drag-over')));
        ['dragleave', 'drop'].forEach(eventName => uploadAreaRef.addEventListener(eventName, () => uploadAreaRef.classList.remove('drag-over')));
        uploadAreaRef.addEventListener('drop', e => handleRefSelect(e.dataTransfer.files[0]));

        removeRefBtn.addEventListener('click', () => {
            refFile = null;
            referenceFaceInput.value = '';
            uploadAreaRef.style.display = 'block';
            refFilePreview.style.display = 'flex';
        });

        uploadAreaTarget.addEventListener('click', () => targetImageInput.click());
        targetImageInput.addEventListener('change', (e) => handleTargetSelect(e.target.files[0]));
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadAreaTarget.addEventListener(eventName, e => { e.preventDefault(); e.stopPropagation(); }, false);
        });
        ['dragenter', 'dragover'].forEach(eventName => uploadAreaTarget.addEventListener(eventName, () => uploadAreaTarget.classList.add('drag-over')));
        ['dragleave', 'drop'].forEach(eventName => uploadAreaTarget.addEventListener(eventName, () => uploadAreaTarget.classList.remove('drag-over')));
        uploadAreaTarget.addEventListener('drop', e => handleTargetSelect(e.dataTransfer.files[0]));

        removeTargetBtn.addEventListener('click', () => {
            targetFile = null;
            targetImageInput.value = '';
            uploadAreaTarget.style.display = 'block';
            targetFilePreview.style.display = 'none';
        });

        const retryLastAttempt = () => {
            submitBtn.click();
        };

        const hideGpuErrorGuide = () => {
            statusMessage.innerHTML = 'نتیجه تعویض چهره شما در اینجا نمایش داده خواهد شد.';
            statusMessage.classList.remove('error');
            outputSection.classList.remove('has-content');
            outputSection.style.padding = '';
            outputSection.style.border = '';
            outputSection.style.background = '';
        };

        const handleTimeout = () => {
            if (pollInterval) {
                clearInterval(pollInterval);
                pollInterval = null;
            }
            activePollRunId = '';
            setUIState('error');
            statusMessage.style.display = 'block';
            statusMessage.classList.add('error');
            
            statusMessage.innerHTML = `
                <div style="padding: 1.5rem; text-align: center;">
                    <p style="font-weight: 700; font-size: 1.1em; color: #c53030; margin-bottom: 1.5rem; line-height: 1.8;">
                        پردازش بیش از حد طولانی شد ممکن است سرور شلوغ باشد می‌توانید مجدداً تلاش کنید
                    </p>
                    <button type="button" class="action-button retry-button" id="timeout-retry-btn" style="margin: 0 auto; max-width: 200px; background: linear-gradient(95deg, var(--accent-secondary) 0%, var(--accent-primary) 100%); color: white; display: flex; align-items: center; justify-content: center; gap: 8px; border: none; padding: 12px 24px; border-radius: var(--radius-btn); cursor: pointer; font-family: var(--app-font); font-weight: 700; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);">
                        <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width: 20px; height: 20px; margin: 0; stroke: currentColor;"><path d="M23 4v6h-6M1 20v-6h6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
                        <span>تلاش مجدد</span>
                    </button>
                </div>
            `;
            
            document.getElementById('timeout-retry-btn').addEventListener('click', () => {
                hideGpuErrorGuide();
                submitBtn.click();
            });
        };

        const handleErrorState = (error) => {
            if (timeoutTimer) {
                clearTimeout(timeoutTimer);
                timeoutTimer = null;
            }
            setUIState('error');
            statusMessage.style.display = 'block';
            statusMessage.classList.add('error');
            
            const errorMessage = String(error.message || error).toLowerCase();
            
            if (errorMessage.includes("gpu") || errorMessage.includes("quota") || errorMessage.includes("exceeded") || errorMessage.includes("limit") || errorMessage.includes("capacity")) {
                outputSection.style.padding = '0';
                outputSection.style.border = 'none';
                outputSection.style.background = 'transparent';
                statusMessage.innerHTML = GPU_QUOTA_ERROR_HTML;
                
                statusMessage.querySelector('.back-button').addEventListener('click', hideGpuErrorGuide);
                statusMessage.querySelector('.retry-button').addEventListener('click', retryLastAttempt);
                statusMessage.querySelector('#tutorialLinkBtn').addEventListener('click', () => {
                    const tutorialUrl = '#/nav/online/news/getSingle/1149635/eyJpdiI6IjhHVGhPQWJwb3E0cjRXbnFWTW5BaUE9PSIsInZhbHVlIjoiS1V0dTdvT21wbXAwSXZaK1RCTG1pVXZqdlFJa1hXV1RKa2FLem9zU3pXMjd5MmlVOGc2YWY0NVdNR3h3Smp1aSIsIm1hYyI6IjY1NTA5ZDYzMjAzMTJhMGQyMWQ4NjA4ZDgyNGZjZDVlY2MyNjdiMjA2NWYzOWRjY2M4ZmVjYWRlMWNlMWQ3ODEiLCJ0YWciOiIifQ==/21135210';
                    parent.postMessage({ type: 'NAVIGATE_TO_URL', url: tutorialUrl }, '*');
                });
            } else {
                statusMessage.innerHTML = `<div style="padding: 1rem;"><b>خطای ارتباط!</b><br>مشکلی در برقراری ارتباط با سرور پیش آمده است. لطفاً چند لحظه دیگر امتحان کنید.</div>`;
            }
        };

        function startPolling(runId) {
            if (pollInterval) clearInterval(pollInterval);
            emptyActionCounter = 0;
            activePollRunId = runId;

            pollInterval = setInterval(async () => {
                if (activePollRunId !== runId) {
                    clearInterval(pollInterval);
                    return;
                }
                try {
                    try {
                        const imgCheck = await fetch(`/static/images/${runId}.png`, { method: 'HEAD' });
                        if (activePollRunId !== runId) return;
                        if (imgCheck.ok) {
                            if (timeoutTimer) {
                                clearTimeout(timeoutTimer);
                                timeoutTimer = null;
                            }
                            clearInterval(pollInterval);
                            setUIState('success');
                            resultImage.src = `/static/images/${runId}.png`;
                            downloadBtn.style.display = 'inline-flex';
                            resultContent.style.display = 'block';

                            // فقط در صورت اتمام موفقیت‌آمیز، استفاده روزانه را شمارش می‌کنیم
                            if (userSubscriptionStatus !== 'paid') {
                                incrementDailyUsage();
                            }
                            return;
                        }
                    } catch(e) {}

                    if (activePollRunId !== runId) return;
                    const activeRes = await fetch('/api/actions/active');
                    if (activePollRunId !== runId) return;
                    const activeData = await activeRes.json();
                    const hasActiveActions = activeData.status === 'success' && activeData.actions.length > 0;

                    if (activePollRunId !== runId) return;
                    const statusRes = await fetch(`/api/status/${runId}`);
                    if (activePollRunId !== runId) return;
                    const statusData = await statusRes.json();

                    if (activePollRunId !== runId) return;

                    if (statusData.status === 'ready') {
                        const urlLower = statusData.url.toLowerCase();
                        if (urlLower.endsWith('.png') || urlLower.endsWith('.jpg') || urlLower.endsWith('.jpeg')) {
                            
                            if (hasActiveActions) {
                                emptyActionCounter = 0;
                                loadingText.textContent = "در صف انتظار برای شروع مجدد پردازش...";
                                return; 
                            } else {
                                emptyActionCounter++;
                                if (emptyActionCounter < 4) {
                                    loadingText.textContent = "در حال آماده‌سازی سیستم برای تعویض چهره...";
                                    return;
                                }
                            }

                            if (timeoutTimer) {
                                clearTimeout(timeoutTimer);
                                timeoutTimer = null;
                            }
                            clearInterval(pollInterval);
                            handleErrorState(new Error("GPU quota exceeded"));
                        }
                    } else {
                        if (hasActiveActions) {
                            emptyActionCounter = 0;
                            loadingText.textContent = "در حال ترکیب چهره و تنظیم نورپردازی...";
                        } else {
                            loadingText.textContent = "در انتظار نوبت پردازش تصویر...";
                        }
                    }
                } catch (e) {
                    console.error("Error polling:", e);
                }
            }, 4000);
        }

        submitBtn.addEventListener('click', async () => {
            if (!refFile || !targetFile) {
                alert("لطفاً هر دو تصویر چهره مرجع و تصویر پس‌زمینه را بارگذاری کنید.");
                return;
            }

            // بررسی محدودیت استفاده روزانه برای کاربران رایگان
            if (userSubscriptionStatus !== 'paid') {
                const usage = getDailyUsage();
                if (usage >= 1) {
                    document.getElementById('limit-modal').classList.add('active');
                    return;
                }
            }

            if (pollInterval) {
                clearInterval(pollInterval);
                pollInterval = null;
            }
            if (timeoutTimer) {
                clearTimeout(timeoutTimer);
                timeoutTimer = null;
            }
            activePollRunId = '';
            hideGpuErrorGuide();

            setUIState('loading');
            currentRunId = 'swap' + Math.random().toString(36).substring(2, 14);
            
            // فعال‌سازی فوری تایمر ۲ دقیقه‌ای همزمان با آپلود اولین عکس
            timeoutTimer = setTimeout(() => {
                handleTimeout();
            }, 120000);
            
            try {
                loadingText.textContent = "در حال بارگذاری عکس چهره...";
                const refExt = await uploadFileToDocker(refFile, 'ref');

                loadingText.textContent = "در حال بارگذاری عکس پس‌زمینه...";
                const targetExt = await uploadFileToDocker(targetFile, 'target');

                loadingText.textContent = "در حال ارسال درخواست به سرور...";
                
                const stepsVal = 4;
                const guidanceVal = 1.0;
                const randomizeSeed = true;
                const seedVal = Math.floor(Math.random() * 2147483647);

                const swapPayload = `FACESWAPCONFIG_userRunId_${currentRunId}_refExt_${refExt}_targetExt_${targetExt}_width_${computedWidth}_height_${computedHeight}_steps_${stepsVal}_guidance_${guidanceVal}_seed_${seedVal}_randomizeSeed_${randomizeSeed}`;

                const response = await fetch('/api/generate', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        prompt: swapPayload,
                        width: computedWidth,
                        height: computedHeight,
                        action_name: 'face-swap'
                    })
                });

                const data = await response.json();

                if (data.status === 'success') {
                    startPolling(data.run_id);
                } else {
                    throw new Error(data.message || 'خطا در ثبت نوبت صف.');
                }

            } catch (error) {
                console.error("An error occurred:", error);
                handleErrorState(error);
            }
        });
        
        resultImage.addEventListener('click', () => {
            if (resultImage.src && resultImage.src !== window.location.href + '#') {
                fullscreenImage.src = resultImage.src;
                fullscreenModal.style.display = 'flex';
            }
        });

        const closeModal = () => { fullscreenModal.style.display = 'none'; };
        closeFullscreenBtn.addEventListener('click', closeModal);
        fullscreenModal.addEventListener('click', (e) => { if (e.target === fullscreenModal) { closeModal(); } });
        
        downloadBtn.addEventListener('click', async (event) => {
            event.preventDefault();
            const imageUrl = resultImage.src;
            if (!imageUrl || imageUrl.endsWith('#')) return;

            const absoluteUrl = new URL(imageUrl, window.location.href).href;

            if (window.parent && window.parent !== window) {
                window.parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: absoluteUrl }, '*');
            } else {
                try {
                    const response = await fetch(absoluteUrl);
                    const blob = await response.blob();
                    const objectUrl = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = objectUrl;
                    a.download = `alpha-swap-${Date.now()}.png`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(objectUrl);
                } catch (e) {
                    console.error("Direct download failed:", e);
                    alert("خطا در دانلود مستقیم فایل.");
                }
            }
        });

        // اجرای فرآیند شناسایی هویت کاربر در زمان لود صفحه
        document.addEventListener('DOMContentLoaded', async () => {
            userFingerprint = await getBrowserFingerprint();
            if (parent && parent !== window) {
                parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*');
            } else {
                updateUIForSubscriptionStatus('free');
            }
            setUIState('idle');
        });
    </script>
</body>
</html>