File size: 98,571 Bytes
86c5d02
 
 
 
 
18806ac
86c5d02
 
 
1df78e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7380f77
 
 
 
 
 
1df78e5
 
 
 
 
 
 
5db68f2
86c5d02
 
1df78e5
86c5d02
5db68f2
86c5d02
5db68f2
18806ac
750e40d
73afec9
7380f77
 
 
 
 
 
1df78e5
5db68f2
 
 
 
 
 
 
1df78e5
 
 
750e40d
 
 
 
1df78e5
5db68f2
86c5d02
1df78e5
 
86c5d02
3f3b086
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f3b086
 
7380f77
3f3b086
 
7380f77
 
1eda8eb
3f3b086
7380f77
3f3b086
7380f77
 
 
d87cb9d
7380f77
 
73afec9
1eda8eb
7380f77
d87cb9d
1eda8eb
7380f77
 
73afec9
d87cb9d
7380f77
 
d87cb9d
7380f77
 
1eda8eb
7380f77
1eda8eb
7380f77
 
 
 
 
 
 
1eda8eb
7380f77
 
 
 
 
 
 
 
d87cb9d
 
 
7380f77
 
 
 
 
 
 
d87cb9d
1eda8eb
d87cb9d
7380f77
 
 
 
 
 
 
 
 
 
1eda8eb
d87cb9d
7380f77
 
 
 
 
 
 
 
 
 
 
 
d87cb9d
 
7380f77
 
 
 
 
 
 
1eda8eb
d87cb9d
7380f77
 
 
 
73afec9
 
7380f77
 
 
 
 
d87cb9d
 
 
7380f77
 
 
1eda8eb
d87cb9d
7380f77
 
 
 
d87cb9d
7380f77
 
 
 
 
 
 
 
 
 
 
 
1eda8eb
d87cb9d
7380f77
 
 
 
 
 
27a4849
7380f77
40091cd
 
7380f77
 
 
 
40091cd
7380f77
40091cd
7380f77
 
 
 
40091cd
7380f77
 
 
 
40091cd
7380f77
 
 
 
40091cd
7380f77
 
 
40091cd
7380f77
 
 
 
 
 
40091cd
7380f77
40091cd
7380f77
 
 
40091cd
7380f77
 
 
 
40091cd
7380f77
 
 
 
 
40091cd
7380f77
 
 
40091cd
7380f77
 
 
 
40091cd
7380f77
 
 
 
40091cd
7380f77
 
 
40091cd
7380f77
 
40091cd
7380f77
 
 
 
 
 
40091cd
7380f77
 
 
 
40091cd
7380f77
 
 
 
 
 
 
 
 
 
 
 
40091cd
7380f77
 
 
 
40091cd
 
7380f77
 
 
 
 
 
 
 
40091cd
7380f77
40091cd
7380f77
40091cd
7380f77
 
 
 
40091cd
7380f77
40091cd
7380f77
 
 
 
 
40091cd
7380f77
40091cd
7380f77
 
 
 
40091cd
7380f77
 
 
 
 
 
40091cd
7380f77
 
 
40091cd
7380f77
40091cd
7380f77
 
 
d87cb9d
73afec9
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dde19d
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db68f2
7380f77
 
 
5db68f2
d57206a
5db68f2
 
 
 
 
18806ac
7380f77
 
 
 
 
 
 
 
 
5db68f2
7380f77
 
 
 
 
 
 
 
 
 
 
 
5db68f2
7380f77
 
 
 
 
5db68f2
 
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db68f2
 
 
7380f77
5db68f2
 
 
 
 
 
 
7380f77
5db68f2
 
 
 
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db68f2
 
 
 
 
 
 
 
 
 
 
7380f77
5db68f2
 
 
7380f77
5db68f2
 
7380f77
 
 
 
 
 
 
5db68f2
86c5d02
 
 
 
 
1df78e5
5db68f2
 
 
 
 
86c5d02
1aa8c20
86c5d02
1aa8c20
1df78e5
9cfe98f
27a4849
28727a6
 
73afec9
d87cb9d
 
 
 
 
3f3b086
d87cb9d
 
 
 
 
 
 
27a4849
d87cb9d
 
 
27a4849
d87cb9d
 
27a4849
40091cd
7380f77
dd8c3d9
40091cd
 
 
 
 
 
 
 
 
d87cb9d
 
 
 
 
 
27a4849
d87cb9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7380f77
1df78e5
86c5d02
18806ac
86c5d02
18806ac
 
1df78e5
 
27a4849
18806ac
750e40d
 
 
86c5d02
18806ac
86c5d02
 
 
 
18806ac
86c5d02
1df78e5
18806ac
 
1df78e5
5db68f2
2dde19d
 
27a4849
1df78e5
86c5d02
 
 
18806ac
7380f77
5db68f2
 
18806ac
5db68f2
 
 
1aa8c20
5db68f2
1aa8c20
86c5d02
18806ac
 
7380f77
5db68f2
 
 
 
 
 
 
7380f77
5db68f2
 
 
 
 
 
 
 
 
 
7380f77
5db68f2
7380f77
 
5db68f2
 
7380f77
5db68f2
 
 
 
 
 
 
 
 
7380f77
5db68f2
 
7380f77
 
5db68f2
 
 
 
27a4849
5db68f2
 
 
27a4849
5db68f2
 
 
 
 
27a4849
5db68f2
28727a6
5db68f2
27a4849
28727a6
 
5db68f2
 
 
27a4849
5db68f2
 
 
27a4849
5db68f2
 
 
 
 
 
 
 
 
7380f77
5db68f2
 
 
 
 
 
 
 
7380f77
5db68f2
 
 
7380f77
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7380f77
5db68f2
7380f77
5db68f2
 
c7a65c1
5045873
c7a65c1
7380f77
5db68f2
7380f77
5db68f2
 
7380f77
 
 
 
5db68f2
c7a65c1
7380f77
 
 
 
 
5db68f2
 
 
 
 
7380f77
 
 
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7380f77
5db68f2
 
 
 
7380f77
5db68f2
 
 
 
 
7380f77
 
5db68f2
 
7380f77
5db68f2
 
 
7380f77
5db68f2
 
 
 
 
7380f77
5db68f2
06545cf
 
 
7380f77
 
 
06545cf
 
7380f77
 
 
 
06545cf
7380f77
 
5db68f2
7380f77
5db68f2
 
 
7380f77
750e40d
 
 
 
 
 
7380f77
 
 
 
 
 
750e40d
 
7380f77
750e40d
7380f77
 
 
 
 
750e40d
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
750e40d
7380f77
 
 
 
 
 
5db68f2
 
7380f77
 
750e40d
7380f77
40091cd
 
 
 
 
 
7380f77
40091cd
 
7380f77
27a4849
 
 
 
 
 
 
 
 
 
 
 
18806ac
 
5db68f2
27a4849
7380f77
 
bce119b
27a4849
28727a6
27a4849
7380f77
 
27a4849
 
7380f77
 
27a4849
 
7380f77
 
27a4849
 
18806ac
06545cf
18806ac
7380f77
 
 
27a4849
 
 
 
 
 
 
 
 
 
 
 
 
7380f77
18806ac
750e40d
27a4849
18806ac
 
 
5db68f2
 
 
 
 
7380f77
5db68f2
 
 
 
7380f77
5db68f2
 
 
750e40d
5db68f2
 
 
7380f77
5db68f2
bce119b
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18806ac
750e40d
 
7380f77
750e40d
7380f77
750e40d
 
 
5db68f2
 
 
7380f77
18806ac
 
5db68f2
 
 
 
 
 
 
 
 
 
27a4849
 
 
 
 
 
 
 
7380f77
27a4849
28727a6
27a4849
7380f77
27a4849
 
7380f77
2ed17fa
27a4849
2ed17fa
27a4849
 
2ed17fa
27a4849
 
 
 
 
5db68f2
27a4849
7380f77
27a4849
7380f77
27a4849
 
 
 
 
7380f77
27a4849
 
