File size: 52,249 Bytes
aecade4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>استودیو ویدیو هوشمند</title>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --app-font: 'Vazirmatn', sans-serif; --app-bg: #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;
            --success-color: #38A169; --danger-color: #E53E3E; --danger-color-hover: #c53030; --danger-glow: rgba(229, 62, 62, 0.25);
            --warning-color: #f59e0b; --warning-glow: rgba(245, 158, 11, 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-xl: 0 20px 25px -5px rgba(26, 32, 44, 0.07), 0 8px 10px -6px rgba(26, 32, 44, 0.05);
            --radius-card: 24px; --radius-btn: 14px; --radius-input: 12px;
            --transition-smooth: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
        }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes core-pulse { 0%, 100% { transform: scale(0.95); box-shadow: 0 0 25px var(--accent-primary-glow); } 50% { transform: scale(1.05); box-shadow: 0 0 50px rgba(74, 108, 250, 0.5); } }
        @keyframes ring-rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes slideInUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes button-pulse { 0% { box-shadow: 0 0 0 0 rgba(74, 108, 250, 0.7); } 70% { box-shadow: 0 0 0 12px rgba(74, 108, 250, 0); } 100% { box-shadow: 0 0 0 0 rgba(74, 108, 250, 0); } }
        @keyframes hint-fade-in-out { 0%, 100% { opacity: 0; transform: translateY(10px); } 15%, 85% { opacity: 1; transform: translateY(0); } }
        @keyframes fadeOutUp { from { opacity: 1; transform: translateY(0); } to { opacity: 0; transform: translateY(-50px); } }
        @keyframes shake { 10%, 90% { transform: translate3d(-1px, 0, 0); } 20%, 80% { transform: translate3d(2px, 0, 0); } 30%, 50%, 70% { transform: translate3d(-4px, 0, 0); } 40%, 60% { transform: translate3d(4px, 0, 0); } }

        body { font-family: var(--app-font); background-color: var(--app-bg); color: var(--text-primary); margin: 0; padding: 2.5rem 1rem; display: flex; justify-content: center; align-items: flex-start; min-height: 100vh; }
        .container { max-width: 820px; width: 100%; }
        header { position: relative; text-align: center; margin-bottom: 2.5rem; animation: fadeIn 0.8s 0.1s ease-out backwards; overflow: hidden; padding: 2rem 0; }
        #neural-network-canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; opacity: 0.7; }
        .header-content { position: relative; z-index: 2; }
        .ai-orb-container { width: 150px; height: 150px; margin: 0 auto 1rem; position: relative; display: flex; align-items: center; justify-content: center; }
        .orb-core { width: 70px; height: 70px; border-radius: 50%; background: radial-gradient(circle, #394A7A 0%, #1A202C 70%); box-shadow: 0 0 25px var(--accent-primary-glow); display: flex; align-items: center; justify-content: center; animation: core-pulse 4s ease-in-out infinite; border: 1px solid rgba(74, 108, 250, 0.3); }
        .face-icon { width: 32px; height: 32px; color: var(--accent-secondary); filter: drop-shadow(0 0 8px rgba(15, 212, 168, 0.7)); transition: var(--transition-smooth); }
        .orb-ring { position: absolute; top: 50%; left: 50%; border-style: solid; border-color: transparent; border-radius: 50%; mix-blend-mode: screen; }
        .orb-ring.one { width: 100px; height: 100px; margin-top: -50px; margin-left: -50px; border-width: 2px; border-top-color: var(--accent-primary); border-right-color: var(--accent-primary); animation: ring-rotate 8s linear infinite; }
        .orb-ring.two { width: 120px; height: 120px; margin-top: -60px; margin-left: -60px; border-width: 1px; border-bottom-color: var(--accent-secondary); animation: ring-rotate 10s linear infinite reverse; }
        h1 { font-size: 2.8rem; font-weight: 800; margin: 0; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .subtitle { font-size: 1.1rem; color: var(--text-secondary); margin-top: 0.5rem; }
        main { 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; }
        .form-group { margin-bottom: 2.5rem; }
        .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-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
        .drop-zone { position: relative; border: 2px dashed var(--input-border); border-radius: var(--radius-input); padding: 1.5rem; text-align: center; cursor: pointer; transition: var(--transition-smooth); background-color: var(--input-bg); min-height: 150px; display: flex; flex-direction: column; justify-content: center; align-items: center; overflow: hidden; }
        .drop-zone.drag-over, .drop-zone:hover:not(.has-file) { border-color: var(--accent-primary); background-color: #fff; box-shadow: 0 0 15px var(--accent-primary-glow); }
        .drop-zone.has-file { border-style: solid; border-color: var(--success-color); padding: 0; cursor: default; background-color: #000; }
        .upload-content { display: flex; flex-direction: column; align-items: center; gap: 0.5rem; }
        .upload-content p { font-size: 0.9rem; }
        .upload-icon svg { width: 32px; height: 32px; color: var(--accent-primary); }
        .preview-img, .preview-vid { display: none; width: 100%; height: 100%; object-fit: contain; position: absolute; top: 0; left: 0; }
        .drop-zone.has-file .upload-content { display: none; }
        .drop-zone.has-file .preview-img, .drop-zone.has-file .preview-vid { display: block; }
        .remove-file-btn { position: absolute; top: 8px; left: 8px; width: 28px; height: 28px; background-color: rgba(26, 32, 44, 0.7); color: white; border: none; border-radius: 50%; font-size: 18px; cursor: pointer; opacity: 0; visibility: hidden; transition: all 0.25s ease-out; z-index: 10; }
        .drop-zone.has-file:hover .remove-file-btn { opacity: 1; visibility: visible; }
        .remove-file-btn:hover { background-color: var(--danger-color); transform: scale(1.1) rotate(90deg); }
        .radio-group { display: flex; flex-wrap: wrap; gap: 1rem; }
        .radio-label { flex: 1; min-width: 120px; padding: 1rem; border: 2px solid var(--input-border); border-radius: var(--radius-btn); cursor: pointer; transition: var(--transition-smooth); text-align: center; font-weight: 600; }
        .radio-label:hover { border-color: var(--accent-primary); }
        .radio-input { display: none; }
        .radio-input:checked + .radio-label { border-color: var(--accent-primary); background-color: var(--accent-primary-glow); color: var(--accent-primary); box-shadow: 0 0 10px var(--accent-primary-glow); }
        .hint-container { min-height: 40px; display: flex; justify-content: center; align-items: center; margin-top: 1rem; }
        .motion-hint { color: var(--text-secondary); font-size: 0.9rem; text-align: center; opacity: 0; transition: var(--transition-smooth); }
        .motion-hint.visible { animation: hint-fade-in-out 4s ease-in-out forwards; }
        #generateButton { box-sizing: border-box; display: flex; align-items: center; justify-content: center; gap: 0.75rem; width: 100%; padding: 0.9rem; font-size: 1.1rem; font-weight: 700; background: linear-gradient(95deg, var(--accent-secondary) 0%, var(--accent-primary) 100%); color: #fff; border: none; border-radius: var(--radius-btn); cursor: pointer; transition: all 0.3s ease; box-shadow: 0 6px 12px -3px var(--accent-primary-glow); margin-top: 1rem; }
        #generateButton svg { width: 24px; height: 24px; flex-shrink: 0; }
        #generateButton:hover:not(:disabled) { transform: translateY(-5px) scale(1.02); box-shadow: 0 8px 20px -4px var(--accent-primary-glow); }
        #generateButton:disabled { background: var(--text-tertiary); cursor: not-allowed; opacity: 0.7; transform: none; box-shadow: none; }
        #results-gallery { display: flex; flex-direction: column; gap: 1.5rem; }
        .job-card { background: var(--panel-bg); border-radius: var(--radius-card); padding: 1.5rem; border: 1px solid var(--panel-border); box-shadow: var(--shadow-md); animation: slideInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1); transition: transform 0.4s ease, opacity 0.4s ease; }
        .job-card.deleting { animation: fadeOutUp 0.5s ease-out forwards; }
        .job-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; }
        .job-id { font-family: 'Courier New', monospace; font-size: 0.8rem; background-color: var(--input-bg); padding: 0.25rem 0.5rem; border-radius: 6px; }
        .job-status { font-weight: 600; font-size: 0.9rem; text-align: left; transition: color 0.3s ease; }
        .job-card.in-progress { background: linear-gradient(135deg, #1e293b, #0f172a); color: #e2e8f0; border-color: #334155; box-shadow: var(--shadow-xl); position: relative; overflow: hidden; padding-bottom: 2rem; }
        .job-card.in-progress .job-id { background-color: rgba(255, 255, 255, 0.1); }
        .job-card.in-progress .job-body { display: flex; flex-direction: column; align-items: center; gap: 1rem; margin-top: 1.5rem; }
        .in-progress-controls { display: flex; justify-content: center; align-items: center; gap: 1rem; margin-top: 0.5rem; }
        .timer-container { position: relative; width: 160px; height: 160px; transition: opacity 0.5s ease, transform 0.5s ease; }
        .timer-svg { transform: rotate(-90deg); width: 100%; height: 100%; }
        .timer-circle-bg { fill: none; stroke: rgba(255, 255, 255, 0.15); stroke-width: 10; }
        .timer-circle-progress { fill: none; stroke: url(#timer-gradient); stroke-width: 10; stroke-linecap: round; transition: stroke-dashoffset 1s linear; }
        .timer-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 2.2rem; font-weight: 700; color: #fff; font-family: 'Courier New', monospace; }
        .reassurance-message { text-align: center; background: rgba(255, 255, 255, 0.05); padding: 1rem; border-radius: var(--radius-btn); border: 1px solid rgba(255, 255, 255, 0.1); font-size: 0.9rem; color: var(--text-tertiary); max-width: 90%; margin: 1.5rem 0; line-height: 1.7; }
        .reassurance-message strong { color: #fff; font-weight: 600; }
        .quick-check-btn { display: flex; align-items: center; gap: 0.5rem; background: var(--accent-primary); color: #fff; border: none; padding: 0.8rem 1.8rem; border-radius: var(--radius-btn); font-weight: 600; cursor: pointer; transition: var(--transition-smooth); animation: button-pulse 2.5s infinite; }
        .quick-check-btn:hover:not(:disabled) { background: var(--accent-primary-hover); transform: scale(1.05); animation-play-state: paused; }
        .quick-check-btn:disabled { background: var(--text-secondary); cursor: wait; }
        .quick-check-feedback { min-height: 20px; font-size: 0.9rem; color: var(--text-tertiary); opacity: 0; transform: translateY(10px); transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); }
        .quick-check-feedback.visible { opacity: 1; transform: translateY(0); }
        .job-card.completed video { width: 100%; border-radius: var(--radius-input); margin-top: 1rem; background-color: #000; }
        .job-card.error .job-body { color: var(--danger-color); background: rgba(229, 62, 62, 0.05); padding: 1rem; border-radius: var(--radius-input); border: 1px solid rgba(229, 62, 62, 0.2); font-family: monospace; direction: ltr; text-align: left; white-space: pre-wrap; margin-bottom: 1rem; }
        .video-controls { display: flex; justify-content: center; align-items: center; gap: 1rem; margin-top: 1rem; }
        .video-button { padding: 0.7rem 1.5rem; border-radius: var(--radius-btn); border: 1px solid var(--input-border); cursor: pointer; font-weight: 600; transition: var(--transition-smooth); background-color: var(--input-bg); color: var(--text-secondary); text-decoration: none; display: inline-flex; align-items: center; justify-content: center; font-family: var(--app-font); font-size: 1rem;}
        .video-button:hover { background-color: var(--panel-border); color: var(--text-primary); }
        .delete-job-btn { padding: 0.7rem; line-height: 0; background-color: transparent; }
        .delete-job-btn svg { width: 18px; height: 18px; color: var(--text-tertiary); transition: color 0.3s ease; }
        .delete-job-btn:hover { background-color: var(--danger-glow); }
        .delete-job-btn:hover svg { color: var(--danger-color); }
        .delete-job-btn.hidden { display: none; }
        
        .modal-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(26, 32, 44, 0.7); 
            z-index: 1000; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(5px);
            opacity: 0; visibility: hidden; transition: opacity 0.3s ease, visibility 0.3s ease;
        }
        .modal-overlay.visible {
            opacity: 1; visibility: visible;
        }
        .modal-box, .alert-box { 
            background: var(--panel-bg); padding: 2.5rem; border-radius: var(--radius-card); text-align: center;
            max-width: 400px; box-shadow: var(--shadow-xl); transform: scale(0.95) translateY(20px);
            opacity: 0; transition: transform 0.4s cubic-bezier(0.25, 0.8, 0.25, 1), opacity 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
        }
        .modal-overlay.visible .modal-box, .modal-overlay.visible .alert-box {
            transform: scale(1) translateY(0); opacity: 1;
        }
        .alert-box h3 { margin-top: 0; font-size: 1.5rem; }
        .alert-box p { color: var(--text-secondary); margin-bottom: 2rem; }
        .alert-box button { background: var(--accent-primary); color: #fff; border: none; padding: 0.8rem 2rem; border-radius: var(--radius-btn); cursor: pointer; font-weight: 600; transition: var(--transition-smooth); }
        .alert-box button:hover { background: var(--accent-primary-hover); transform: scale(1.05); }
        #validation-modal .alert-box { animation: shake 0.6s cubic-bezier(.36,.07,.19,.97) both; }
        #validation-modal .alert-box h3 { color: var(--warning-color); display: flex; justify-content: center; align-items: center; gap: 0.5rem; }
        #validation-modal .alert-box svg { width: 28px; height: 28px; }
        #validation-modal .alert-box button { background: var(--warning-color); box-shadow: 0 4px 14px 0 var(--warning-glow); }
        #validation-modal .alert-box button:hover { background: #d97706; }
        .modal-box { max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto; text-align: right; }
        .modal-box h2 { font-size: 1.8rem; font-weight: 800; margin-top: 0; margin-bottom: 0.5rem; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .modal-box .intro-text { color: var(--text-secondary); margin-bottom: 2rem; line-height: 1.8; }
        .modal-box h3 { font-size: 1.2rem; font-weight: 700; margin-bottom: 1rem; border-bottom: 2px solid var(--panel-border); padding-bottom: 0.5rem; text-align: center;}
        .modal-box .rules-list { list-style: none; padding-right: 0; counter-reset: rule-counter; }
        .modal-box .rules-list li { position: relative; padding-right: 40px; margin-bottom: 1rem; line-height: 1.7; color: var(--text-secondary); }
        .modal-box .rules-list li::before { counter-increment: rule-counter; content: counter(rule-counter); position: absolute; right: 0; top: 0; width: 28px; height: 28px; border-radius: 50%; background: var(--accent-primary-glow); color: var(--accent-primary); display: flex; align-items: center; justify-content: center; font-weight: 700; }
        .modal-actions { margin-top: 2rem; text-align: center; display: flex; gap: 1rem; justify-content: center; }
        #accept-terms-btn { width: 100%; padding: 1rem; font-size: 1.1rem; font-weight: 700; background: linear-gradient(95deg, var(--accent-secondary) 0%, var(--accent-primary) 100%); color: #fff; border: none; border-radius: var(--radius-btn); cursor: pointer; transition: var(--transition-smooth); box-shadow: 0 6px 12px -3px var(--accent-primary-glow); }
        #accept-terms-btn:hover { transform: translateY(-3px) scale(1.02); box-shadow: 0 8px 20px -4px var(--accent-primary-glow); }
        .exit-notice { font-size: 0.8rem; color: var(--text-tertiary); margin-top: 1rem; }
        .modal-actions button { flex-grow: 1; padding: 0.8rem 1.5rem; border-radius: var(--radius-btn); border: none; font-weight: 700; cursor: pointer; transition: all 0.25s ease; font-family: var(--app-font); }
        .modal-actions .confirm-delete-btn { background-color: var(--danger-color); color: white; box-shadow: 0 4px 14px 0 var(--danger-glow); }
        .modal-actions .confirm-delete-btn:hover { background-color: var(--danger-color-hover); transform: translateY(-2px); box-shadow: 0 6px 20px 0 var(--danger-glow); }
        .modal-actions .cancel-delete-btn { background-color: var(--input-bg); color: var(--text-secondary); border: 1px solid var(--input-border); }
        .modal-actions .cancel-delete-btn:hover { background-color: var(--panel-border); color: var(--text-primary); transform: translateY(-2px); }
    </style>
</head>
<body>
    <div class="container">
        <!-- هدر و فرم -->
        <header>
            <canvas id="neural-network-canvas"></canvas>
            <div class="header-content">
                 <div class="ai-orb-container">
                    <div class="orb-core"><svg class="face-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/><circle cx="12" cy="12" r="3"/></svg></div>
                    <div class="orb-ring one"></div><div class="orb-ring two"></div>
                </div>
                <h1>انیماتور ویدیو هوش مصنوعی آلفا</h1>
                <p class="subtitle">تغییر چهره در حالت واقعی با هوش مصنوعی آلفا ~ با توجه به اینکه این مدل برای تولید ویدیو زمان زیادی رو لازم داره هر بار تا 3 درخواست رو میتونید همزمان برای مدل ارسال کنید و صفحه رو ترک کنید،  همه کارها سمت سرور انجام میشه و میتونید مجدداً برگردید و ویدیو رو تحویل بگیرید. با ترک صفحه و خارج شدن از برنامه پروژه شما در حال انجام است و از بین نخواهد رفت . گاهی اوقات ممکنه بخاطر شلوغی ساخت ویدیو شما روی دور بینهایت بره بعد از نیم ساعت اگر ویدیو ساخته نشد یک دکمه حذف میاد کنار درخواست، درخواست قبلی رو حذف کنید و در زمان های که شلوغ نیست برای ساخت بفرستید.</p>
            </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" stroke-linecap="round" stroke-linejoin="round"><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-grid">
                    <label id="image-drop-zone" for="image-input" class="drop-zone"><div class="upload-content"><div class="upload-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg></div><p>عکس (اجباری)</p></div><img id="image-preview" class="preview-img" alt="Preview"><button id="remove-image-btn" type="button" class="remove-file-btn">&times;</button></label>
                    <input type="file" id="image-input" accept="image/*" hidden>
                    <label id="video-drop-zone" for="video-input" class="drop-zone"><div class="upload-content"><div class="upload-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M8 12.5l3.5-3 5 5M2 12h3m14 0h3M12 2v3m0 14v3"/></svg></div><p>ویدیو (2 تا 30 ثانیه)</p></div><video id="video-preview" class="preview-vid" muted playsinline loop></video><button id="remove-video-btn" type="button" class="remove-file-btn">&times;</button></label>
                    <input type="file" id="video-input" accept="video/mp4, video/webm" hidden>
                </div>
            </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" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/></svg>۲. نوع حرکت را انتخاب کنید</div>
                <div class="radio-group" id="motion-group">
                    <input type="radio" id="motion-mix" name="motion" value="wan2.2-animate-mix" class="radio-input" checked><label for="motion-mix" class="radio-label">ترکیبی (Mix)</label>
                    <input type="radio" id="motion-move" name="motion" value="wan2.2-animate-move" class="radio-input"><label for="motion-move" class="radio-label">حرکت (Move)</label>
                </div>
                <div class="hint-container"><p id="motion-hint" class="motion-hint"></p></div>
                <button id="generateButton" disabled><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/></svg><span>ساخت ویدیو</span></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" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>۳. گالری نتایج</div>
                <div id="results-gallery"></div>
            </div>
        </main>
    </div>

    <!-- مدال‌ها -->
    <div id="terms-modal" class="modal-overlay">
        <div class="modal-box">
            <h2>ویدیو Animate Pro Alpha</h2>
            <p class="intro-text">این تکنولوژی پیشرفته برای تولید محتوای خلاقانه و ساخت ویدیو های مفید طراحی شده است. شما میتوانید تصویر خودتونو در موقعیت یک ویدیو و یا حالت یک ویدیو رو در موقعیت تصویر تون انتقال بدید.</p>
            <h3>قوانین استفاده</h3>
            <ol class="rules-list">
                <li>با ادامه دادن، مسئولیت کامل استفاده از این سرویس بر عهده کاربر خواهد بود و ما هیچگونه مسئولیتی از بابت محتوای تولید شده نداریم.</li>
                <li>هدف اصلی ما احترام به حقوق دیگران و اهمیت به حریم خصوصی است. به همین سبب، استفاده از تصاویر و ویدیوهایی که این شرایط را نقض کند، منجر به مسدود شدن حساب کاربری خواهد شد.</li>
                <li>این سرویس دارای بررسی‌های هوش مصنوعی است. استفاده از مواردی که باعث نقض قوانین و یا عدم احترام به حقوق دیگران باشد، منجر به مسدود شدن حساب و از بین رفتن اشتراک شما خواهد شد.</li>
                <li>هوش مصنوعی آلفا، همواره در طلیعه‌ی نوآوری و پیشرفته‌ترین دستاوردهای هوش مصنوعی گام برمی‌دارد. ما بر این باوریم که با بهره‌گیری از این فناوری‌ها، بهترین مسیرهای توسعه را خواهیم گشود.</li>
            </ol>
            <div class="modal-actions">
                <button id="accept-terms-btn">می‌پذیرم و ادامه می‌دهم</button>
                <p class="exit-notice">در صورت عدم پذیرش قوانین لطفاً از این صفحه خارج شوید.</p>
            </div>
        </div>
    </div>
    <div id="alert-modal" class="modal-overlay">
        <div class="alert-box">
            <h3>ظرفیت تکمیل است!</h3>
            <p>شما در حال حاضر ۳ درخواست در حال پردازش دارید. لطفاً تا تکمیل یکی از آن‌ها صبر کنید و سپس درخواست جدید خود را ثبت نمایید.</p>
            <button id="close-alert-btn">متوجه شدم</button>
        </div>
    </div>
    <div id="delete-confirm-modal" class="modal-overlay">
        <div class="modal-box" style="max-width: 420px;">
            <h3>تایید حذف</h3>
            <p>آیا از حذف این ویدیو مطمئن هستید؟ این عمل غیرقابل بازگشت است.</p>
            <div class="modal-actions">
                <button class="cancel-delete-btn">انصراف</button>
                <button class="confirm-delete-btn">بله، حذف کن</button>
            </div>
        </div>
    </div>
    <!-- <<< مدال جدید برای خطای مدت زمان ویدیو >>> -->
    <div id="validation-modal" class="modal-overlay">
        <div class="alert-box">
            <h3><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg> ویدیو نامعتبر</h3>
            <p>مدت زمان ویدیو باید بین ۲ تا ۳۰ ثانیه باشد. لطفاً ویدیوی دیگری انتخاب کنید.</p>
            <button id="close-validation-btn">متوجه شدم</button>
        </div>
    </div>

    <svg width="0" height="0" style="position:absolute;">
        <defs><linearGradient id="timer-gradient" x1="0%" y1="0%" x2="0%" y2="100%"><stop offset="0%" stop-color="var(--accent-secondary)" /><stop offset="100%" stop-color="var(--accent-primary)" /></linearGradient></defs>
    </svg>
    <script>
        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=25,maxDistance=120;const computedStyles=getComputedStyle(document.documentElement),particleColor=computedStyles.getPropertyValue("--accent-primary").trim(),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=.3*(Math.random()-.5),this.vy=.3*(Math.random()-.5),this.radius=1.5}update(){this.x+=this.vx,this.y+=this.vy,(this.x<0||this.x>canvas.width)&&(this.vx*=-1),(this.y<0||this.y>canvas.height)&&(this.vy*=-1)}draw(){ctx.beginPath(),ctx.arc(this.x,this.y,this.radius,0,2*Math.PI),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,distance=Math.sqrt(dx*dx+dy*dy);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=.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>
    
    <script type="module">
        const API_BASE_URL = "/api"; 
        const MAX_CONCURRENT_JOBS = 3;
        const MAX_JOBS_IN_GALLERY = 20;
        const COUNTDOWN_DURATION_MINUTES = 20;
        const STUCK_JOB_DELETE_THRESHOLD_MINUTES = 30;
        // <<< محدوده زمانی ویدیو >>>
        const MIN_VIDEO_DURATION = 2;
        const MAX_VIDEO_DURATION = 30;

        const db = {
            _db: null,
            init(dbName, version) { return new Promise((resolve, reject) => { const request = indexedDB.open(dbName, version); request.onupgradeneeded = e => { const db = e.target.result; if (!db.objectStoreNames.contains('jobs')) db.createObjectStore('jobs', { keyPath: 'id' }); }; request.onsuccess = e => { this._db = e.target.result; resolve(this); }; request.onerror = e => reject(e.target.error); }); },
            set(storeName, value) { return new Promise((resolve, reject) => { const tx = this._db.transaction(storeName, 'readwrite'); tx.oncomplete = () => resolve(); tx.onerror = e => reject(e.target.error); tx.objectStore(storeName).put(value); }); },
            get(storeName, key) { return new Promise((resolve, reject) => { const request = this._db.transaction(storeName, 'readonly').objectStore(storeName).get(key); request.onsuccess = () => resolve(request.result); request.onerror = e => reject(e.target.error); }); },
            delete(storeName, key) { return new Promise((resolve, reject) => { const tx = this._db.transaction(storeName, 'readwrite'); tx.oncomplete = () => resolve(); tx.onerror = e => reject(e.target.error); tx.objectStore(storeName).delete(key); }); },
            getAll(storeName) { return new Promise((resolve, reject) => { const request = this._db.transaction(storeName, 'readonly').objectStore(storeName).getAll(); request.onsuccess = () => resolve(request.result); request.onerror = e => reject(e.target.error); }); }
        };

        const generateBtn = document.getElementById('generateButton');
        const gallery = document.getElementById('results-gallery');
        const alertModal = document.getElementById('alert-modal');
        const closeAlertBtn = document.getElementById('close-alert-btn');
        const termsModal = document.getElementById('terms-modal');
        const acceptTermsBtn = document.getElementById('accept-terms-btn');
        const motionHint = document.getElementById('motion-hint');
        const motionRadios = document.querySelectorAll('input[name="motion"]');
        
        const deleteConfirmModal = document.getElementById('delete-confirm-modal');
        const confirmDeleteBtn = deleteConfirmModal.querySelector('.confirm-delete-btn');
        const cancelDeleteBtn = deleteConfirmModal.querySelector('.cancel-delete-btn');

        // <<< المان‌های مدال جدید >>>
        const validationModal = document.getElementById('validation-modal');
        const closeValidationBtn = document.getElementById('close-validation-btn');

        let currentImageFile = null; let currentVideoFile = null; let pollingIntervals = {}; let jobTimers = {}; let hintTimeout = null;
        const motionHints = { 'wan2.2-animate-mix': 'تصویر شما در موقعیت ویدیوی ورودی قرار خواهد گرفت.', 'wan2.2-animate-move': 'حرکات ویدیو روی تصویر شما اعمال خواهد شد.' };
        
        const showAlert = (modalElem) => modalElem.classList.add('visible');
        const hideAlert = (modalElem) => modalElem.classList.remove('visible');
        closeAlertBtn.addEventListener('click', () => hideAlert(alertModal));
        closeValidationBtn.addEventListener('click', () => hideAlert(validationModal));

        function updateGenerateButtonState() { generateBtn.disabled = !(currentImageFile && currentVideoFile); }
        
        // <<< تابع setupDropZone با منطق اعتبارسنجی >>>
        function setupDropZone(zoneId, inputId, previewId, fileType, onFileSet) {
            const dropZone = document.getElementById(zoneId);
            const fileInput = document.getElementById(inputId);
            const preview = document.getElementById(previewId);
            const removeBtn = document.getElementById(`remove-${fileType}-btn`);

            const reset = () => {
                fileInput.value = '';
                dropZone.classList.remove('has-file');
                if (preview.src) { URL.revokeObjectURL(preview.src); }
                preview.src = '';
                preview.style.display = 'none';
                onFileSet(null);
            };

            const handleFile = (file) => {
                if (!file) return;

                const objectURL = URL.createObjectURL(file);

                if (fileType === 'video') {
                    const videoElement = document.createElement('video');
                    videoElement.preload = 'metadata';
                    videoElement.src = objectURL;
                    
                    videoElement.onloadedmetadata = () => {
                        const duration = videoElement.duration;
                        if (duration >= MIN_VIDEO_DURATION && duration <= MAX_VIDEO_DURATION) {
                            dropZone.classList.add('has-file');
                            preview.src = objectURL;
                            preview.style.display = 'block';
                            onFileSet(file);
                        } else {
                            showAlert(validationModal);
                            reset();
                        }
                    };
                    videoElement.onerror = () => {
                        alert("خطا در خواندن فایل ویدیو. لطفاً فایل دیگری را امتحان کنید.");
                        reset();
                    };
                } else { // برای عکس
                    dropZone.classList.add('has-file');
                    preview.src = objectURL;
                    preview.style.display = 'block';
                    onFileSet(file);
                }
            };

            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eName => dropZone.addEventListener(eName, e => {e.preventDefault(); e.stopPropagation();}));
            ['dragenter', 'dragover'].forEach(eName => dropZone.addEventListener(eName, () => dropZone.classList.add('drag-over')));
            ['dragleave', 'drop'].forEach(eName => dropZone.addEventListener(eName, () => dropZone.classList.remove('drag-over')));
            dropZone.addEventListener('drop', e => { if (e.dataTransfer.files.length > 0) handleFile(e.dataTransfer.files[0]); });
            fileInput.addEventListener('change', e => { if (e.target.files.length > 0) handleFile(e.target.files[0]); });
            removeBtn.addEventListener('click', e => { e.stopPropagation(); reset(); });
            
            return reset;
        }

        const resetImage = setupDropZone('image-drop-zone', 'image-input', 'image-preview', 'image', file => { currentImageFile = file; updateGenerateButtonState(); });
        const resetVideo = setupDropZone('video-drop-zone', 'video-input', 'video-preview', 'video', file => { currentVideoFile = file; updateGenerateButtonState(); });
        
        motionRadios.forEach(radio => { radio.addEventListener('change', (e) => { const hintText = motionHints[e.target.value]; if (hintText) { motionHint.textContent = hintText; motionHint.classList.remove('visible'); clearTimeout(hintTimeout); setTimeout(() => { motionHint.classList.add('visible'); hintTimeout = setTimeout(() => { motionHint.classList.remove('visible'); }, 4000); }, 50); } }); });

        function createJobCard(job) {
            let card = document.getElementById(`job-${job.id}`);
            if (!card) { card = document.createElement('div'); card.id = `job-${job.id}`; card.className = 'job-card'; gallery.prepend(card); }
            if (jobTimers[job.id]) { clearInterval(jobTimers[job.id]); delete jobTimers[job.id]; }
            
            if (job.status === 'completed') {
                card.classList.remove('in-progress', 'error');
                card.classList.add('completed');
                card.innerHTML = `<div class="job-header"><span class="job-id">${job.id.substring(0, 8)}</span><span class="job-status" style="color: var(--success-color);">✅ انجام شد</span></div><video src="${job.result}" controls loop autoplay muted></video><div class="video-controls"><button class="video-button download-via-post-btn" data-video-url="${job.result}">دانلود ویدیو</button><button class="delete-job-btn video-button" data-job-id="${job.id}" title="حذف"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 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></button></div>`;
            } else if (job.status === 'error') {
                card.classList.remove('in-progress', 'completed');
                card.classList.add('error');
                card.innerHTML = `<div class="job-header"><span class="job-id">${job.id.substring(0, 8)}</span><span class="job-status" style="color: var(--danger-color);">❌ خطا</span></div><div class="job-body">${job.result || 'خطای نامشخص'}</div><div class="video-controls"><button class="delete-job-btn video-button" data-job-id="${job.id}" title="حذف خطا"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 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> <span>حذف</span></button></div>`;
            } else {
                card.classList.remove('completed', 'error');
                card.classList.add('in-progress');
                card.innerHTML = `<div class="job-header"><span class="job-id">${job.id.substring(0, 8)}</span><span class="job-status">${job.status || 'در حال ارسال...'}</span></div><div class="reassurance-message"><strong>خیالتان راحت!</strong><p>پردازش ویدیوی شما شروع شده. می‌توانید این صفحه را ببندید و بعداً سر بزنید.</p></div><div class="job-body"><div class="timer-container"><svg class="timer-svg" viewBox="0 0 100 100"><circle class="timer-circle-bg" cx="50" cy="50" r="45"></circle><circle class="timer-circle-progress" cx="50" cy="50" r="45"></circle></svg><div class="timer-text">--:--</div></div><div class="in-progress-controls"><button class="quick-check-btn"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12 A8 8 0 0 1 12 20 A8 8 0 0 1 4 12 A8 8 0 0 1 20 12 z"/><path d="M12 8v4l2 2"/></svg><span>پیگیری سریع</span></button><button class="delete-job-btn video-button hidden" data-job-id="${job.id}" title="حذف"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg></button></div><div class="quick-check-feedback"></div></div>`;
                
                const timerText = card.querySelector('.timer-text');
                const progressCircle = card.querySelector('.timer-circle-progress');
                const statusElem = card.querySelector('.job-status');
                const deleteBtn = card.querySelector('.delete-job-btn');
                const radius = progressCircle.r.baseVal.value;
                const circumference = 2 * Math.PI * radius;
                progressCircle.style.strokeDasharray = circumference;
                const countdownTotalSeconds = COUNTDOWN_DURATION_MINUTES * 60;

                const updateTimer = () => {
                    const elapsedSeconds = Math.floor((Date.now() - job.timestamp) / 1000);
                    const elapsedMinutes = elapsedSeconds / 60;
                    
                    let remainingSeconds = countdownTotalSeconds - elapsedSeconds;
                    if (remainingSeconds <= 0) {
                        remainingSeconds = 0;
                        if (statusElem && !['completed', 'error'].includes(job.status)) statusElem.textContent = 'در حال نهایی سازی...';
                    }
                    const minutes = String(Math.floor(remainingSeconds / 60)).padStart(2, '0');
                    const seconds = String(remainingSeconds % 60).padStart(2, '0');
                    timerText.textContent = `${minutes}:${seconds}`;
                    const progress = remainingSeconds / countdownTotalSeconds;
                    const offset = circumference * (1 - progress);
                    progressCircle.style.strokeDashoffset = offset;

                    if (deleteBtn && elapsedMinutes >= STUCK_JOB_DELETE_THRESHOLD_MINUTES) {
                        deleteBtn.classList.remove('hidden');
                        if (jobTimers[job.id]) { clearInterval(jobTimers[job.id]); }
                    }
                };
                updateTimer();
                jobTimers[job.id] = setInterval(updateTimer, 1000);
                
                const quickCheckBtn = card.querySelector('.quick-check-btn');
                if (quickCheckBtn) {
                    quickCheckBtn.addEventListener('click', () => {
                        const feedbackElem = card.querySelector('.quick-check-feedback');
                        if(feedbackElem) { feedbackElem.textContent = 'در حال بررسی وضعیت...'; feedbackElem.classList.add('visible'); setTimeout(() => { feedbackElem.classList.remove('visible'); }, 3000); }
                        checkJobStatus(job.id, true);
                    });
                }
            }
        }

        async function manageGalleryLimit() {
            const allJobs = await db.getAll('jobs');
            if (allJobs.length > MAX_JOBS_IN_GALLERY) {
                const jobToRemove = allJobs.sort((a, b) => a.timestamp - b.timestamp).find(j => j.status === 'completed' || j.status === 'error');
                if (jobToRemove) {
                    await db.delete('jobs', jobToRemove.id);
                    const cardToRemove = document.getElementById(`job-${jobToRemove.id}`);
                    if (cardToRemove) cardToRemove.remove();
                }
            }
        }
        
        async function checkJobStatus(jobId, isManualCheck = false) {
            const btn = document.querySelector(`#job-${jobId} .quick-check-btn`);
            if (isManualCheck && btn) { btn.disabled = true; btn.querySelector('span').textContent = 'در حال بررسی...'; }
            try {
                const response = await fetch(`${API_BASE_URL}/check_status`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId }) });
                if (!response.ok) throw new Error('خطا در بررسی وضعیت');
                const data = await response.json(); const job = await db.get('jobs', jobId);
                if (job && (job.status !== data.status || job.result !== data.result)) { job.status = data.status; job.result = data.result; await db.set('jobs', job); createJobCard(job); }
                if (data.status === 'completed' || data.status === 'error') { if (pollingIntervals[jobId]) { clearInterval(pollingIntervals[jobId]); delete pollingIntervals[jobId]; } } 
                else if (isManualCheck) { const feedbackElem = document.querySelector(`#job-${jobId} .quick-check-feedback`); if(feedbackElem) feedbackElem.textContent = 'هنوز در حال پردازش است.'; }
            } catch (e) { console.error("خطا:", e); } 
            finally { if (isManualCheck && btn) { setTimeout(() => { if(btn) { btn.disabled = false; btn.querySelector('span').textContent = 'پیگیری سریع'; } }, 2000); } }
        }

        async function main() {
            const jobDB = await db.init('AnimationJobsDB_v15_Validation', 1);

            if (localStorage.getItem('termsAccepted_v1') !== 'true') {
                showAlert(termsModal);
            }
            acceptTermsBtn.addEventListener('click', () => {
                localStorage.setItem('termsAccepted_v1', 'true');
                hideAlert(termsModal);
            });

            const allJobs = await jobDB.getAll('jobs');
            allJobs.sort((a, b) => a.timestamp - b.timestamp).forEach(job => {
                createJobCard(job);
                if (job.status !== 'completed' && job.status !== 'error') {
                    checkJobStatus(job.id);
                    pollingIntervals[job.id] = setInterval(() => checkJobStatus(job.id), 15000);
                }
            });

            generateBtn.addEventListener('click', async () => {
                if (!currentImageFile || !currentVideoFile) return;
                const currentJobs = await jobDB.getAll('jobs'); const activeJobs = currentJobs.filter(j => j.status !== 'completed' && j.status !== 'error');
                if (activeJobs.length >= MAX_CONCURRENT_JOBS) { showAlert(alertModal); return; }
                generateBtn.disabled = true; generateBtn.querySelector('span').textContent = 'در حال ارسال...';
                try {
                    await manageGalleryLimit();
                    const formData = new FormData();
                    formData.append('image_file', currentImageFile); formData.append('video_file', currentVideoFile); formData.append('motion', document.querySelector('input[name="motion"]:checked').value); formData.append('style', 'wan-pro');
                    const response = await fetch(`${API_BASE_URL}/submit_job`, { method: 'POST', body: formData });
                    if (!response.ok) { const errData = await response.json(); throw new Error(errData.error || 'خطای ناشناخته از سرور'); }
                    const data = await response.json(); const newJob = { id: data.job_id, status: 'ارسال شد، در صف پردازش...', timestamp: Date.now() };
                    await jobDB.set('jobs', newJob); createJobCard(newJob);
                    pollingIntervals[newJob.id] = setInterval(() => checkJobStatus(newJob.id), 15000);
                    resetImage(); resetVideo();
                } catch (e) {
                    const alertBox = document.querySelector('#alert-modal .alert-box');
                    if (alertBox) {
                        if (e.message.includes('<strong>')) {
                            alertBox.querySelector('h3').textContent = 'خطا در ارسال';
                            alertBox.querySelector('p').innerHTML = e.message;
                        } else {
                            alertBox.querySelector('h3').textContent = 'یک خطا رخ داد';
                            alertBox.querySelector('p').textContent = e.message;
                        }
                        showAlert(alertModal);
                    } else {
                        alert('خطا: ' + e.message.replace(/<br>/g, '\n').replace(/<[^>]*>?/gm, ''));
                    }
                } 
                finally { generateBtn.querySelector('span').textContent = 'ساخت ویدیو'; updateGenerateButtonState(); }
            });
            
            gallery.addEventListener('click', e => {
                const button = e.target.closest('.delete-job-btn, .download-via-post-btn');
                if (!button) return;

                if (button.classList.contains('delete-job-btn')) {
                    const jobId = button.dataset.jobId;
                    deleteConfirmModal.dataset.jobIdToDelete = jobId;
                    showAlert(deleteConfirmModal);
                }
                else if (button.classList.contains('download-via-post-btn')) {
                    const relativeVideoUrl = button.dataset.videoUrl;
                    if (relativeVideoUrl) {
                        const absoluteVideoUrl = new URL(relativeVideoUrl, window.location.href).href;
                        if (window.parent !== window) {
                            window.parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: absoluteVideoUrl }, '*'); 
                        } else {
                            console.warn('این صفحه در iframe نیست. لینک به صورت مستقیم باز می‌شود.');
                            window.open(absoluteVideoUrl, '_blank');
                        }
                    }
                }
            });

            confirmDeleteBtn.addEventListener('click', async () => {
                const jobId = deleteConfirmModal.dataset.jobIdToDelete;
                if (!jobId) return;

                const cardToDelete = document.getElementById(`job-${jobId}`);
                if (cardToDelete) {
                    cardToDelete.classList.add('deleting');
                    setTimeout(async () => {
                        await db.delete('jobs', jobId);
                        cardToDelete.remove();
                        hideAlert(deleteConfirmModal);
                        delete deleteConfirmModal.dataset.jobIdToDelete;
                    }, 500);
                }
            });

            cancelDeleteBtn.addEventListener('click', () => hideAlert(deleteConfirmModal));
            deleteConfirmModal.addEventListener('click', e => {
                if (e.target === deleteConfirmModal) hideAlert(deleteConfirmModal);
            });

            updateGenerateButtonState();
        }
        main().catch(console.error);
    </script>
</body>
</html>