File size: 34,602 Bytes
6fbf602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!-- =========================================================================
     لودر Iframe — ویرایشگر ویدیو آلفا  —  نسخه‌ی ۲۰۲۶/۱۰/۲۰
     -------------------------------------------------------------------------
     تغییرات نسخه‌ی ۲۰۲۶/۱۰/۲۰:
       • دکمه‌ی برگشت گوشی مثل کروم کار می‌کند: داخل ویرایشگر، برگشت اول پنجره‌ی باز را
         می‌بندد، بعد از ویرایشگر به صفحه‌ی اول برنامه («پروژه‌ی جدید») می‌رود و فقط از
         صفحه‌ی اول، برنامه بسته می‌شود. (برنامه و لودر با پیام‌های AE_NAV / AE_BACK
         هماهنگ می‌شوند؛ اگر برنامه‌ی اندروید دکمه‌ی برگشت را به تاریخچه‌ی وب‌ویو بدهد،
         که در بیشتر برنامه‌ها همین است، این روش کار می‌کند.)
       • اجازه‌ی میکروفون به آی‌فریم داده شد (اگر خود برنامه‌ی اندروید هم اجازه داشته باشد،
         ضبط صدا داخل ویرایشگر کار می‌کند؛ اگر نه، ویرایشگر انتخاب فایل صدا را پیشنهاد می‌دهد).

     تغییرات نسخه‌ی ۲۰۲۶/۱۰/۱۳:
       ۱) دانلود: دیگر لودر ویدیو را دانلود و دوباره آپلود نمی‌کند. خودِ سرور
          لینکِ aisada را می‌سازد و فقط «لینکِ آماده» با پیامِ OPEN_EXTERNAL_URL
          به این لودر می‌رسد؛ لودر فقط همان را در مرورگرِ گوشی باز می‌کند.
          (پیام‌های قدیمیِ DOWNLOAD_REQUEST فقط به‌عنوان پشتیبان مانده‌اند و
           برنامه فقط وقتی می‌فرستدشان که سرور نتوانسته باشد لینک بسازد.)
       ۲) روانی روی گوشی‌های ضعیف:
          • بعد از باز شدنِ برنامه، صفحه‌ی بیرونی کاملاً قفل می‌شود (اسکرول و
            کشیدنِ لبه‌ها فقط داخلِ برنامه است) → دیگر پرش و نیمه‌کاره کشیده شدنِ
            استایل‌ها وسطِ بالا/پایین کردن پیش نمی‌آید.
          • انیمیشنِ شبکه‌ی عصبیِ لودینگ بعد از باز شدن کاملاً از حافظه حذف
            می‌شود تا کلِ حافظه‌ی گرافیکی برای برنامه بماند.
          • آی‌فریم بعد از نمایش، لایه‌ی اضافه‌ی GPU نگه نمی‌دارد.
       ۳) باز کردنِ لینک: دیگر یک لینک دو بار باز نمی‌شود.
     ========================================================================= -->
