File size: 58,260 Bytes
86c5d02
 
 
 
 
18806ac
86c5d02
 
 
1df78e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db68f2
86c5d02
 
1df78e5
86c5d02
5db68f2
86c5d02
5db68f2
18806ac
750e40d
1df78e5
5db68f2
 
 
 
 
 
 
 
 
1df78e5
 
 
750e40d
 
 
 
 
5db68f2
1df78e5
5db68f2
86c5d02
1df78e5
 
86c5d02
18806ac
5db68f2
1df78e5
 
 
86c5d02
1df78e5
 
86c5d02
1df78e5
 
86c5d02
1aa8c20
18806ac
5db68f2
 
 
18806ac
5db68f2
 
 
 
1df78e5
 
750e40d
 
 
 
2dde19d
 
18806ac
2dde19d
 
 
 
 
 
 
 
 
1df78e5
 
 
 
 
 
 
 
 
 
 
5db68f2
 
18806ac
2af51ca
5db68f2
 
2dde19d
5db68f2
 
 
 
 
 
18806ac
5db68f2
 
 
 
 
 
 
 
 
 
2dde19d
5db68f2
 
 
 
 
18806ac
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86c5d02
 
 
 
 
1df78e5
5db68f2
 
 
 
 
86c5d02
1aa8c20
86c5d02
1aa8c20
1df78e5
18806ac
1df78e5
 
86c5d02
1df78e5
18806ac
1df78e5
 
86c5d02
1aa8c20
86c5d02
18806ac
86c5d02
18806ac
86c5d02
18806ac
 
1df78e5
 
5db68f2
18806ac
750e40d
 
 
86c5d02
18806ac
86c5d02
 
 
 
18806ac
86c5d02
1df78e5
18806ac
 
1df78e5
5db68f2
2dde19d
 
 
1df78e5
86c5d02
 
 
18806ac
5db68f2
 
 
18806ac
5db68f2
 
 
1aa8c20
5db68f2
1aa8c20
86c5d02
18806ac
 
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fb4c45
5db68f2
4fb4c45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db68f2
 
 
 
 
 
 
 
750e40d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db68f2
 
 
 
 
750e40d
 
 
 
5db68f2
18806ac
 
 
 
 
 
5db68f2
18806ac
 
5db68f2
 
 
 
bce119b
5db68f2
18806ac
 
5db68f2
 
18806ac
 
 
 
 
bce119b
86c5d02
5db68f2
18806ac
 
 
5db68f2
18806ac
86c5d02
18806ac
 
 
 
 
86c5d02
18806ac
750e40d
 
18806ac
 
 
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18806ac
5db68f2
 
 
750e40d
5db68f2
 
 
 
 
bce119b
5db68f2
18806ac
750e40d
 
 
 
 
 
 
 
 
 
 
 
 
 
5db68f2
 
 
18806ac
5db68f2
18806ac
 
 
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18806ac
 
 
5db68f2
18806ac
 
1df78e5
 
 
 
bce119b
1df78e5
bce119b
86c5d02
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dde19d
 
2af51ca
5db68f2
2dde19d
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86c5d02
5db68f2
86c5d02
18806ac
 
86c5d02
 
 
18806ac
5db68f2
 
 
18806ac
 
 
 
 
5db68f2
18806ac
5db68f2
18806ac
5db68f2
18806ac
 
5db68f2
18806ac
750e40d
 
18806ac
5db68f2
 
 
 
 
 
 
 
 
 
 
 
 
 
18806ac
 
 
1aa8c20
1df78e5
18806ac
1df78e5
86c5d02
 