7380f77
 
 
 
 
27a4849
 
 
7380f77
27a4849
7380f77
 
 
d57206a
7380f77
 
 
 
 
d57206a
 
7380f77
 
d57206a
 
 
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d57206a
 
7380f77
 
 
 
 
 
 
 
 
 
 
d57206a
 
7380f77
27a4849
 
 
7380f77
 
 
 
27a4849
 
7380f77
 
d57206a
 
27a4849
5db68f2
27a4849
 
 
 
86c5d02
27a4849
 
86c5d02
 
 
18806ac
7380f77
 
18806ac
 
 
 
7380f77
18806ac
5db68f2
18806ac
5db68f2
18806ac
 
7380f77
d57206a
 
 
 
7380f77
d57206a
7380f77
d57206a
 
7380f77
 
 
 
 
d57206a
 
 
 
 
 
 
 
 
 
7380f77
d57206a
 
 
 
 
7380f77
d57206a
 
 
 
 
 
 
7380f77
d57206a
 
7380f77
 
d57206a
7380f77
 
d57206a
 
7380f77
 
d57206a
7380f77
d57206a
 
 
 
 
 
7380f77
d57206a
7380f77
d57206a
 
 
 
 
7380f77
 
d57206a
 
 
 
7380f77
d57206a
 
 
 
 
 
7380f77
 
 
 
 
 
 
 
 
 
 
 
d57206a
 
7380f77
d57206a
 
7380f77
18806ac
7380f77
 
18806ac
5db68f2
27a4849
7380f77
27a4849
7380f77
27a4849
7380f77
27a4849
5db68f2
7380f77
1aa8c20
1df78e5
7380f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86c5d02
 