<style>
    /* تعریف متغیرهای رنگی */
    #tts-app-container {
      --color-primary: #4CAF50;
      --color-secondary: rgb(84, 110, 122);
      --color-danger: #f44336;
      --color-white: #ffffff;
      --color-black: #000000;
      --color-gray: #f0f0f0;
      --color-light-gray: #ddd;
    }

    #tts-app-container {
      position: relative; margin: 0; padding: 0; font-family: Arial, sans-serif;
      text-align: center; direction: rtl;
      background-color: var(--color-white); overflow: hidden;
      height: 100vh;
      height: 100dvh;
    }

    /* در تمام مدت (هم لودینگ و هم بعد از باز شدن) صفحه‌ی بیرونی تکان نمی‌خورد */
    html.tts-app-lock, html.tts-app-lock body {
      overflow: hidden !important;
      overscroll-behavior: none;
      height: 100%;
      margin: 0;
    }

    /* استایل کانتینر اصلی */
    #tts-app-container .iframe-container {
      position: fixed; top: 0; left: 0; width: 100%;
      height: 100%; height: calc(var(--vh, 1vh) * 100); height: 100dvh;
      overflow: hidden; z-index: 9998;
      background-color: #121212;
      padding-bottom: env(safe-area-inset-bottom);
      box-sizing: border-box;
    }

    /* استایل آی‌فریم */
    #tts-app-container .iframe-container iframe {
      position: absolute; top: 0; left: 0; width: 100%; height: 100%;
      border: none; display: block; opacity: 0;
      background: #121212;
      transition: opacity 0.6s ease-in;
    }
    #tts-app-container .iframe-container iframe.visible { opacity: 1; }
    /* بعد از تمام شدنِ محو شدن، هیچ ترنزیشن/لایه‌ی اضافه‌ای روی آی‌فریم نمی‌ماند */
    #tts-app-container .iframe-container iframe.settled { opacity: 1; transition: none; }

    /* استایل بخش لودینگ و شبکه عصبی */
    #tts-app-container .loading {
      position: absolute; top: 0; left: 0; width: 100%; height: 100%;
      display: flex; flex-direction: column; align-items: center; justify-content: center;
      background: var(--color-white); z-index: 10002;
      opacity: 1; transition: opacity 0.8s ease-out;
    }
    #tts-app-container .loading.hidden { opacity: 0; pointer-events: none; }

    /* کانواس شبکه عصبی */
    #loading-canvas {
      position: absolute; top: 0; left: 0; width: 100%; height: 100%;
      z-index: 1; /* زیر محتوای متنی */
    }

    #tts-app-container .loading-content {
      z-index: 2; /* روی شبکه عصبی */
      display: flex; flex-direction: column; align-items: center;
      gap: 20px; width: 80%; max-width: 400px;
    }

    #tts-app-container .loading-text { font-size: 18px; font-weight: 500; color: #37474F; letter-spacing: 0.5px; min-height: 22px; }
    #tts-app-container .loading-text::after { content: '_'; display: inline-block; margin-right: 5px; font-weight: 300; animation: tts-blink-cursor 0.9s infinite; color: #90A4AE; }
    #tts-app-container .loading-text.finished::after { display: none; }
    @keyframes tts-blink-cursor { 50% { opacity: 0; } }

    #tts-app-container .progress-bar-container { width: 100%; height: 4px; background-color: rgba(176, 190, 197, 0.2); border-radius: 4px; overflow: hidden; position: relative; }
    #tts-app-container .progress-bar-fill { width: 0%; height: 100%; border-radius: 4px; transition: width 0.1s linear; background: linear-gradient(90deg, #B0BEC5, #78909C); }

    #tts-app-container .error-message { display: none; color: var(--color-danger); margin-top: 20px; font-size: 16px; text-align: center; }
    #tts-app-container #retryButton { display: none; margin-top: 20px; padding: 10px 25px; font-size: 14px; font-weight: 600; color: #fff; background: linear-gradient(135deg, #78909C, #546E7A); border: none; border-radius: 8px; cursor: pointer; box-shadow: 0 2px 5px rgba(0,0,0,0.15); transition: all 0.2s ease; }

    /* استایل نوتیفیکیشن و دانلود */
    .tts-notification { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #ffffff; padding: 20px 30px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15); z-index: 10003; display: none; text-align: center; width: 90%; max-width: 400px; max-height: 80vh; overflow-y: auto; border-top: 4px solid var(--color-primary, #4CAF50); direction: rtl; box-sizing: border-box; }
    .tts-notification-buttons { display: flex; justify-content: center; margin-top: 20px; flex-wrap: wrap; gap: 10px; }
    .tts-notification-buttons button { background-color: var(--color-primary, #4CAF50); color: #ffffff; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer; transition: background-color 0.2s; }

    #download-loading-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 10004; display: none; justify-content: center; align-items: center; color: white; font-size: 1.2rem; flex-direction: column; gap: 15px; }
    .lds-dual-ring { display: inline-block; width: 60px; height: 60px; }
    .lds-dual-ring:after { content: " "; display: block; width: 46px; height: 46px; margin: 8px; border-radius: 50%; border: 5px solid #fff; border-color: #fff transparent #fff transparent; animation: lds-dual-ring 1.2s linear infinite; }
    @keyframes lds-dual-ring { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

    /* ---------- کارت پشتیبانِ باز کردن لینک در مرورگر ---------- */
    #pay-fallback {
      position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 10010; display: none;
      align-items: center; justify-content: center; padding: 18px;
      background: rgba(15, 20, 30, 0.62); direction: rtl;
      font-family: Tahoma, Arial, sans-serif; box-sizing: border-box;
    }
    #pay-fallback .pf-card {
      background: #fff; border-radius: 18px; padding: 22px 20px;
      width: 100%; max-width: 400px; text-align: center; box-sizing: border-box;
      box-shadow: 0 22px 55px -18px rgba(0,0,0,0.5);
    }
    #pay-fallback h4 { margin: 0 0 8px; font-size: 16px; color: #1A202C; }
    #pay-fallback p { margin: 0 0 14px; font-size: 13px; line-height: 2; color: #626F86; }
    #pay-fallback .pf-url {
      font-family: monospace; font-size: 11px; direction: ltr; text-align: left;
      background: #F4F6FA; border: 1px solid #E1E7EF; border-radius: 10px;
      padding: 10px; word-break: break-all; color: #4A5568;
      max-height: 90px; overflow: auto; margin-bottom: 14px;
    }
    #pay-fallback .pf-btns { display: flex; gap: 8px; }
    #pay-fallback button {
      flex: 1; border: none; border-radius: 11px; padding: 12px 8px; margin: 0 4px;
      font-family: inherit; font-size: 13px; font-weight: bold; cursor: pointer;
    }
    #pay-fallback .pf-primary { background: #4A6CFA; color: #fff; }
    #pay-fallback .pf-ghost { background: #EEF1F6; color: #4A5568; }
</style>
<div id="tts-app-container">
<div class="iframe-container">
<div class="loading" id="loadingContainer"><canvas id="loading-canvas"></canvas>
<div class="loading-content">
<div class="loading-text" id="typingText"></div>
<div class="progress-bar-container">
<div class="progress-bar-fill" id="progressBar"></div>
</div>
<div class="error-message" id="errorMessage"></div>
<button id="retryButton">بارگذاری مجدد</button></div>
</div>
<!-- ⚠️ allow-popups و allow-popups-to-escape-sandbox برای باز شدنِ لینکِ دانلود در مرورگر ضروری هستند. --> <iframe id="myIframe" title="استودیو ویرایش ویدیو آلفا" sandbox="allow-scripts allow-same-origin allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-downloads" allow="microphone; clipboard-read; clipboard-write; fullscreen; autoplay; encrypted-media; picture-in-picture" allowfullscreen="allowfullscreen"></iframe></div>
</div>
<div id="download-loading-overlay">
<div class="lds-dual-ring"></div>
<span id="download-status-text">در حال آماده&zwnj;سازی لینک دانلود...</span></div>
<div id="pay-fallback">
<div class="pf-card">
<h4>باز کردن در مرورگر</h4>
<p>اگر لینک به&zwnj;صورت خودکار باز نشد، آن را در مرورگر گوشی (کروم) باز کنید.</p>
<div class="pf-url" id="pf-url"></div>
<div class="pf-btns"><button type="button" class="pf-ghost" id="pf-close">بستن</button> <button type="button" class="pf-ghost" id="pf-copy">کپی لینک</button> <button type="button" class="pf-primary" id="pf-open">باز کردن</button></div>
</div>
</div>
<p>
<script>
(function() {
    // --- تنظیمات اصلی ---
    var siteURL = 'https://videoeditor.appalpha.ir';
    var siteOrigin = new URL(siteURL).origin;
    // فقط برای روشِ پشتیبانِ قدیمی (وقتی سرور نتوانسته لینک بسازد)
    var uploadURL = 'https://www.aisada.ir/hamed/upload.php';
    var iframe = document.getElementById('myIframe');
    var loadingMessage = "استودیو ویرایش ویدیو آلفا";

    // --- متغیرهای انیمیشن و UI ---
    var progressBar = document.getElementById('progressBar');
    var retryButton = document.getElementById('retryButton');
    var errorMessage = document.getElementById('errorMessage');
    var loadingContainer = document.getElementById('loadingContainer');
    var typingTextElement = document.getElementById('typingText');
    var canvas = document.getElementById('loading-canvas');
    var ctx = canvas ? canvas.getContext('2d') : null;

    var animationFrameId = 0, isIframeLoaded = false, isTypingComplete = false, isTransitionStarted = false;
    var charIndex = 0, typingTimeout = 0, loadingTimeout = 0, appShown = false;
    var particlesArray = [];

    // صفحه‌ی بیرونی تا وقتی برنامه روی صفحه است قفل می‌ماند (اسکرول و کشیدنِ
    // لبه‌ها فقط داخلِ برنامه). اگر اپ به صفحه‌ی دیگری برود و این لودر حذف یا
    // پنهان شود، قفل خودکار برداشته می‌شود تا صفحه‌های دیگرِ اپ گیر نکنند.
    var appContainer = document.getElementById('tts-app-container');
    function syncScrollLock() {
        var on = !!(appContainer && document.documentElement.contains(appContainer) && appContainer.offsetParent !== null);
        document.documentElement.classList.toggle('tts-app-lock', on);
        return on;
    }
    syncScrollLock();
    var lockTimer = setInterval(function () {
        if (!document.documentElement.contains(appContainer)) {
            document.documentElement.classList.remove('tts-app-lock');
            clearInterval(lockTimer);
            return;
        }
        syncScrollLock();
    }, 700);
    window.addEventListener('hashchange', function () { setTimeout(syncScrollLock, 60); setTimeout(syncScrollLock, 700); });
    window.addEventListener('popstate', function () { setTimeout(syncScrollLock, 60); setTimeout(syncScrollLock, 700); });

    // --- تنظیم ارتفاع برای موبایل ---
    function setVhVariable() {
        var vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', vh + 'px');
    }

    // --- انیمیشن شبکه عصبی (Neural Network) ---
    function resizeCanvas() {
        if (canvas && canvas.parentElement) {
            canvas.width = canvas.parentElement.clientWidth;
            canvas.height = canvas.parentElement.clientHeight;
        }
    }

    function Particle(x, y, s, c, sx, sy) {
        this.x = x; this.y = y; this.size = s; this.color = c; this.speedX = sx; this.speedY = sy;
    }
    Particle.prototype.update = function () {
        if (this.x > canvas.width || this.x < 0) this.speedX = -this.speedX;
        if (this.y > canvas.height || this.y < 0) this.speedY = -this.speedY;
        this.x += this.speedX; this.y += this.speedY;
    };
    Particle.prototype.draw = function () {
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
    };

    function initParticles() {
        if (!canvas) return;
        particlesArray = [];
        var n = Math.min(90, (canvas.width * canvas.height) / 9000);
        for (var i = 0; i < n; i++) {
            var s = Math.random() * 1.8 + 0.8;
            var x = Math.random() * canvas.width;
            var y = Math.random() * canvas.height;
            var sx = (Math.random() * 0.3) - 0.15;
            var sy = (Math.random() * 0.3) - 0.15;
            particlesArray.push(new Particle(x, y, s, 'rgba(144, 164, 174, 0.6)', sx, sy));
        }
    }

    function handleConnections() {
        for (var a = 0; a < particlesArray.length; a++) {
            for (var b = a; b < particlesArray.length; b++) {
                var dx = particlesArray[a].x - particlesArray[b].x;
                var dy = particlesArray[a].y - particlesArray[b].y;
                var d2 = dx * dx + dy * dy;
                if (d2 < 14400) {
                    var opacityValue = 1 - (Math.sqrt(d2) / 120);
                    ctx.strokeStyle = 'rgba(176, 190, 197, ' + opacityValue + ')';
                    ctx.lineWidth = 0.8;
                    ctx.beginPath();
                    ctx.moveTo(particlesArray[a].x, particlesArray[a].y);
                    ctx.lineTo(particlesArray[b].x, particlesArray[b].y);
                    ctx.stroke();
                }
            }
        }
    }

    function animate() {
        if (!ctx || !canvas || appShown) return;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < particlesArray.length; i++) { particlesArray[i].update(); particlesArray[i].draw(); }
        handleConnections();
        animationFrameId = requestAnimationFrame(animate);
    }

    function typewriterEffect() {
        if (charIndex < loadingMessage.length) {
            typingTextElement.textContent += loadingMessage.charAt(charIndex);
            charIndex++;
            progressBar.style.width = ((charIndex / loadingMessage.length) * 100) + '%';
            typingTimeout = setTimeout(typewriterEffect, 80);
        } else {
            typingTextElement.classList.add('finished');
            isTypingComplete = true;
            triggerTransition();
        }
    }

    function startLoadingAnimation() {
        if (animationFrameId) cancelAnimationFrame(animationFrameId);
        if (typingTimeout) clearTimeout(typingTimeout);

        loadingContainer.style.display = 'flex';
        loadingContainer.classList.remove('hidden');

        charIndex = 0;
        isIframeLoaded = false;
        isTypingComplete = false;
        isTransitionStarted = false;

        typingTextElement.textContent = '';
        typingTextElement.classList.remove('finished');
        typingTextElement.style.display = 'block';

        progressBar.style.width = '0%';
        retryButton.style.display = 'none';
        errorMessage.style.display = 'none';

        resizeCanvas();
        initParticles();
        animate();
        typewriterEffect();
    }

    function stopLoadingAnimation() {
        if (animationFrameId) cancelAnimationFrame(animationFrameId);
        animationFrameId = 0;
        if (typingTimeout) clearTimeout(typingTimeout);
    }

    /* بعد از باز شدنِ برنامه، لودینگ و کانواسش کاملاً از حافظه بیرون می‌روند */
    function releaseLoader() {
        stopLoadingAnimation();
        particlesArray = [];
        if (canvas) { canvas.width = 0; canvas.height = 0; }
        loadingContainer.style.display = 'none';
    }

    function triggerTransition() {
        if (isIframeLoaded && isTypingComplete && !isTransitionStarted) {
            isTransitionStarted = true;
            progressBar.style.width = '100%';
            setTimeout(function () {
                appShown = true;
                loadingContainer.classList.add('hidden');
                iframe.classList.add('visible');
                setTimeout(function () {
                    releaseLoader();
                    iframe.classList.add('settled');
                    iframe.classList.remove('visible');
                }, 850);
            }, 300);
        }
    }

    // --- مدیریت Iframe و خطاها ---
    function iframeLoaded() {
        // رویدادِ load برای about:blank (پیش از تنظیم src) نادیده گرفته می‌شود
        if (!iframe.getAttribute('src')) return;
        if (loadingTimeout) clearTimeout(loadingTimeout);
        isIframeLoaded = true;
        triggerTransition();
    }

    function iframeError() {
        if (loadingTimeout) clearTimeout(loadingTimeout);
        stopLoadingAnimation();
        typingTextElement.style.display = 'none';
        errorMessage.style.display = 'block';
        errorMessage.innerHTML = 'بارگیری با مشکل مواجه شد.<br />اتصال اینترنت خود را بررسی و دوباره تلاش کنید.';
        retryButton.style.display = 'block';
        progressBar.style.width = '0%';
    }

    function loadIframe() {
        appShown = false;
        iframe.classList.remove('visible', 'settled');
        startLoadingAnimation();
        if (loadingTimeout) clearTimeout(loadingTimeout);
        loadingTimeout = setTimeout(iframeError, 45000);
        iframe.onload = iframeLoaded;
        iframe.onerror = iframeError;
        iframe.setAttribute('src', siteURL);
    }

    retryButton.addEventListener('click', function () {
        // بارگذاریِ کاملاً تازه (حتی اگر بعداً جواب قبلی برسد)
        iframe.removeAttribute('src');
        setTimeout(loadIframe, 30);
    });

    // ================================================================
    // --- باز کردن لینک در مرورگر گوشی (نه داخل برنامه) ---
    // ================================================================
    var payFallback = document.getElementById('pay-fallback');
    var pfUrl = document.getElementById('pf-url');
    var pfCopy = document.getElementById('pf-copy');
    var lastPayUrl = '';
    var lastOpenAt = 0, lastOpenUrl = '';

    function isSafeUrl(url) {
        return typeof url === 'string' && /^https?:\/\//i.test(url) && url.length < 4000;
    }

    function openInExternalBrowser(url) {
        if (!isSafeUrl(url)) return;
        // یک لینک در کمتر از ۲ ثانیه دو بار باز نمی‌شود
        var now = Date.now();
        if (url === lastOpenUrl && now - lastOpenAt < 2000) return;
        lastOpenUrl = url; lastOpenAt = now;
        lastPayUrl = url;

        // نکته: با «noopener» در window.open همیشه null برمی‌گردد و قبلاً باعث
        // می‌شد روشِ دوم هم اجرا شود و لینک دو بار باز شود.
        var opened = null;
        try {
            opened = window.open(url, '_blank');
            if (opened) { try { opened.opener = null; } catch (e) {} }
        } catch (e) { opened = null; }

        if (!opened) {
            try {
                var a = document.createElement('a');
                a.href = url;
                a.target = '_blank';
                a.rel = 'noopener noreferrer';
                a.style.display = 'none';
                document.body.appendChild(a);
                a.click();
                setTimeout(function () { try { a.parentNode.removeChild(a); } catch (e) {} }, 800);
            } catch (e) {}
        }

        // اگر بعد از کمی مکث کاربر از برنامه خارج نشده بود، کارت پشتیبان نشان داده می‌شود
        setTimeout(function () {
            if (document.hidden) return;
            pfUrl.textContent = url;
            pfCopy.textContent = 'کپی لینک';
            payFallback.style.display = 'flex';
        }, 1500);
    }

    document.getElementById('pf-close').onclick = function () {
        payFallback.style.display = 'none';
    };

    pfCopy.onclick = function () {
        var text = lastPayUrl;
        var done = function () { pfCopy.textContent = 'کپی شد ✓'; };
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(done).catch(function () { legacyCopy(text, done); });
        } else {
            legacyCopy(text, done);
        }
    };

    document.getElementById('pf-open').onclick = function () {
        if (!lastPayUrl) return;
        var win = null;
        try { win = window.open(lastPayUrl, '_blank'); } catch (e) {}
        if (!win) {
            try {
                var clean = lastPayUrl.replace(/^https?:\/\//, '');
                window.location.href = 'intent://' + clean +
                    '#Intent;scheme=https;action=android.intent.action.VIEW;end';
            } catch (e) {}
        }
        payFallback.style.display = 'none';
    };

    function legacyCopy(text, done) {
        try {
            var ta = document.createElement('textarea');
            ta.value = text;
            ta.style.position = 'fixed';
            ta.style.opacity = '0';
            document.body.appendChild(ta);
            ta.select();
            document.execCommand('copy');
            ta.parentNode.removeChild(ta);
            done();
        } catch (e) {}
    }

    // --- پیام‌ها ---
    var downloadOverlay = document.getElementById('download-loading-overlay');
    var downloadStatusText = document.getElementById('download-status-text');

    function createNotification(messageText) {
        var existing = document.querySelectorAll('.tts-notification');
        for (var i = 0; i < existing.length; i++) existing[i].parentNode.removeChild(existing[i]);
        var notificationDiv = document.createElement('div');
        notificationDiv.className = 'tts-notification';
        notificationDiv.innerHTML = '<p>' + messageText + '</p><div class="tts-notification-buttons"><button>باشه</button></div>';
        document.body.appendChild(notificationDiv);
        notificationDiv.style.display = 'block';
        notificationDiv.querySelector('button').onclick = function () { notificationDiv.parentNode.removeChild(notificationDiv); };
    }

    // ================================================================
    // --- روشِ پشتیبانِ قدیمی (فقط اگر سرور نتوانسته باشد لینک بسازد) ---
    // در حالت عادی برنامه این پیام‌ها را نمی‌فرستد؛ لینک را سرور می‌سازد.
    // ================================================================
    function uploadBlobInChunks(blob, onProgress) {
        var CHUNK_SIZE = 4 * 1024 * 1024;
        var totalChunks = Math.ceil(blob.size / CHUNK_SIZE);
        var originalFileName = 'alpha-video-' + Date.now() + '.mp4';
        var fileIdentifier = 'sub-' + originalFileName + '-' + blob.size;
        var chunkNumber = 0;

        function next() {
            if (chunkNumber >= totalChunks) return Promise.reject(new Error('لینک نهایی دریافت نشد.'));
            var start = chunkNumber * CHUNK_SIZE;
            var chunk = blob.slice(start, Math.min(start + CHUNK_SIZE, blob.size));
            var formData = new FormData();
            formData.append('isChunk', 'true');
            formData.append('chunk', chunk, originalFileName);
            formData.append('chunkNumber', chunkNumber);
            formData.append('totalChunks', totalChunks);
            formData.append('originalFileName', originalFileName);
            formData.append('fileIdentifier', fileIdentifier);
            return fetch(uploadURL, { method: 'POST', body: formData })
                .then(function (response) {
                    if (!response.ok) throw new Error('خطای سرور: ' + response.statusText);
                    return response.json();
                })
                .then(function (result) {
                    if (!result.success) throw new Error(result.message || 'خطای پردازش سرور');
                    chunkNumber++;
                    if (onProgress) onProgress(Math.round((chunkNumber / totalChunks) * 100));
                    if (result.url) return result.url;
                    return next();
                });
        }
        return next();
    }

    function legacyUploadAndOpen(getBlob) {
        downloadOverlay.style.display = 'flex';
        downloadStatusText.innerText = 'در حال آماده‌سازی لینک دانلود...';
        Promise.resolve().then(getBlob).then(function (blob) {
            if (!blob || !blob.size) throw new Error('فایل دریافتی خالی است.');
            downloadStatusText.innerText = 'در حال آماده‌سازی لینک دانلود (0%)...';
            return uploadBlobInChunks(blob, function (percent) {
                downloadStatusText.innerText = 'در حال آماده‌سازی لینک دانلود (' + percent + '%)...';
            });
        }).then(function (finalUrl) {
            downloadOverlay.style.display = 'none';
            openInExternalBrowser(finalUrl);
        }).catch(function (error) {
            downloadOverlay.style.display = 'none';
            console.error('خطای دانلود:', error);
            createNotification('ارتباط با سرور دانلود برقرار نشد. لطفاً اتصال اینترنت خود را بررسی کنید.');
        });
    }

    function dataURLToBlob(dataURL) {
        return fetch(dataURL).then(function (res) { return res.blob(); }).catch(function () {
            var parts = String(dataURL).split(',');
            var mimeMatch = parts[0].match(/:(.*?);/);
            var mime = mimeMatch ? mimeMatch[1] : 'video/mp4';
            var binary = atob(parts[1]);
            var bytes = new Uint8Array(binary.length);
            for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
            return new Blob([bytes], { type: mime });
        });
    }

    // ================================================================
    // --- دکمه‌ی برگشت گوشی (مثل کروم) ---
    // ویرایشگر «عمق» صفحه‌اش را می‌فرستد (AE_NAV): ۰ = صفحه‌ی اول برنامه، بیشتر = داخل
    // ویرایشگر یا یک پنجره. تا وقتی عمق بیشتر از صفر است یک ورودیِ ساختگی در تاریخچه
    // نگه داشته می‌شود؛ دکمه‌ی برگشت همان را برمی‌دارد و لودر به ویرایشگر می‌گوید یک قدم
    // برگردد (AE_BACK). در صفحه‌ی اول، دکمه‌ی برگشت مثل همیشه کار خود برنامه را می‌کند.
    // ================================================================
    var aeDepth = 0, aeDummy = false, aeIgnore = 0;
    function aeSync() {
        if (aeDepth > 0) {
            if (!aeDummy) {
                try { history.pushState({ aeBack: 1 }, '', location.href); aeDummy = true; } catch (e) {}
            }
        } else if (aeDummy) {
            aeDummy = false;
            aeIgnore++;
            try { history.back(); } catch (e) { aeIgnore--; }
        }
    }
    window.addEventListener('popstate', function () {
        if (aeIgnore > 0) { aeIgnore--; return; }
        if (!aeDummy) return;
        aeDummy = false;
        if (aeDepth > 0 && iframe && iframe.contentWindow) {
            try { iframe.contentWindow.postMessage({ type: 'AE_BACK' }, siteOrigin); } catch (e) {}
        }
    });

    // ================================================================
    // --- ارتباط با برنامه‌ی داخلِ آی‌فریم ---
    // ================================================================
    window.addEventListener('message', function (event) {
        if (!iframe || !iframe.contentWindow) return;
        if (event.origin !== siteOrigin) return;
        var data = event.data;
        if (!data || !data.type) return;

        if (data.type === 'AE_HELLO') {
            try { iframe.contentWindow.postMessage({ type: 'AE_BRIDGE', v: 1 }, siteOrigin); } catch (e) {}
            return;
        }
        if (data.type === 'AE_NAV') {
            aeDepth = Math.max(0, parseInt(data.depth, 10) || 0);
            aeSync();
            return;
        }

        if (data.type === 'REQUEST_USER_DATA') {
            try {
                var userString = localStorage.getItem('user');
                iframe.contentWindow.postMessage({ type: 'USER_DATA_RESPONSE', payload: userString }, siteOrigin);
            } catch (e) {
                iframe.contentWindow.postMessage({ type: 'USER_DATA_RESPONSE', payload: null, error: e.message }, siteOrigin);
            }
            return;
        }
        if (data.type === 'NAVIGATE_TO_PREMIUM') {
            document.documentElement.classList.remove('tts-app-lock');
            window.top.location.href = '#/nav/online/news/getSingle/1149636/eyJpdiI6Im1JcFBaUCtld1JxR1JLUkd5NlpNZnc9PSIsInZhbHVlIjoiSTZaeHdBd2tDODVDajduSllBejhSSG01NUUyUHd0cTI2R0pCbFdPUmZVZjVjM01NOGxuOXVlL3ZGZUZjZmF1YyIsIm1hYyI6IjlhZWZkM2FlNGUzMzM5OTNmYjExMWQ3M2JhMWZiMGRmMDJlM2FhN2UyNDllZDA0N2ZkMWFlYzdhMjQ3ZDc5ODAiLCJ0YWciOiIifQ==/20934991';
            return;
        }
        if (data.type === 'NAVIGATE_TO_URL' && data.url) {
            document.documentElement.classList.remove('tts-app-lock');
            window.top.location.href = data.url;
            return;
        }

        // ★ روشِ اصلیِ دانلود: سرور لینکِ aisada را ساخته؛ لودر فقط بازش می‌کند
        if (data.type === 'OPEN_EXTERNAL_URL' && data.url) {
            openInExternalBrowser(data.url);
            return;
        }

        // پشتیبانِ قدیمی (فقط اگر سرور نتوانسته باشد لینک بسازد)
        if (data.type === 'DOWNLOAD_REQUEST' && data.url) {
            legacyUploadAndOpen(function () {
                downloadStatusText.innerText = 'در حال دریافت فایل از سرور...';
                return fetch(data.url).then(function (r) {
                    if (!r.ok) throw new Error('خطا در خواندن فایل: ' + r.statusText);
                    return r.blob();
                });
            });
            return;
        }
        if (data.type === 'DOWNLOAD_REQUEST_BASE64' && data.base64) {
            legacyUploadAndOpen(function () { return dataURLToBlob(data.base64); });
        }
    });

    // --- رویدادهای پنجره ---
    setVhVariable();
    window.addEventListener('resize', function () {
        setVhVariable();
        if (!appShown && loadingContainer.style.display !== 'none') {
            resizeCanvas();
            initParticles();
        }
    });
    // وقتی کاربر از برنامه بیرون می‌رود، انیمیشنِ لودینگ هم می‌ایستد
    document.addEventListener('visibilitychange', function () {
        if (appShown) return;
        if (document.hidden) { if (animationFrameId) cancelAnimationFrame(animationFrameId); animationFrameId = 0; }
        else if (!animationFrameId && loadingContainer.style.display !== 'none') animate();
    });

    // شروع
    loadIframe();
})();
</script>
</p>
<!-- پایان کد کامل -->