750e40d
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
<!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;
            --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); } }

        * { 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 */
        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; }
        
        /* Badge */
        #subscription-status-badge { display: none; padding: 6px 16px; border-radius: 20px; font-size: 0.85em; font-weight: 700; margin-top: 1rem; display: inline-block; animation: badge-fade-in 0.6s 0.5s ease-out backwards; 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); }

        /* Panels */
        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-area { position: relative; border: 2px dashed var(--input-border); border-radius: var(--radius-input); padding: 2.5rem; text-align: center; cursor: pointer; transition: var(--transition-smooth); background-color: var(--input-bg); min-height: 200px; display: flex; flex-direction: column; justify-content: center; align-items: center; overflow: hidden; }
        #upload-area.drag-over, #upload-area:hover:not(.has-file) { border-color: var(--accent-primary); background-color: #fff; box-shadow: 0 0 15px var(--accent-primary-glow); }
        #upload-area.has-file { border-style: solid; border-color: var(--panel-border); padding: 0; cursor: default; }
        #upload-content { display: flex; flex-direction: column; align-items: center; gap: 1rem; }
        #upload-icon svg { width: 48px; height: 48px; color: var(--accent-primary); stroke-width: 1.5; opacity: 0.8; }
        #upload-area p { margin: 0; color: var(--text-secondary); font-weight: 500; }
        #preview-image-main { display: none; width: 100%; height: 100%; object-fit: contain; position: absolute; top: 0; left: 0; }
        #remove-file-btn-main { display: none; position: absolute; top: 12px; right: 12px; background-color: rgba(26, 32, 44, 0.6); color: white; border: none; width: 32px; height: 32px; border-radius: 50%; cursor: pointer; font-size: 1.2rem; line-height: 1; z-index: 10; transition: var(--transition-smooth); padding: 0; }
        #remove-file-btn-main:hover { background-color: var(--danger-color); transform: scale(1.1); }
        #upload-area.has-file #upload-content { display: none; }
        #upload-area.has-file #preview-image-main, #upload-area.has-file #remove-file-btn-main { display: block; }
        
        /* 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 Standardized --- */
        #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); }
        
        .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); }

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

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

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

        @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;}
        }
    </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>
                <label id="upload-area" for="file-input">
                    <div id="upload-content">
                        <div id="upload-icon"><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>فایل تصویر را اینجا بکشید یا برای انتخاب کلیک کنید</p>
                    </div>
                    <img id="preview-image-main" src="" alt="Preview">
                    <button type="button" id="remove-file-btn-main" title="حذف تصویر">&times;</button>
                </label>
                <input type="file" id="file-input" accept="image/png, image/jpeg, image/webp" hidden>
            </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" 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>
        // --- توابع پاپ‌آپ سفارشی ---
        function showCustomConfirm(title, message, onConfirm) {
            const backdrop = document.createElement('div');
            backdrop.className = 'confirm-modal-backdrop';
            
            const content = document.createElement('div');
            content.className = 'confirm-modal-content';
            
            content.innerHTML = `
                <div class="confirm-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"></path><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
                </div>
                <div class="confirm-title">${title}</div>
                <div class="confirm-message">${message}</div>
                <div class="confirm-actions">
                    <button class="confirm-btn btn-cancel" id="confirm-cancel">انصراف</button>
                    <button class="confirm-btn btn-danger" id="confirm-ok">تایید و حذف</button>
                </div>
            `;
            
            backdrop.appendChild(content);
            document.body.appendChild(backdrop);
            
            const close = () => {
                backdrop.style.opacity = '0';
                setTimeout(() => backdrop.remove(), 300);
            };
            
            backdrop.querySelector('#confirm-cancel').onclick = close;
            backdrop.querySelector('#confirm-ok').onclick = () => {
                onConfirm();
                close();
            };
            backdrop.onclick = (e) => {
                if(e.target === backdrop) close();
            }
        }

        // --- مدیریت دیتابیس (ذخیره Blob بجای URL) ---
        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(blob) {
            return new Promise((resolve, reject) => {
                if (!db) return resolve();
                const tx = db.transaction([inputStore], 'readwrite');
                tx.objectStore(inputStore).put({ id: 'current_input', blob: blob });
                tx.oncomplete = () => resolve();
                tx.onerror = () => reject();
            });
        }

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

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

        // توابع سابقه (History)
        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);
                const newItem = {
                    blob: blob,
                    prompt: prompt,
                    timestamp: Date.now()
                };
                store.add(newItem);

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

        async function loadHistory() {
            if (!db) await initDB();
            return new Promise((resolve, reject) => {
                const transaction = db.transaction([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 safeTitle = item.prompt.replace(/"/g, '&quot;');
                const div = document.createElement('div');
                div.className = 'history-item';

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

                grid.appendChild(div);
            });
        }

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

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

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

    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(promptText).then(showSuccess).catch(fallbackCopy);
    } else {
        fallbackCopy();
    }
};

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

        // --- تنظیمات حساب و ارتباط با والد ---
        let userSubscriptionStatus = 'free';
        let userFingerprint = null;
        let countdownInterval = null;
        let 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 fingerprintString = components.join('---'); 
            let hash = 0; 
            for (let i = 0; i < fingerprintString.length; i++) { hash = ((hash << 5) - hash) + fingerprintString.charCodeAt(i); hash |= 0; } 
            return 'fp_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); 
                const m = Math.floor((timeLeft % 3600) / 60); 
                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 }, '*');
        };

        // --- مدیریت آپلود و متغیرها ---
        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 promptInput = document.getElementById('prompt-input');
        const submitBtn = document.getElementById('submit-btn');
        const imageResultContainer = document.getElementById('image-result-container');
        
        let uploadedFile = null;
        let activePollTimer = null;
        let activeTimeoutTimer = null;
        let fakeProgressInterval = null;
        let isResultProcessed = false;

        async function handleFile(file) {
            if (!file || !file.type.startsWith('image/')) return alert('لطفاً یک تصویر انتخاب کنید.');
            uploadedFile = file;
            await saveInputImage(file); // ذخیره در دیتابیس برای ماندگاری بعد از رفرش
            
            const reader = new FileReader();
            reader.onload = (e) => { previewImage.src = e.target.result; };
            reader.readAsDataURL(file);
            uploadArea.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(); // حذف از دیتابیس
            checkFormState();
        };

        fileInput.onchange = (e) => handleFile(e.target.files[0]);
        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]); };
        
        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%';
        }

        // --- ارسال درخواست به سرور ---
        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);
            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="font-weight: bold; margin-bottom: 15px; color: var(--accent-primary); text-align:center; font-size: 1.1rem;">ویرایش شما آماده شد! 🎨</div>
                                    <div class="generated-image-box">
                                        <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" stroke-linecap="round" stroke-linejoin="round" style="width: 22px; height: 22px;"><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>
                                `;

                                // ذخیره مستقیم فایل Blob در دیتابیس تاریخچه
                                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);
                                }
                                
                                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();
        }

        // --- راه‌اندازی اولیه ---
        document.addEventListener('DOMContentLoaded', async () => {
            userFingerprint = await getBrowserFingerprint(); 
            parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*'); 
            try {
                await initDB();
                
                // بازیابی تصویر کاربر در صورت رفرش صفحه
                const savedInput = await getInputImage();
                if (savedInput) {
                    uploadedFile = savedInput;
                    const reader = new FileReader();
                    reader.onload = (e) => { previewImage.src = e.target.result; };
                    reader.readAsDataURL(savedInput);
                    uploadArea.classList.add('has-file');
                    checkFormState();
                }

                await loadHistory();
            } catch (e) {
                console.error(e);
            }
        });

        // انیمیشن شبکه عصبی هدر
        document.addEventListener('DOMContentLoaded', () => { const canvas = document.getElementById('neural-network-canvas'); if (!canvas) return; const header = canvas.parentElement; const ctx = canvas.getContext('2d'); let particles = []; const particleCount = 20; const maxDistance = 100; const 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; const dy = particles[i].y - particles[j].y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < maxDistance) { ctx.beginPath(); ctx.moveTo(particles[i].x, particles[i].y); ctx.lineTo(particles[j].x, particles[j].y); ctx.strokeStyle = lineColor; ctx.lineWidth = 0.2; ctx.globalAlpha = 1 - distance / maxDistance; ctx.stroke(); } } } ctx.globalAlpha = 1; } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(particle => { particle.update(); particle.draw(); }); connectParticles(); requestAnimationFrame(animate); } window.addEventListener('resize', resizeCanvas); resizeCanvas(); animate(); });
    </script>
</body>
</html>