06545cf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Photoshop Pro</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: #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;
            --danger-color: #e53e3e;
            --danger-color-hover: #c53030;
            --upscale-gold: #F59E0B;
            --upscale-gold-light: #FEF3C7;
            --upscale-gold-glow: rgba(245, 158, 11, 0.3);
            --upscale-purple: #7C3AED;
            --upscale-purple-light: #EDE9FE;
            --upscale-purple-glow: rgba(124, 58, 237, 0.25);
            --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;
            --radius-sm: 10px;
            --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 fadeInBackdrop { from { opacity: 0; } to { opacity: 1; } }
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @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); } }
        @keyframes glow-text { 0% { opacity: 0.7; } 50% { opacity: 1; } 100% { opacity: 0.7; } }
        @keyframes badge-fade-in { from { opacity: 0; transform: translateY(-10px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } }
        @keyframes img-pop-in { from { opacity: 0; transform: scale(0.92); } to { opacity: 1; transform: scale(1); } }
        @keyframes shimmer { 0% { background-position: -200% center; } 100% { background-position: 200% center; } }
        @keyframes upscale-pulse { 0% { box-shadow: 0 0 0 0 var(--upscale-gold-glow); } 70% { box-shadow: 0 0 0 12px transparent; } 100% { box-shadow: 0 0 0 0 transparent; } }
        @keyframes float-stars { 0%, 100% { transform: translateY(0px) rotate(0deg); } 50% { transform: translateY(-8px) rotate(180deg); } }
        @keyframes reveal-upscaled { from { opacity: 0; transform: scale(0.95) translateY(20px); } to { opacity: 1; transform: scale(1) translateY(0); } }
        @keyframes sparkle { 0%, 100% { opacity: 0; transform: scale(0); } 50% { opacity: 1; transform: scale(1); } }
        @keyframes history-upscale-glow { 0%, 100% { box-shadow: 0 0 0 1px rgba(245,158,11,0.3), 0 4px 15px rgba(245,158,11,0.1); } 50% { box-shadow: 0 0 0 2px rgba(245,158,11,0.5), 0 6px 20px rgba(245,158,11,0.2); } }

        * { 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; align-items: flex-start; min-height: 100vh; padding: 2.5rem 1rem; }
        .container { max-width: 820px; width: 100%; display: flex; flex-direction: column; gap: 1.5rem; }
        
        header { position: relative; text-align: center; margin-bottom: 1rem; 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; }
        h1, .subtitle, #subscription-status-badge { position: relative; z-index: 2; }
        h1 { font-size: 2.8rem; font-weight: 800; 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; }
        .subtitle { font-size: 1.1rem; color: var(--text-secondary); margin-top: 0; }
        
        #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; position: relative; z-index: 2;}
        #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); }

        main, .gallery-section { 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.3s ease-out backwards; }
        .gallery-section { margin-top: 1.5rem; animation-delay: 0.5s; }
        .form-group { margin-bottom: 2.5rem; }
        .form-group:last-child { margin-bottom: 0; }
        .form-label { display: flex; align-items: center; gap: 0.75rem; font-weight: 700; color: var(--text-primary); font-size: 1.2em; margin-bottom: 1.2rem; }
        .form-label svg { width: 24px; height: 24px; color: var(--accent-primary); }

        /* Upload Area */
        .upload-images-wrapper { display: flex; flex-direction: column; gap: 12px; }
        .upload-primary-row { width: 100%; }
        .upload-primary-label { display: flex; align-items: center; gap: 8px; font-size: 0.82rem; font-weight: 700; color: var(--accent-primary); margin-bottom: 8px; letter-spacing: 0.3px; }
        .upload-primary-label .badge-required { background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); color: white; font-size: 0.68rem; font-weight: 800; padding: 2px 8px; border-radius: 20px; letter-spacing: 0.5px; }
        .upload-secondary-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .upload-optional-label { display: flex; align-items: center; gap: 6px; font-size: 0.78rem; font-weight: 700; color: var(--text-secondary); margin-bottom: 8px; }
        .upload-optional-label .badge-optional { background: var(--input-bg); color: var(--text-tertiary); font-size: 0.65rem; font-weight: 700; padding: 2px 7px; border-radius: 20px; border: 1px solid var(--input-border); }
        #upload-area, #upload-area-2, #upload-area-3 { position: relative; border: 2px dashed var(--input-border); border-radius: var(--radius-input); text-align: center; cursor: pointer; transition: var(--transition-smooth); background-color: var(--input-bg); display: flex; flex-direction: column; justify-content: center; align-items: center; overflow: hidden; }
        #upload-area { min-height: 200px; padding: 2.2rem 1.5rem; }
        #upload-area-2, #upload-area-3 { min-height: 140px; padding: 1.5rem 1rem; }
        #upload-area.drag-over, #upload-area:hover:not(.has-file), #upload-area-2.drag-over, #upload-area-2:hover:not(.has-file), #upload-area-3.drag-over, #upload-area-3:hover:not(.has-file) { border-color: var(--accent-primary); background-color: #fff; box-shadow: 0 0 0 4px var(--accent-primary-glow); }
        #upload-area.has-file, #upload-area-2.has-file, #upload-area-3.has-file { border-style: solid; border-color: var(--accent-primary); background-color: #f0f4ff; padding: 0; cursor: default; }
        .upload-content { display: flex; flex-direction: column; align-items: center; gap: 0.6rem; pointer-events: none; }
        .upload-icon-circle { width: 52px; height: 52px; border-radius: 50%; background: linear-gradient(135deg, rgba(74,108,250,0.12), rgba(15,212,168,0.1)); display: flex; align-items: center; justify-content: center; margin-bottom: 4px; border: 1.5px solid rgba(74,108,250,0.15); }
        #upload-area-2 .upload-icon-circle, #upload-area-3 .upload-icon-circle { width: 40px; height: 40px; }
        .upload-icon-circle svg { width: 24px; height: 24px; color: var(--accent-primary); stroke-width: 1.8; }
        #upload-area-2 .upload-icon-circle svg, #upload-area-3 .upload-icon-circle svg { width: 20px; height: 20px; }
        .upload-area-p { margin: 0; color: var(--text-secondary); font-weight: 600; font-size: 0.85rem; line-height: 1.5; }
        .upload-area-p.small { font-size: 0.75rem; color: var(--text-tertiary); font-weight: 500; }
        #upload-area-2 .upload-area-p, #upload-area-3 .upload-area-p { font-size: 0.78rem; }
        #upload-area-2 .upload-area-p.small, #upload-area-3 .upload-area-p.small { font-size: 0.68rem; }
        #remove-file-btn-main, #remove-file-btn-main-2, #remove-file-btn-main-3 { display: none; position: absolute; top: 10px; right: 10px; background-color: rgba(26, 32, 44, 0.75); color: white; border: none; width: 30px; height: 30px; border-radius: 50%; cursor: pointer; font-size: 1.1rem; line-height: 1; z-index: 10; transition: var(--transition-smooth); padding: 0; backdrop-filter: blur(4px); }
        #remove-file-btn-main:hover, #remove-file-btn-main-2:hover, #remove-file-btn-main-3:hover { background-color: var(--danger-color); transform: scale(1.1); }
        .img-index-badge { display: none; position: absolute; bottom: 10px; left: 10px; background: rgba(26,32,44,0.7); color: white; font-size: 0.7rem; font-weight: 700; padding: 3px 9px; border-radius: 20px; z-index: 10; backdrop-filter: blur(4px); }
        #upload-area.has-file .upload-content, #upload-area-2.has-file .upload-content, #upload-area-3.has-file .upload-content { display: none; }
        #upload-area.has-file #preview-image-main, #upload-area.has-file #remove-file-btn-main, #upload-area.has-file .img-index-badge, #upload-area-2.has-file #preview-image-main-2, #upload-area-2.has-file #remove-file-btn-main-2, #upload-area-2.has-file .img-index-badge, #upload-area-3.has-file #preview-image-main-3, #upload-area-3.has-file #remove-file-btn-main-3, #upload-area-3.has-file .img-index-badge { display: block; }
        #upload-area.has-file { min-height: unset !important; height: auto !important; }
        #upload-area-2.has-file, #upload-area-3.has-file { min-height: unset !important; height: auto !important; }
        #preview-image-main { display: none; width: 100%; height: auto !important; max-width: 100%; object-fit: contain !important; position: static !important; border-radius: inherit; animation: img-pop-in 0.35s ease-out; }
        #preview-image-main-2, #preview-image-main-3 { display: none; width: 100%; height: auto !important; max-width: 100%; object-fit: contain !important; position: static !important; border-radius: inherit; animation: img-pop-in 0.3s ease-out; }
        #upload-area.has-file #remove-file-btn-main, #upload-area-2.has-file #remove-file-btn-main-2, #upload-area-3.has-file #remove-file-btn-main-3 { position: absolute; top: 10px; right: 10px; }
        #upload-area.has-file .img-index-badge, #upload-area-2.has-file .img-index-badge, #upload-area-3.has-file .img-index-badge { position: absolute; bottom: 10px; left: 10px; }

        /* Optional toggle */
        .optional-toggle-btn { display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%; margin-top: 4px; padding: 10px 18px; background: linear-gradient(135deg, rgba(74,108,250,0.06) 0%, rgba(15,212,168,0.05) 100%); border: 1.5px dashed rgba(74,108,250,0.3); border-radius: var(--radius-btn); cursor: pointer; transition: var(--transition-smooth); font-family: var(--app-font); font-size: 0.83rem; font-weight: 700; color: var(--accent-primary); letter-spacing: 0.2px; position: relative; overflow: hidden; }
        .optional-toggle-btn::before { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(74,108,250,0.06), transparent); transform: translateX(-100%); transition: transform 0.5s ease; }
        .optional-toggle-btn:hover::before { transform: translateX(100%); }
        .optional-toggle-btn:hover { background: linear-gradient(135deg, rgba(74,108,250,0.1) 0%, rgba(15,212,168,0.08) 100%); border-color: var(--accent-primary); box-shadow: 0 0 0 3px var(--accent-primary-glow); transform: translateY(-1px); }
        .optional-toggle-btn:active { transform: translateY(0); }
        .optional-toggle-btn .toggle-icon { width: 22px; height: 22px; border-radius: 50%; background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary)); display: flex; align-items: center; justify-content: center; flex-shrink: 0; box-shadow: 0 2px 8px rgba(74,108,250,0.3); transition: transform 0.35s cubic-bezier(0.4,0,0.2,1); }
        .optional-toggle-btn .toggle-icon svg { width: 12px; height: 12px; color: white; stroke-width: 3; transition: transform 0.35s cubic-bezier(0.4,0,0.2,1); }
        .optional-toggle-btn.is-open .toggle-icon svg { transform: rotate(180deg); }
        .optional-toggle-btn .toggle-label { flex: 1; text-align: right; }
        .optional-toggle-btn .toggle-badge { background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); color: white; font-size: 0.68rem; font-weight: 800; padding: 2px 9px; border-radius: 20px; letter-spacing: 0.4px; }
        .optional-toggle-btn.is-open .toggle-badge { background: linear-gradient(90deg, var(--accent-secondary), var(--accent-primary)); }
        .optional-toggle-btn .toggle-dots { display: flex; gap: 3px; align-items: center; }
        .optional-toggle-btn .toggle-dots span { width: 5px; height: 5px; border-radius: 50%; background: var(--accent-primary); opacity: 0.4; transition: var(--transition-smooth); }
        .optional-toggle-btn:hover .toggle-dots span, .optional-toggle-btn.is-open .toggle-dots span { opacity: 1; }
        .optional-toggle-btn.is-open .toggle-dots span:nth-child(2) { background: var(--accent-secondary); }
        .optional-uploads-panel { overflow: hidden; max-height: 0; opacity: 0; transition: max-height 0.45s cubic-bezier(0.4,0,0.2,1), opacity 0.3s ease, margin-top 0.35s ease; margin-top: 0; }
        .optional-uploads-panel.is-open { max-height: 600px; opacity: 1; margin-top: 12px; }

        /* Textarea & Buttons */
        textarea { width: 100%; padding: 1rem 1.2rem; border-radius: var(--radius-input); border: 2px solid var(--input-border); background-color: var(--input-bg); color: var(--text-primary); box-shadow: var(--shadow-sm) inset; font-family: var(--app-font); font-size: 1.05rem; box-sizing: border-box; transition: var(--transition-smooth); min-height: 120px; resize: vertical; }
        textarea:focus { outline: none; border-color: var(--accent-primary); box-shadow: 0 0 0 4px var(--accent-primary-glow); background-color: #fff; }
        #submit-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); margin-top: 1rem; }
        #submit-btn svg { width: 26px; height: 26px; filter: drop-shadow(0 0 5px rgba(255,255,255,0.4)); }
        #submit-btn:hover:not(:disabled) { transform: translateY(-4px) scale(1.01); box-shadow: 0 10px 20px -4px var(--accent-primary-glow); }
        #submit-btn:disabled { background: var(--text-tertiary); cursor: not-allowed; box-shadow: none; opacity: 0.7; transform: none; }
        #submit-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; }
        .credit-info { font-size: 0.95rem; color: var(--text-tertiary); text-align: center; margin-top: 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-top: 1rem; padding: 1rem; background: linear-gradient(90deg, #FFD54F, #FFC107); 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%; max-height: 500px; border-radius: var(--radius-input); border: 1px solid var(--panel-border); box-shadow: var(--shadow-lg); object-fit: contain; cursor: pointer; transition: transform 0.2s; }
        .generated-image-box img:hover { transform: scale(1.02); }
        
        /* 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; }
        .noise-layer, .sketch-layer, .building-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
        .noise-layer { 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 { 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 { 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); } 50% { transform: translate(10px, -15px) scale(1.05); } 100% { transform: translate(0, 0) scale(1); } }
        .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); z-index: 2; text-align: center; width: 90%; }
        .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; z-index: 2; }

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

        /* =============================================
           ✨ ENHANCED UPSCALED IMAGE SECTION
           ============================================= */
        
        /* Result wrapper: edited + upscaled side layout on wide screens */
        .result-images-wrapper {
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 0;
        }

        /* Edited image card */
        .result-card {
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 14px;
            padding: 24px;
            background: var(--input-bg);
            border-radius: 20px;
            border: 1px solid var(--panel-border);
            margin-bottom: 20px;
        }

        .result-card-label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.82rem;
            font-weight: 700;
            color: var(--text-secondary);
            background: var(--panel-bg);
            padding: 5px 14px;
            border-radius: 20px;
            border: 1px solid var(--panel-border);
            align-self: flex-start;
        }
        .result-card-label svg { width: 14px; height: 14px; }

        .result-card img {
            max-width: 100%;
            max-height: 500px;
            border-radius: 14px;
            border: 1px solid var(--panel-border);
            box-shadow: var(--shadow-lg);
            object-fit: contain;
            cursor: pointer;
            transition: transform 0.2s;
            width: 100%;
        }
        .result-card img:hover { transform: scale(1.01); }

        /* ✨ Upscaled card - premium feel */
        .upscaled-card {
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 16px;
            padding: 28px 24px;
            background: linear-gradient(135deg, #fffbeb 0%, #fdf4ff 50%, #f0f9ff 100%);
            border-radius: 24px;
            border: 2px solid transparent;
            background-clip: padding-box;
            position: relative;
            overflow: hidden;
        }

        /* Rainbow border via pseudo */
        .upscaled-card::before {
            content: '';
            position: absolute;
            inset: -2px;
            background: linear-gradient(135deg, #F59E0B, #A855F7, #3B82F6, #10B981, #F59E0B);
            background-size: 300% 300%;
            border-radius: 26px;
            z-index: -1;
            animation: shimmer 4s linear infinite;
        }

        /* Subtle sparkles decoration */
        .upscaled-card::after {
            content: '✦ ✦ ✦';
            position: absolute;
            top: 12px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 0.55rem;
            letter-spacing: 8px;
            color: var(--upscale-gold);
            opacity: 0.6;
            pointer-events: none;
        }

        .upscaled-header {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
            width: 100%;
            padding-top: 8px;
        }

        .upscaled-title-row {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .upscaled-icon {
            width: 44px;
            height: 44px;
            background: linear-gradient(135deg, #F59E0B, #EF4444);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
            font-size: 1.4rem;
            animation: float-stars 3s ease-in-out infinite;
        }

        .upscaled-title {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }
        .upscaled-title-main {
            font-size: 1.05rem;
            font-weight: 800;
            background: linear-gradient(90deg, #D97706, #7C3AED);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            letter-spacing: -0.3px;
        }
        .upscaled-title-sub {
            font-size: 0.72rem;
            font-weight: 600;
            color: var(--text-tertiary);
        }

        /* Tech badges */
        .upscaled-badges {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            justify-content: center;
        }
        .tech-badge {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.72rem;
            font-weight: 700;
            letter-spacing: 0.3px;
        }
        .tech-badge.gold {
            background: linear-gradient(90deg, rgba(245,158,11,0.15), rgba(251,191,36,0.1));
            color: #D97706;
            border: 1px solid rgba(245,158,11,0.3);
        }
        .tech-badge.purple {
            background: linear-gradient(90deg, rgba(124,58,237,0.1), rgba(167,139,250,0.08));
            color: #7C3AED;
            border: 1px solid rgba(124,58,237,0.2);
        }
        .tech-badge.blue {
            background: linear-gradient(90deg, rgba(59,130,246,0.1), rgba(99,179,237,0.08));
            color: #2563EB;
            border: 1px solid rgba(59,130,246,0.2);
        }
        .tech-badge .badge-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: currentColor;
            animation: upscale-pulse 2s ease-out infinite;
        }

        /* Loading state for upscaled */
        .upscaled-loading {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 14px;
            padding: 2rem 0;
            width: 100%;
        }
        .upscaled-loading-visual {
            position: relative;
            width: 80px;
            height: 80px;
        }
        .upscaled-loading-ring {
            position: absolute;
            inset: 0;
            border-radius: 50%;
            border: 3px solid transparent;
        }
        .upscaled-loading-ring:nth-child(1) {
            border-top-color: #F59E0B;
            animation: spin 1.2s linear infinite;
        }
        .upscaled-loading-ring:nth-child(2) {
            border-right-color: #A855F7;
            inset: 8px;
            animation: spin 1.8s linear infinite reverse;
        }
        .upscaled-loading-ring:nth-child(3) {
            border-bottom-color: #3B82F6;
            inset: 16px;
            animation: spin 1s linear infinite;
        }
        .upscaled-loading-core {
            position: absolute;
            inset: 24px;
            border-radius: 50%;
            background: linear-gradient(135deg, #F59E0B, #A855F7);
            opacity: 0.8;
        }
        .upscaled-loading-text {
            font-size: 0.88rem;
            font-weight: 700;
            color: #92400E;
            text-align: center;
            line-height: 1.6;
        }
        .upscaled-loading-steps {
            display: flex;
            gap: 6px;
            align-items: center;
        }
        .upscaled-step {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 0.68rem;
            font-weight: 600;
            color: var(--text-tertiary);
            padding: 3px 10px;
            border-radius: 20px;
            background: rgba(245,158,11,0.08);
            border: 1px solid rgba(245,158,11,0.2);
            transition: all 0.5s;
        }
        .upscaled-step.active {
            color: #D97706;
            background: rgba(245,158,11,0.15);
            border-color: rgba(245,158,11,0.4);
        }

        /* Upscaled image reveal */
        .upscaled-image-reveal {
            width: 100%;
            display: none;
            flex-direction: column;
            align-items: center;
            gap: 12px;
            animation: reveal-upscaled 0.6s cubic-bezier(0.4, 0, 0.2, 1) forwards;
        }
        .upscaled-image-reveal.visible { display: flex; }

        .upscaled-image-frame {
            width: 100%;
            position: relative;
            border-radius: 18px;
            overflow: hidden;
            box-shadow: 0 8px 40px rgba(245,158,11,0.2), 0 4px 20px rgba(124,58,237,0.15), var(--shadow-xl);
        }
        .upscaled-image-frame img {
            width: 100%;
            max-height: 550px;
            object-fit: contain;
            display: block;
            cursor: pointer;
            transition: transform 0.3s ease;
        }
        .upscaled-image-frame img:hover { transform: scale(1.01); }

        /* Corner sparkles on image */
        .upscaled-image-frame::before,
        .upscaled-image-frame::after {
            content: '✦';
            position: absolute;
            font-size: 1rem;
            z-index: 2;
            pointer-events: none;
            animation: sparkle 2s ease-in-out infinite;
        }
        .upscaled-image-frame::before {
            top: 10px;
            right: 12px;
            color: #F59E0B;
            animation-delay: 0s;
        }
        .upscaled-image-frame::after {
            bottom: 10px;
            left: 12px;
            color: #A855F7;
            animation-delay: 1s;
        }

        /* Size info strip */
        .upscaled-info-strip {
            display: flex;
            gap: 10px;
            align-items: center;
            justify-content: center;
            flex-wrap: wrap;
        }
        .upscaled-info-chip {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 0.75rem;
            font-weight: 700;
            padding: 5px 14px;
            border-radius: 20px;
        }
        .upscaled-info-chip.size-chip {
            background: linear-gradient(90deg, rgba(16, 185, 129, 0.12), rgba(6, 182, 212, 0.08));
            color: #065F46;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }
        .upscaled-info-chip svg { width: 13px; height: 13px; }

        /* Download button - premium gold */
        .download-upscaled-btn-premium {
            display: none;
            align-items: center;
            justify-content: center;
            gap: 10px;
            width: 100%;
            max-width: 340px;
            padding: 1rem 1.5rem;
            background: linear-gradient(135deg, #F59E0B 0%, #EF4444 50%, #A855F7 100%);
            background-size: 200% 200%;
            color: white;
            border: none;
            border-radius: var(--radius-btn);
            font-family: var(--app-font);
            font-weight: 800;
            font-size: 1rem;
            cursor: pointer;
            transition: var(--transition-smooth);
            box-shadow: 0 6px 20px rgba(245,158,11,0.35), 0 3px 10px rgba(168,85,247,0.2);
            letter-spacing: 0.3px;
            animation: shimmer 3s ease-in-out infinite;
        }
        .download-upscaled-btn-premium:hover {
            transform: translateY(-4px) scale(1.02);
            box-shadow: 0 10px 30px rgba(245,158,11,0.45), 0 5px 15px rgba(168,85,247,0.3);
        }
        .download-upscaled-btn-premium svg { width: 22px; height: 22px; filter: drop-shadow(0 0 4px rgba(255,255,255,0.4)); }
        .download-upscaled-btn-premium.visible { display: inline-flex; }

        /* =============================================
           ✨ ENHANCED HISTORY ITEMS FOR UPSCALED
           ============================================= */
        .history-section { display: none; animation: fadeIn 0.5s ease-out; }
        .history-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; }
        .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; margin: 0; }
        .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-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); }
        
        /* ✨ Special upscaled history item */
        .history-item.is-upscaled {
            background: linear-gradient(135deg, #fffbeb, #fdf4ff);
            border: 1.5px solid rgba(245,158,11,0.3);
            animation: history-upscale-glow 3s ease-in-out infinite;
        }
        .history-item.is-upscaled:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 25px rgba(245,158,11,0.2), 0 4px 12px rgba(124,58,237,0.1);
        }

        .history-item img { width: 100%; height: 200px; object-fit: cover; cursor: pointer; border-bottom: 1px solid var(--input-border); }
        .history-item.is-upscaled img {
            border-bottom: 1.5px solid rgba(245,158,11,0.2);
            position: relative;
        }

        .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;
            align-items: center;
            font-weight: 600;
            background: var(--panel-bg);
            padding: 5px 8px;
            border-radius: 6px;
            border: 1px solid var(--panel-border);
        }
        
        /* ✨ Upscaled meta badge */
        .history-meta.upscaled-meta {
            background: linear-gradient(90deg, rgba(245,158,11,0.08), rgba(168,85,247,0.06));
            border: 1px solid rgba(245,158,11,0.25);
            color: #92400E;
        }
        .history-meta .upscaled-meta-icon {
            font-size: 0.75rem;
        }

        /* Small crown on upscaled thumbnail */
        .history-img-wrapper {
            position: relative;
            overflow: hidden;
        }
        .history-img-wrapper img { display: block; }
        .upscaled-corner-badge {
            display: none;
            position: absolute;
            top: 0;
            right: 0;
            background: linear-gradient(135deg, #F59E0B, #EF4444);
            color: white;
            font-size: 0.6rem;
            font-weight: 800;
            padding: 3px 8px 3px 12px;
            border-bottom-left-radius: 10px;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 8px rgba(245,158,11,0.4);
            z-index: 2;
        }
        .is-upscaled .upscaled-corner-badge { display: block; }

        .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; }

        /* Modal & confirm */
        .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); }
        .iv-action-btn svg { width: 20px; height: 20px; }
        .iv-btn-copy { background: #4A5568; }
        .iv-btn-copy:hover { background: #2D3748; }

        /* Modal upscaled label */
        .modal-upscale-label {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 6px 16px;
            border-radius: 20px;
            background: linear-gradient(90deg, rgba(245,158,11,0.2), rgba(168,85,247,0.15));
            border: 1px solid rgba(245,158,11,0.3);
            color: #FDE68A;
            font-size: 0.8rem;
            font-weight: 700;
            letter-spacing: 0.5px;
        }

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

        @media (max-width: 650px) {
            main, .gallery-section { padding: 1.5rem; } h1 { font-size: 2.2rem; }
            .generator-container { 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; }
            .upload-secondary-row { grid-template-columns: 1fr 1fr; gap: 8px; }
            #upload-area { min-height: 160px; }
            #upload-area-2, #upload-area-3 { min-height: 120px; }
            .upscaled-loading-steps { flex-wrap: wrap; justify-content: center; }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <canvas id="neural-network-canvas"></canvas>
            <div style="position: relative; z-index: 2;">
                <h1>فتوشاپ هوش مصنوعی ✨</h1>
                <p class="subtitle">تصاویر خود را با قدرت هوش مصنوعی و به زبان ساده ویرایش کنید</p>
                <div id="subscription-status-badge">درحال بررسی...</div>
            </div>
        </header>

        <main>
             <div class="form-group">
                <div class="form-label">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg>
                    ۱. تصاویر خود را انتخاب کنید
                </div>
                
                <div class="upload-images-wrapper">
                    <div class="upload-primary-row">
                        <div class="upload-primary-label">
                            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                            تصویر اصلی
                            <span class="badge-required">الزامی</span>
                        </div>
                        <label id="upload-area" for="file-input">
                            <div class="upload-content">
                                <div class="upload-icon-circle">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><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 class="upload-area-p">فایل تصویر را اینجا بکشید</p>
                                <p class="upload-area-p small">یا کلیک کنید برای انتخاب — PNG, JPG, WEBP</p>
                            </div>
                            <img id="preview-image-main" src="" alt="Preview">
                            <button type="button" id="remove-file-btn-main" title="حذف تصویر">&times;</button>
                            <span class="img-index-badge">تصویر ۱</span>
                        </label>
                        <input type="file" id="file-input" accept="image/png, image/jpeg, image/webp" hidden>
                    </div>

                    <button type="button" id="optional-uploads-toggle" class="optional-toggle-btn" aria-expanded="false">
                        <div class="toggle-dots"><span></span><span></span><span></span></div>
                        <span class="toggle-label">افزودن تصاویر بیشتر اختیاری</span>
                        <span class="toggle-badge">اختیاری</span>
                        <div class="toggle-icon">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="6 9 12 15 18 9"></polyline>
                            </svg>
                        </div>
                    </button>

                    <div class="optional-uploads-panel" id="optional-uploads-panel">
                    <div class="upload-secondary-row">
                        <div>
                            <div class="upload-optional-label">
                                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                                تصویر دوم
                                <span class="badge-optional">اختیاری</span>
                            </div>
                            <label id="upload-area-2" for="file-input-2">
                                <div class="upload-content">
                                    <div class="upload-icon-circle">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><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 class="upload-area-p">کلیک یا درگ کنید</p>
                                </div>
                                <img id="preview-image-main-2" src="" alt="Preview">
                                <button type="button" id="remove-file-btn-main-2" title="حذف تصویر">&times;</button>
                                <span class="img-index-badge">تصویر ۲</span>
                            </label>
                            <input type="file" id="file-input-2" accept="image/png, image/jpeg, image/webp" hidden>
                        </div>
                        <div>
                            <div class="upload-optional-label">
                                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                                تصویر سوم
                                <span class="badge-optional">اختیاری</span>
                            </div>
                            <label id="upload-area-3" for="file-input-3">
                                <div class="upload-content">
                                    <div class="upload-icon-circle">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><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 class="upload-area-p">کلیک یا درگ کنید</p>
                                </div>
                                <img id="preview-image-main-3" src="" alt="Preview">
                                <button type="button" id="remove-file-btn-main-3" title="حذف تصویر">&times;</button>
                                <span class="img-index-badge">تصویر ۳</span>
                            </label>
                            <input type="file" id="file-input-3" accept="image/png, image/jpeg, image/webp" hidden>
                        </div>
                    </div>
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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>
                    ۲. دستور ویرایش را بنویسید
                </label>
                <textarea id="prompt-input" placeholder="مثال: پس‌زمینه را حذف کن و یک ساحل آفتابی قرار بده"></textarea>
                
                <div id="credit-info" class="credit-info">درحال بررسی اعتبار...</div>
                <button id="upgrade-button" class="upgrade-btn">⭐️ ارتقا به نسخه نامحدود</button>

                <button id="submit-btn" disabled>
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/></svg>
                    <span id="btn-text">ایجاد کن</span>
                    <div class="spinner"></div>
                </button>
            </div>

            <div class="form-group">
                 <div class="form-label">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/><path d="M21 14l-1.5 3-3-1.5 3-3 1.5 3z"/><path d="M19.5 2.5l-3 1.5 1.5 3 3-1.5-1.5-3z"/></svg>
                     ۳. نتیجه نهایی
                </div>
                <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>
            </div>
        </main>
        
        <section class="gallery-section history-section" id="history-section" style="display: none;">
            <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"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M9 21V9"/></svg>
                    تاریخچه ویرایش‌های شما
                </h3>
                <button id="clear-history-btn" class="danger-btn">حذف همه</button>
            </div>
            <div id="history-grid" class="history-grid"></div>
        </section>
    </div>

    <script>
        // --- Custom Confirm Dialog ---
        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"><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(); }
        }

        // --- Database ---
        const dbName = 'AI_Editor_DB_v3';
        const historyStore = 'EditHistory';
        const inputStore = 'InputImageStore';
        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(historyStore)) db.createObjectStore(historyStore, { keyPath: 'id', autoIncrement: true });
                    if (!db.objectStoreNames.contains(inputStore)) db.createObjectStore(inputStore, { keyPath: 'id' });
                };
            });
        }

        function saveInputImage(key, blob) {
            return new Promise((resolve, reject) => {
                if (!db) return resolve();
                const tx = db.transaction([inputStore], 'readwrite');
                tx.objectStore(inputStore).put({ id: key, blob: blob });
                tx.oncomplete = () => resolve();
                tx.onerror = () => reject();
            });
        }

        function getInputImage(key) {
            return new Promise((resolve) => {
                if (!db) return resolve(null);
                const tx = db.transaction([inputStore], 'readonly');
                const req = tx.objectStore(inputStore).get(key);
                req.onsuccess = () => resolve(req.result ? req.result.blob : null);
                req.onerror = () => resolve(null);
            });
        }

        function clearInputImage(key) {
            return new Promise((resolve) => {
                if (!db) return resolve();
                const tx = db.transaction([inputStore], 'readwrite');
                tx.objectStore(inputStore).delete(key);
                tx.oncomplete = () => resolve();
            });
        }

        async function saveToHistory(blob, prompt) {
            if (!db) await initDB();
            return new Promise((resolve, reject) => {
                const transaction = db.transaction([historyStore], 'readwrite');
                const store = transaction.objectStore(historyStore);
                store.add({ blob, prompt, timestamp: Date.now() });
                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([historyStore], 'readonly');
                const store = transaction.objectStore(historyStore);
                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 isUpscaled = item.prompt.endsWith(" (باکیفیت شده)");
                const displayPrompt = isUpscaled ? item.prompt.replace(" (باکیفیت شده)", "") : item.prompt;
                const safeTitle = displayPrompt.replace(/"/g, '&quot;');

                const div = document.createElement('div');
                div.className = 'history-item' + (isUpscaled ? ' is-upscaled' : '');

                div.innerHTML = `
                    <div class="history-img-wrapper">
                        <img src="${blobUrl}" alt="History Image" title="برای مشاهده کلیک کنید">
                        <div class="upscaled-corner-badge">✦ باکیفیت</div>
                    </div>
                    <div class="history-details">
                        <div class="history-prompt" dir="auto" title="${safeTitle}">${displayPrompt}</div>
                        <div class="history-meta ${isUpscaled ? 'upscaled-meta' : ''}">
                            ${isUpscaled
                                ? `<span>✦ ارتقا کیفیت CodeFormer</span><span class="upscaled-meta-icon">🎨</span>`
                                : `<span>ویرایش شده</span>`
                            }
                        </div>
                        <button class="history-delete-btn">حذف تصویر</button>
                    </div>
                `;

                div.querySelector('img').addEventListener('click', () => viewHistoryImage(blobUrl, item.prompt, isUpscaled));
                div.querySelector('.history-meta').onclick = (e) => { e.stopPropagation(); viewHistoryImage(blobUrl, item.prompt, isUpscaled); };
                div.querySelector('.history-delete-btn').addEventListener('click', (e) => { e.stopPropagation(); deleteHistoryItem(item.id); });
                grid.appendChild(div);
            });
        }

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

        document.getElementById('clear-history-btn').addEventListener('click', () => {
            showCustomConfirm('حذف تمام تصاویر', 'آیا از پاک کردن تمامی تصاویر از سابقه مطمئن هستید؟ این عمل غیرقابل بازگشت است.', async () => {
                if (!db) await initDB();
                const transaction = db.transaction([historyStore], 'readwrite');
                transaction.objectStore(historyStore).clear();
                transaction.oncomplete = () => loadHistory();
            });
        });

        window.viewHistoryImage = function(url, promptText, isUpscaled = false) {
            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()">
                    ${isUpscaled ? `<div class="modal-upscale-label">✦ نسخه باکیفیت شده — CodeFormer AI</div>` : ''}
                    <img src="${url}" alt="Full Image" class="full-view-img" style="${isUpscaled ? 'box-shadow: 0 0 40px rgba(245,158,11,0.3), 0 0 20px rgba(168,85,247,0.2);' : ''}">
                    <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"><rect x="9" y="9" width="13" height="13" rx="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"><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"><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 ta = document.createElement("textarea"); ta.value = promptText; ta.style.cssText = "position:fixed;top:-9999px;left:-9999px";
                    document.body.appendChild(ta); ta.focus(); ta.select();
                    try { document.execCommand('copy'); showSuccess(); } catch(e) {}
                    document.body.removeChild(ta);
                };
                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);
        };

        // --- Account & subscription ---
        let userSubscriptionStatus = 'free';
        let userFingerprint = null;
        let countdownInterval = null;
        let freeCreditRemaining = 5;
        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 str = components.join('---');
            let hash = 0;
            for (let i = 0; i < str.length; i++) { hash = ((hash << 5) - hash) + str.charCodeAt(i); hash |= 0; }
            return 'fp_edit_' + 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 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';
                checkFormState(); 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 submitBtn = document.getElementById('submit-btn');
            try {
                const response = await fetch('/api/check-edit-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) {
                    freeCreditRemaining = 0; submitBtn.disabled = true;
                    upgradeBtn.style.display = 'block'; startCountdown(result.reset_timestamp);
                } else {
                    freeCreditRemaining = result.credits_remaining; checkFormState();
                    upgradeBtn.style.display = 'none'; if (countdownInterval) clearInterval(countdownInterval);
                    creditInfoDiv.innerHTML = `شما <b>${result.credits_remaining}</b> اعتبار ویرایش تصویر برای این هفته دارید.`;
                }
            } catch (error) { creditInfoDiv.textContent = "خطا در ارتباط با سیستم اعتبار."; submitBtn.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 d = Math.floor(timeLeft / 86400); const h = Math.floor((timeLeft % 86400) / 3600);
                creditInfoDiv.innerHTML = `<span style="color:var(--danger-color)">اعتبار این هفته تمام شد.</span> زمان شارژ مجدد: ${d} روز و ${h} ساعت`;
            };
            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.getElementById('upgrade-button').addEventListener('click', () => parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM' }, '*'));
        window.triggerDownload = function(url) { parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: url }, '*'); };

        // --- Optional uploads toggle ---
        const optionalToggleBtn = document.getElementById('optional-uploads-toggle');
        const optionalPanel = document.getElementById('optional-uploads-panel');
        optionalToggleBtn.addEventListener('click', () => {
            const isOpen = optionalPanel.classList.toggle('is-open');
            optionalToggleBtn.classList.toggle('is-open', isOpen);
            optionalToggleBtn.setAttribute('aria-expanded', isOpen.toString());
            optionalToggleBtn.querySelector('.toggle-label').textContent = isOpen ? 'بستن تصاویر بیشتر اختیاری' : 'افزودن تصاویر بیشتر اختیاری';
        });

        // --- File Upload Management ---
        const uploadArea = document.getElementById('upload-area');
        const fileInput = document.getElementById('file-input');
        const previewImage = document.getElementById('preview-image-main');
        const removeFileBtn = document.getElementById('remove-file-btn-main');
        const uploadArea2 = document.getElementById('upload-area-2');
        const fileInput2 = document.getElementById('file-input-2');
        const previewImage2 = document.getElementById('preview-image-main-2');
        const removeFileBtn2 = document.getElementById('remove-file-btn-main-2');
        const uploadArea3 = document.getElementById('upload-area-3');
        const fileInput3 = document.getElementById('file-input-3');
        const previewImage3 = document.getElementById('preview-image-main-3');
        const removeFileBtn3 = document.getElementById('remove-file-btn-main-3');
        const promptInput = document.getElementById('prompt-input');
        const submitBtn = document.getElementById('submit-btn');
        const imageResultContainer = document.getElementById('image-result-container');

        let uploadedFile = null, uploadedFile2 = null, uploadedFile3 = null;
        let activePollTimer = null, activeTimeoutTimer = null, fakeProgressInterval = null, isResultProcessed = false;

        async function handleFile(file, boxIndex) {
            if (!file || !file.type.startsWith('image/')) return alert('لطفاً یک تصویر انتخاب کنید.');
            if (boxIndex === 1) {
                uploadedFile = file; await saveInputImage('current_input', file);
                const reader = new FileReader(); reader.onload = (e) => { previewImage.src = e.target.result; }; reader.readAsDataURL(file);
                uploadArea.classList.add('has-file');
            } else if (boxIndex === 2) {
                uploadedFile2 = file; await saveInputImage('current_input_2', file);
                const reader = new FileReader(); reader.onload = (e) => { previewImage2.src = e.target.result; }; reader.readAsDataURL(file);
                uploadArea2.classList.add('has-file');
            } else if (boxIndex === 3) {
                uploadedFile3 = file; await saveInputImage('current_input_3', file);
                const reader = new FileReader(); reader.onload = (e) => { previewImage3.src = e.target.result; }; reader.readAsDataURL(file);
                uploadArea3.classList.add('has-file');
            }
            checkFormState();
        }

        removeFileBtn.onclick = async (e) => { e.preventDefault(); e.stopPropagation(); uploadedFile = null; fileInput.value = ''; previewImage.src = ''; uploadArea.classList.remove('has-file'); await clearInputImage('current_input'); checkFormState(); };
        removeFileBtn2.onclick = async (e) => { e.preventDefault(); e.stopPropagation(); uploadedFile2 = null; fileInput2.value = ''; previewImage2.src = ''; uploadArea2.classList.remove('has-file'); await clearInputImage('current_input_2'); checkFormState(); };
        removeFileBtn3.onclick = async (e) => { e.preventDefault(); e.stopPropagation(); uploadedFile3 = null; fileInput3.value = ''; previewImage3.src = ''; uploadArea3.classList.remove('has-file'); await clearInputImage('current_input_3'); checkFormState(); };

        fileInput.onchange = (e) => handleFile(e.target.files[0], 1);
        uploadArea.ondragover = (e) => { e.preventDefault(); uploadArea.classList.add('drag-over'); };
        uploadArea.ondragleave = () => uploadArea.classList.remove('drag-over');
        uploadArea.ondrop = (e) => { e.preventDefault(); uploadArea.classList.remove('drag-over'); handleFile(e.dataTransfer.files[0], 1); };
        fileInput2.onchange = (e) => handleFile(e.target.files[0], 2);
        uploadArea2.ondragover = (e) => { e.preventDefault(); uploadArea2.classList.add('drag-over'); };
        uploadArea2.ondragleave = () => uploadArea2.classList.remove('drag-over');
        uploadArea2.ondrop = (e) => { e.preventDefault(); uploadArea2.classList.remove('drag-over'); handleFile(e.dataTransfer.files[0], 2); };
        fileInput3.onchange = (e) => handleFile(e.target.files[0], 3);
        uploadArea3.ondragover = (e) => { e.preventDefault(); uploadArea3.classList.add('drag-over'); };
        uploadArea3.ondragleave = () => uploadArea3.classList.remove('drag-over');
        uploadArea3.ondrop = (e) => { e.preventDefault(); uploadArea3.classList.remove('drag-over'); handleFile(e.dataTransfer.files[0], 3); };

        function checkFormState() {
            let limitReached = (userSubscriptionStatus === 'free' && freeCreditRemaining === 0);
            submitBtn.disabled = limitReached || !(uploadedFile && promptInput.value.trim() !== '');
        }
        promptInput.oninput = checkFormState;

        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%';
        }

        // --- Upscaled loading steps animation ---
        let stepsInterval = null;
        const stepLabels = ['تحلیل تصویر', 'بازسازی جزئیات', 'افزایش کیفیت', 'پردازش نهایی'];
        function animateUpscaleSteps() {
            let currentStep = 0;
            function updateSteps() {
                document.querySelectorAll('.upscaled-step').forEach((el, i) => {
                    el.classList.toggle('active', i === currentStep);
                });
                currentStep = (currentStep + 1) % stepLabels.length;
            }
            updateSteps();
            stepsInterval = setInterval(updateSteps, 2200);
        }
        function stopStepsAnimation() { if (stepsInterval) clearInterval(stepsInterval); }

        submitBtn.onclick = async () => {
            if (userSubscriptionStatus !== 'paid') {
                try {
                    const response = await fetch('/api/check-edit-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);

            submitBtn.disabled = true; promptInput.disabled = true;
            document.getElementById('btn-text').style.display = 'none';
            document.querySelector('.spinner').style.display = 'inline-block';
            const originalPrompt = promptInput.value.trim();

            imageResultContainer.innerHTML = `
                <div class="generator-container" style="display:flex;">
                    <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" id="loading-text">در حال پردازش و ویرایش...</div>
                    <div class="progress-bar" id="tv-progress-bar"></div>
                </div>
            `;

            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);
                    }
                    warnDiv.innerHTML = '⏳ پردازش تصویر بیش از حد طولانی شد.<br>ممکن است سرور شلوغ باشد. می‌توانید مجدداً تلاش کنید.';
                    submitBtn.disabled = false; promptInput.disabled = false;
                    document.getElementById('btn-text').style.display = 'inline-block';
                    document.querySelector('.spinner').style.display = 'none';
                    document.getElementById('btn-text').innerHTML = 'تلاش مجدد';
                }
            }, 120000);

            startFakeProgress(50);
            isResultProcessed = false;

            const formData = new FormData();
            formData.append('image', uploadedFile);
            if (uploadedFile2) formData.append('image2', uploadedFile2);
            if (uploadedFile3) formData.append('image3', uploadedFile3);
            formData.append('prompt', originalPrompt);

            try {
                const res = await fetch('/api/edit', { method: 'POST', body: formData });
                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-edit-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="width:100%;text-align:center;font-weight:800;font-size:1.15rem;color:var(--accent-primary);margin-bottom:4px;">ویرایش شما آماده شد! 🎨</div>
                                    <div class="result-images-wrapper">

                                        <!-- تصویر ویرایش شده معمولی -->
                                        <div class="result-card">
                                            <div class="result-card-label">
                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                                                تصویر ویرایش شده
                                            </div>
                                            <img id="result-image-display" src="${statusData.url}" alt="تصویر ویرایش شده">
                                            <button class="download-btn" onclick="triggerDownload('${absoluteUrl}')">
                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:20px;height:20px;"><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>

                                        <!-- ✨ باکیفیت شده — premium card -->
                                        <div class="upscaled-card" id="upscaled-card">
                                            <div class="upscaled-header">
                                                <div class="upscaled-title-row">
                                                    <div class="upscaled-icon">✦</div>
                                                    <div class="upscaled-title">
                                                        <div class="upscaled-title-main">ارتقای کیفیت هوش مصنوعی</div>
                                                        <div class="upscaled-title-sub">پردازش با CodeFormer Neural Engine</div>
                                                    </div>
                                                </div>
                                                <div class="upscaled-badges">
                                                    <span class="tech-badge gold"><span class="badge-dot"></span>CodeFormer</span>
                                                    <span class="tech-badge purple"><span class="badge-dot"></span>Face Restore</span>
                                                    <span class="tech-badge blue"><span class="badge-dot"></span>4× Upscale</span>
                                                </div>
                                            </div>

                                            <!-- Loading state -->
                                            <div class="upscaled-loading" id="upscaled-loading-container">
                                                <div class="upscaled-loading-visual">
                                                    <div class="upscaled-loading-ring"></div>
                                                    <div class="upscaled-loading-ring"></div>
                                                    <div class="upscaled-loading-ring"></div>
                                                    <div class="upscaled-loading-core"></div>
                                                </div>
                                                <div class="upscaled-loading-text">
                                                    هوش مصنوعی در حال بازسازی جزئیات تصویر...<br>
                                                    <span style="font-size:0.78rem;color:#B45309;font-weight:500;">این مرحله ممکن است چند دقیقه طول بکشد</span>
                                                </div>
                                                <div class="upscaled-loading-steps">
                                                    ${stepLabels.map(l => `<span class="upscaled-step">${l}</span>`).join('')}
                                                </div>
                                            </div>

                                            <!-- Result image (hidden until ready) -->
                                            <div class="upscaled-image-reveal" id="upscaled-image-reveal">
                                                <div class="upscaled-image-frame">
                                                    <img id="result-upscaled-image-display" src="" alt="تصویر باکیفیت شده">
                                                </div>
                                                <div class="upscaled-info-strip" id="upscaled-info-strip"></div>
                                            </div>

                                            <button id="download-upscaled-btn" class="download-upscaled-btn-premium">
                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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>
                                `;

                                // Start step animation
                                animateUpscaleSteps();

                                // Save edited image to history
                                try {
                                    const imgRes = await fetch(absoluteUrl);
                                    if (imgRes.ok) { const blob = await imgRes.blob(); await saveToHistory(blob, originalPrompt); }
                                } catch(e) { console.error('Failed to save history blob', e); }

                                pollUpscaledImage(data.run_id, originalPrompt);
                                resetBtn();
                            }
                        } catch(e) { console.error('Polling error', e); }
                    }, 3500);
                } else {
                    displayError('خطا در ارتباط با گیت‌هاب سرور.');
                }
            } catch (e) {
                displayError('خطای اتصال به سرور!');
            }
        };

        function displayError(msg) {
            clearInterval(fakeProgressInterval); clearTimeout(activeTimeoutTimer);
            imageResultContainer.innerHTML = `<div style="color:var(--danger-color);font-weight:bold;text-align:center;padding:2rem;">خطا: ${msg}</div>`;
            resetBtn();
        }

        function resetBtn() {
            submitBtn.disabled = false; promptInput.disabled = false;
            document.getElementById('btn-text').style.display = 'inline-block';
            document.getElementById('btn-text').textContent = 'ایجاد کن';
            document.querySelector('.spinner').style.display = 'none';
            checkFormState();
        }

        // Poll upscaled result
        function pollUpscaledImage(runId, promptText) {
            let elapsed = 0;
            const upscaledPollTimer = setInterval(async () => {
                elapsed += 3;
                if (elapsed > 300) {
                    clearInterval(upscaledPollTimer);
                    stopStepsAnimation();
                    const loadingContainer = document.getElementById('upscaled-loading-container');
                    if (loadingContainer) {
                        loadingContainer.innerHTML = `
                            <div style="display:flex;flex-direction:column;align-items:center;gap:8px;padding:1rem;">
                                <span style="font-size:1.5rem;">⚠️</span>
                                <span style="font-size:0.82rem;color:#92400E;font-weight:600;text-align:center;line-height:1.6;">ارتقای کیفیت به دلیل ترافیک بالای سرور انجام نشد.<br>تصویر ویرایش شده فوق در دسترس است.</span>
                            </div>`;
                    }
                    return;
                }

                try {
                    const statusRes = await fetch(`/api/status/${runId}_upscaled`);
                    const statusData = await statusRes.json();

                    if (statusData.status === 'ready') {
                        clearInterval(upscaledPollTimer);
                        stopStepsAnimation();

                        const upscaledUrl = statusData.url;
                        const absoluteUpscaledUrl = window.location.origin + upscaledUrl;

                        const loadingContainer = document.getElementById('upscaled-loading-container');
                        const revealDiv = document.getElementById('upscaled-image-reveal');
                        const upscaledImg = document.getElementById('result-upscaled-image-display');
                        const downloadBtn = document.getElementById('download-upscaled-btn');

                        if (loadingContainer) loadingContainer.style.display = 'none';

                        if (upscaledImg) {
                            upscaledImg.src = upscaledUrl;
                            upscaledImg.onclick = () => viewHistoryImage(absoluteUpscaledUrl, promptText + " (باکیفیت شده)", true);
                        }

                        if (revealDiv) revealDiv.classList.add('visible');

                        if (downloadBtn) {
                            downloadBtn.classList.add('visible');
                            downloadBtn.onclick = () => triggerDownload(absoluteUpscaledUrl);
                        }

                        // Show file size
                        calculateAndShowSizeAsync(absoluteUpscaledUrl, 'upscaled-info-strip');

                        // Save upscaled to history
                        try {
                            const imgRes = await fetch(absoluteUpscaledUrl);
                            if (imgRes.ok) {
                                const blob = await imgRes.blob();
                                await saveToHistory(blob, promptText + " (باکیفیت شده)");
                            }
                        } catch (e) { console.error('Failed to save upscaled history blob', e); }
                    }
                } catch (e) { console.error('Upscaled polling error', e); }
            }, 3000);
        }

        function formatBytes(bytes, decimals = 2) {
            if (bytes === 0) return '0 بایت';
            const k = 1024, dm = decimals < 0 ? 0 : decimals;
            const sizes = ['بایت', 'کیلوبایت', 'مگابایت'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        }

        async function calculateAndShowSizeAsync(url, containerId) {
            try {
                const response = await fetch(url, { method: 'HEAD' });
                if (!response.ok) return;
                const contentLength = response.headers.get('content-length');
                if (contentLength) {
                    const sizeInBytes = parseInt(contentLength, 10);
                    const container = document.getElementById(containerId);
                    if (container) {
                        container.innerHTML = `
                            <div class="upscaled-info-chip size-chip">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg>
                                حجم فایل: ${formatBytes(sizeInBytes)}
                            </div>
                            <div class="upscaled-info-chip size-chip">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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>
                                کیفیت بالا
                            </div>
                        `;
                    }
                }
            } catch (err) { console.warn("امکان دریافت حجم تصویر فراهم نشد:", err); }
        }

        // --- Init ---
        document.addEventListener('DOMContentLoaded', async () => {
            userFingerprint = await getBrowserFingerprint();
            parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*');
            try {
                await initDB();
                const savedInput = await getInputImage('current_input');
                if (savedInput) { uploadedFile = savedInput; const r = new FileReader(); r.onload = e => { previewImage.src = e.target.result; }; r.readAsDataURL(savedInput); uploadArea.classList.add('has-file'); }
                const savedInput2 = await getInputImage('current_input_2');
                if (savedInput2) { uploadedFile2 = savedInput2; const r = new FileReader(); r.onload = e => { previewImage2.src = e.target.result; }; r.readAsDataURL(savedInput2); uploadArea2.classList.add('has-file'); }
                const savedInput3 = await getInputImage('current_input_3');
                if (savedInput3) { uploadedFile3 = savedInput3; const r = new FileReader(); r.onload = e => { previewImage3.src = e.target.result; }; r.readAsDataURL(savedInput3); uploadArea3.classList.add('has-file'); }
                checkFormState();
                await loadHistory();
            } catch (e) { console.error(e); }
        });

        // Neural network canvas animation
        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, maxDistance = 100;
            const computedStyles = getComputedStyle(document.documentElement);
            const particleColor = computedStyles.getPropertyValue('--accent-primary').trim();
            const lineColor = computedStyles.getPropertyValue('--text-tertiary').trim();
            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, 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() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(p => { p.update(); p.draw(); }); connectParticles(); requestAnimationFrame(animate); }
            window.addEventListener('resize', resizeCanvas);
            resizeCanvas(); animate();
        });
    </script>
</body>
</html>