File size: 52,375 Bytes
abc7c31
 
 
 
 
b8360f5
abc7c31
b8360f5
abc7c31
b7f33b9
0990804
abc7c31
6a16ddb
b8360f5
6a16ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abc7c31
6a16ddb
 
 
 
b8360f5
 
 
6a16ddb
 
 
b8360f5
6a16ddb
 
 
 
 
 
b7f33b9
6a16ddb
b7f33b9
6a16ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8360f5
6a16ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
b8360f5
6a16ddb
 
 
 
b8360f5
6a16ddb
 
 
 
abc7c31
6a16ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8360f5
6a16ddb
 
 
 
 
b8360f5
 
 
6a16ddb
b8360f5
 
 
6a16ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8360f5
 
 
6a16ddb
 
 
 
 
b8360f5
b7f33b9
abc7c31
 
6a16ddb
abc7c31
 
6a16ddb
 
abc7c31
 
 
 
 
6a16ddb
 
b8360f5
 
 
abc7c31
6a16ddb
abc7c31
6a16ddb
 
abc7c31
 
 
6a16ddb
abc7c31
b8360f5
abc7c31
 
 
6a16ddb
abc7c31
 
6a16ddb
abc7c31
 
b8360f5
abc7c31
b8360f5
6a16ddb
 
b8360f5
abc7c31
 
 
 
 
 
6a16ddb
abc7c31
 
 
6a16ddb
b8360f5
6a16ddb
 
 
 
 
 
b8360f5
6a16ddb
b8360f5
6a16ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8360f5
 
abc7c31
 
 
 
6a16ddb
b8360f5
 
abc7c31
6a16ddb
 
abc7c31
6a16ddb
abc7c31
 
b8360f5
6a16ddb
b8360f5
6a16ddb
 
b8360f5
6a16ddb
 
 
 
b8360f5
 
 
 
abc7c31
 
6a16ddb
 
 
 
 
 
b8360f5
0990804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8360f5
6a16ddb
 
 
b8360f5
6a16ddb
 
 
 
b7f33b9
6a16ddb
0990804
 
 
 
 
abc7c31
6a16ddb
 
b8360f5
0990804
6a16ddb
 
 
0990804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a16ddb
0990804
6a16ddb
0990804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a16ddb
 
0990804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a16ddb
 
 
 
0990804
6a16ddb
 
 
 
 
 
0990804
 
 
 
6a16ddb
b8360f5
0990804
b8360f5
6a16ddb
0990804
 
6a16ddb
 
 
 
 
 
0990804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a16ddb
 
0990804
 
 
 
 
 
 
 
 
 
 
 
 
 
6a16ddb
 
 
 
0990804
6a16ddb
 
 
0990804
6a16ddb
 
 
0990804
6a16ddb
 
 
0990804
6a16ddb
 
 
 
 
0990804
6a16ddb
0990804
6a16ddb
b8360f5
6a16ddb
 
b8360f5
6a16ddb
0990804
 
 
 
 
6a16ddb
 
 
b8360f5
6a16ddb
abc7c31
0990804
6a16ddb
b8360f5
6a16ddb
0990804
 
6a16ddb
 
 
 
b7f33b9
abc7c31
 
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
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alpha TTS - نسل جدید تبدیل متن به صدا</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800;900&display=swap');

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

        @keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes modalZoomIn { from { opacity: 0; transform: scale(0.9) translateY(20px); } to { opacity: 1; transform: scale(1) translateY(0); } }
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }

        /* --- Original Loading Animation Keyframes --- */
        @keyframes rotate-loader-orbital { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes orbit-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes satellite-pulse-1 { from { transform: scale(0.7) translateX(-50%); opacity: 0.6; } to { transform: scale(1.1) translateX(-50%); opacity: 1; } }
        @keyframes satellite-pulse-2 { from { transform: scale(0.7) translateY(-50%); opacity: 0.6; } to { transform: scale(1.1) translateY(-50%); opacity: 1; } }
        @keyframes satellite-pulse-3 { from { transform: scale(0.7) translateX(50%); opacity: 0.6; } to { transform: scale(1.1) translateX(50%); opacity: 1; } }

        /* --- Base Styles --- */
        body {
            font-family: var(--app-font); direction: rtl; background-color: var(--app-bg);
            color: var(--text-primary); font-size: 16px; line-height: 1.8; margin: 0;
            padding: 2.5rem 0; min-height: 100vh; -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale; display: flex; justify-content: center;
            align-items: flex-start; overflow-x: hidden;
            background-image: radial-gradient(var(--text-tertiary) 0.5px, transparent 0.5px);
            background-size: 20px 20px; background-position: -10px -10px;
        }
        .container { max-width: 820px; width: 92%; margin: 0 auto; }
        
        /* --- App Header --- */
        .app-header { padding: 0.5rem 0 2.5rem 0; text-align: center; margin-bottom: 1.5rem; animation: fadeIn 0.8s 0.2s ease-out backwards; }
        .app-header h1 { font-size: 2.5em; font-weight: 900; margin: 0 0 0.8rem 0; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: -1px; }
        .app-header p { font-size: 1.05em; color: var(--text-secondary); margin-top: 0; opacity: 0.9; font-weight: 400; line-height: 1.7; }
        
        /* --- Main Content Panel --- */
        .main-content { padding: 3rem; background-color: var(--panel-bg); border-radius: var(--radius-card); box-shadow: var(--shadow-xl); border: 1px solid var(--panel-border); animation: fadeIn 0.8s 0.4s ease-out backwards; }
        .form-group { margin-bottom: 2.2rem; }
        label { display: block; font-weight: 700; color: var(--text-primary); font-size: 1.1em; margin-bottom: 1rem; }
        textarea, input[type="text"] { width: 100%; padding: 1rem 1.2rem; border-radius: var(--radius-input); border: 1px 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: 1rem; box-sizing: border-box; transition: var(--transition-smooth); }
        textarea:focus, input[type="text"]:focus { outline: none; border-color: var(--accent-primary); box-shadow: 0 0 0 3px var(--accent-primary-glow), var(--shadow-sm) inset; background-color: var(--panel-bg); }
        textarea { min-height: 120px; resize: vertical; }
        .char-counter-wrapper { font-size: 0.85em; color: var(--text-tertiary); text-align: left; margin-top: 0.75rem; padding: 0 0.2rem; }
        #char-count { font-weight: 600; color: var(--accent-primary); }
        
        /* --- Speaker Selection Display --- */
        #selected-speaker-display { text-align: center; margin-top: 1.5rem; }
        #selected-speaker-card { display: inline-flex; align-items: center; background: linear-gradient(135deg, var(--input-bg) 0%, var(--panel-bg) 100%); border-radius: 50px; padding: 0.75rem 0.75rem 0.75rem 1.5rem; box-shadow: var(--shadow-md); border: 1px solid var(--panel-border); transition: var(--transition-bounce); cursor: pointer; margin-bottom: 1.5rem; }
        #selected-speaker-card:hover { transform: translateY(-6px) scale(1.03); box-shadow: var(--shadow-lg); border-color: var(--accent-primary); }
        #selected-speaker-card img { width: 60px; height: 60px; border-radius: 50%; object-fit: cover; margin-left: 1rem; border: 3px solid var(--accent-secondary); box-shadow: 0 0 15px -3px var(--accent-secondary-glow); transition: var(--transition-smooth); }
        #selected-speaker-info { text-align: right; }
        #selected-speaker-info h3 { margin: 0; font-size: 1.25em; font-weight: 800; }
        #selected-speaker-info p { margin: 2px 0 0; color: var(--text-secondary); font-size: 0.85em; font-weight: 500; }
        #change-speaker-btn { display: inline-flex; align-items: center; justify-content: center; padding: 12px 24px; border-radius: var(--radius-btn); background: var(--panel-bg); border: 1px solid var(--input-border); color: var(--text-primary); cursor: pointer; font-family: var(--app-font); font-weight: 600; font-size: 1em; transition: var(--transition-smooth); box-shadow: var(--shadow-md); }
        #change-speaker-btn:hover { background: var(--input-bg); border-color: var(--accent-primary); color: var(--accent-primary); transform: translateY(-3px) scale(1.05); box-shadow: var(--shadow-lg); }

        /* --- Modals --- */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(18, 24, 38, 0.6); backdrop-filter: blur(10px) saturate(150%); display: none; align-items: center; justify-content: center; z-index: 1000; opacity: 0; transition: opacity var(--transition-smooth); }
        .modal-overlay.visible { display: flex; opacity: 1; }
        .modal-dialog { background: var(--panel-bg); padding: 2.5rem; border-radius: var(--radius-card); width: 90%; box-shadow: var(--shadow-xl); border: 1px solid var(--panel-border); opacity: 0; animation: modalZoomIn 0.4s cubic-bezier(0.4, 0, 0.2, 1) forwards; }
        .modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; padding-bottom: 1.5rem; border-bottom: 1px solid var(--panel-border); }
        .modal-header h2 { margin: 0; font-size: 1.8em; font-weight: 800; color: var(--accent-primary); }
        .close-modal-btn { background: none; border: none; font-size: 2.5rem; cursor: pointer; color: var(--text-tertiary); transition: var(--transition-smooth); line-height: 1; }
        .close-modal-btn:hover { color: var(--accent-primary); transform: rotate(90deg) scale(1.1); }
        #speaker-modal .modal-dialog { max-width: 750px; max-height: 85vh; overflow-y: auto; }
        #speaker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 1.5rem; }
        .speaker-card { cursor: pointer; transition: var(--transition-smooth); text-align: center; position: relative; border-radius: var(--radius-card); padding: 0.5rem; }
        .speaker-card:hover { transform: translateY(-8px); }
        .speaker-card input[type="radio"] { display: none; }
        .speaker-card .speaker-visual { border: 3px solid transparent; border-radius: 18px; overflow: hidden; box-shadow: var(--shadow-md); position: relative; background-color: var(--input-bg); transition: var(--transition-bounce); }
        .speaker-card:hover .speaker-visual { box-shadow: var(--shadow-lg); }
        .speaker-card img { width: 100%; height: 130px; object-fit: cover; display: block; background-color: #e0e0e0; border-radius: 14px; transition: transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94); }
        .speaker-card:hover img { transform: scale(1.1); }
        .speaker-card .speaker-name { padding: 0.8rem 0.4rem 0.2rem; font-weight: 600; font-size: 0.95em; color: var(--text-secondary); transition: color 0.2s; }
        .speaker-card input[type="radio"]:checked + .speaker-visual { border-color: var(--accent-secondary); box-shadow: 0 0 25px -5px var(--accent-secondary-glow); transform: scale(1.05); }

        /* --- Slider --- */
        .label-with-info { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1.2rem; }
        .info-icon { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 50%; background-color: var(--input-bg); border: 1px solid var(--input-border); color: var(--text-secondary); font-size: 0.9em; font-weight: 700; cursor: pointer; transition: var(--transition-smooth); user-select: none; }
        .info-icon:hover { background-color: var(--accent-primary); color: white; border-color: var(--accent-primary); transform: scale(1.1); box-shadow: 0 0 10px var(--accent-primary-glow); }
        .slider-container { display: flex; align-items: center; gap: 1.5rem; }
        input[type="range"] { flex-grow: 1; -webkit-appearance: none; appearance: none; width: 100%; height: 6px; background: var(--input-border); border-radius: 3px; outline: none; cursor: pointer; }
        input[type="range"]::-webkit-slider-runnable-track { background: linear-gradient(to right, var(--accent-secondary) 0%, var(--accent-primary) 100%); height: 6px; border-radius: 3px; }
        input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 24px; height: 24px; background: #fff; border-radius: 50%; cursor: pointer; border: 4px solid var(--accent-primary); box-shadow: var(--shadow-md); margin-top: -9px; transition: var(--transition-fast); }
        input[type="range"]:hover::-webkit-slider-thumb { transform: scale(1.15); box-shadow: 0 0 0 8px var(--accent-primary-glow); }
        #temperature-value { font-weight: 700; background-color: var(--input-bg); padding: 0.5rem 1rem; border-radius: 8px; border: 1px solid var(--input-border); min-width: 45px; text-align: center; color: var(--accent-primary); font-size: 1em; box-shadow: var(--shadow-sm); }
        
        /* --- Generate Button --- */
        #generate-btn { width: 100%; padding: 1.1rem 1.5rem; font-size: 1.25em; font-weight: 800; font-family: var(--app-font); 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), transform 0.15s ease-out; box-shadow: 0 6px 12px -3px var(--accent-primary-glow), 0 6px 12px -3px var(--accent-secondary-glow); position: relative; overflow: hidden; letter-spacing: 0.5px; }
        #generate-btn:hover:not(:disabled) { transform: translateY(-5px) scale(1.02); box-shadow: 0 8px 20px -4px var(--accent-primary-glow), 0 8px 20px -4px var(--accent-secondary-glow); }
        #generate-btn:disabled { background: var(--text-tertiary); cursor: not-allowed; box-shadow: none; color: var(--text-secondary); }
        #generate-btn svg { display:inline-block; margin-left: 0.5em; width:1.2em; height:1.2em; vertical-align: middle; }

        /* --- Output Section --- */
        #output-section { margin-top: 3rem; display: flex; align-items: center; justify-content: center; flex-direction: column; min-height: 220px; position: relative; box-sizing: border-box; padding: 2rem; background-color: var(--input-bg); border-radius: var(--radius-card); border: 2px dashed var(--input-border); box-shadow: var(--shadow-sm) inset; transition: var(--transition-smooth); }
        #output-section.has-content { background-color: var(--panel-bg); border: 1px solid var(--panel-border); box-shadow: var(--shadow-lg); padding: 0; min-height: auto; }
        #status-message { font-weight: 500; color: var(--text-secondary); text-align: center; font-size: 1.1em; }
        
        /* --- Original Loading Animation --- */
        #loading-animation-wrapper { display: none; flex-direction: column; align-items: center; justify-content: center; gap: 1.8rem; width: 100%; }
        .orbital-loader { width: 110px; height: 110px; position: relative; animation: rotate-loader-orbital 10s linear infinite; }
        .orbit { position: absolute; top: 50%; left: 50%; border: 2px dashed rgba(74, 108, 250, 0.35); border-radius: 50%; transform-origin: center center; }
        .orbit:nth-child(1) { width: 35px; height: 35px; margin: -17.5px 0 0 -17.5px; animation: orbit-spin 2.8s linear infinite reverse; }
        .orbit:nth-child(2) { width: 65px; height: 65px; margin: -32.5px 0 0 -32.5px; animation: orbit-spin 3.8s linear infinite; }
        .orbit:nth-child(3) { width: 95px; height: 95px; margin: -47.5px 0 0 -47.5px; animation: orbit-spin 4.8s linear infinite reverse; }
        .orbit .satellite { position: absolute; width: 10px; height: 10px; border-radius: 50%; background-color: var(--accent-primary); box-shadow: 0 0 8px var(--accent-primary), 0 0 12px var(--accent-secondary); }
        .orbit:nth-child(1) .satellite { top: -5px; left: 50%; animation: satellite-pulse-1 1.4s ease-in-out infinite alternate; }
        .orbit:nth-child(2) .satellite { top: 50%; left: -5px; background-color: var(--accent-secondary); animation: satellite-pulse-2 1.4s 0.2s ease-in-out infinite alternate; }
        .orbit:nth-child(3) .satellite { bottom: -5px; right: 50%; animation: satellite-pulse-3 1.4s 0.4s ease-in-out infinite alternate;}
        #loading-text { font-size: 1.2em; font-weight: 700; color: var(--text-primary); text-align: center; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

        /* --- Original Audio Player Styles --- */
        #audio-player-content { display: none; width: 100%; padding: 1.5rem; box-sizing: border-box; flex-direction: column; gap: 1.2rem; }
        .audio-waveform-container { display: flex; align-items: center; gap: 1rem; width: 100%; margin-bottom: 1rem; }
        .audio-time { font-size: 0.9em; color: var(--text-secondary); min-width: 40px; text-align: center; font-variant-numeric: tabular-nums; user-select: none; }
        .audio-waveform { flex-grow: 1; height: 60px; position: relative; overflow: hidden; display: flex; align-items: center; justify-content: center; margin-bottom: 0.5rem; }
        #audio-waveform-canvas { display: block; max-width: 100%; height: 100%; }
        .audio-waveform-dashed-line { position: absolute; top: 50%; left: 0; width: 100%; height: 1px; background-image: linear-gradient(to right, var(--waveform-dashed-line-color) 33%, transparent 0%); background-position: center; background-size: 10px 1px; transform: translateY(-50%); z-index: 1; }
        .audio-controls-group { display: flex; justify-content: center; align-items: center; gap: 1.5rem; margin-bottom: 1rem; }
        .audio-skip-btn, .audio-play-pause-btn-large, .audio-volume-btn, .audio-speed-btn { background: none; border: none; cursor: pointer; padding: 8px; transition: transform 0.2s, opacity 0.2s; }
        .audio-skip-btn, .audio-play-pause-btn-large, .audio-volume-btn { color: var(--text-secondary); }
        .audio-skip-btn:hover, .audio-play-pause-btn-large:hover, .audio-volume-btn:hover { color: var(--accent-primary); opacity: 0.9; }
        .audio-skip-btn:active, .audio-play-pause-btn-large:active, .audio-volume-btn:active { transform: scale(0.9); }
        .audio-skip-btn svg { width: 28px; height: 28px; fill: currentColor; }
        .audio-play-pause-btn-large { padding: 0; width: 50px; height: 50px; }
        .audio-play-pause-btn-large svg { width: 38px; height: 38px; fill: currentColor; }
        .audio-utility-controls { display: flex; align-items: center; justify-content: space-between; width: 100%; }
        .audio-volume-btn svg { width: 24px; height: 24px; fill: currentColor; }
        .audio-speed-btn { font-family: var(--app-font); font-size: 0.9em; font-weight: 600; background-color: var(--panel-bg); border: 1px solid var(--panel-border); border-radius: 8px; min-width: 40px; text-align: center; color: var(--text-primary); box-shadow: var(--shadow-sm); }
        .audio-speed-btn:hover { background-color: var(--input-bg); }
        #hidden-audio-player { display: none !important; }

        @media (max-width: 600px) {
            body { padding: 1.5rem 0; }
            .main-content { padding: 1.5rem; }
            .app-header h1 { font-size: 2em; }
            #selected-speaker-card { flex-direction: column; padding: 1rem; border-radius: var(--radius-card); }
            #selected-speaker-card img { margin-left: 0; margin-bottom: 1rem; }
        }
    </style>
</head>
<body>

    <div class="container">
        <header class="app-header">
            <h1>مولد صدای هوشمند آلفا</h1>
            <p>کیفیت استودیو، قدرت هوش مصنوعی. صدایی فراتر از انتظار خلق کنید.</p>
        </header>

        <main class="main-content">
            <form id="tts-form">
                <div class="form-group">
                    <label for="text-input">📝 متن اصلی</label>
                    <textarea id="text-input" rows="5" placeholder="متن خود را برای تبدیل به گفتار اینجا وارد کنید..."></textarea>
                    <div class="char-counter-wrapper">
                        <span id="char-count">0</span> / <span id="char-max">50000</span> نویسه
                    </div>
                </div>

                <div class="form-group">
                    <label for="prompt-input">🗣️ توصیف لحن و احساس (اختیاری)</label>
                    <input type="text" id="prompt-input" placeholder="مثال: با لحنی آرام و قصه‌گو، یا صدای یک گوینده خبر حرفه‌ای">
                </div>

                <div class="form-group">
                    <label>🎤 گوینده منتخب</label>
                    <div id="selected-speaker-display">
                        <div id="selected-speaker-card" title="برای تغییر گوینده کلیک کنید">
                            <img id="selected-speaker-img" src="" alt="عکس گوینده">
                            <div id="selected-speaker-info">
                                <h3 id="selected-speaker-name"></h3>
                                <p id="selected-speaker-desc"></p>
                            </div>
                        </div>
                        <button type="button" id="change-speaker-btn">تغییر گوینده</button>
                    </div>
                </div>

                <div class="form-group">
                    <div class="label-with-info">
                        <label for="temperature-slider">🌡️ خلاقیت و پویایی صدا</label>
                        <div class="info-icon" id="temp-info-icon" role="button" tabindex="0" aria-label="اطلاعات بیشتر">!</div>
                    </div>
                    <div class="slider-container">
                        <input type="range" id="temperature-slider" min="0.1" max="1.5" step="0.05" value="0.9">
                        <span id="temperature-value">0.9</span>
                    </div>
                </div>

                <button type="submit" id="generate-btn">✨ خلق صدا با آلفا</button>
            </form>

            <div id="output-section">
                <div id="status-message">صدای تولید شده در اینجا ظاهر خواهد شد.</div>
                <div id="loading-animation-wrapper">
                      <div class="orbital-loader">
                         <div class="orbit"><div class="satellite"></div></div>
                         <div class="orbit"><div class="satellite"></div></div>
                         <div class="orbit"><div class="satellite"></div></div>
                     </div>
                     <p id="loading-text">در حال پردازش هوشمند و تولید صدا...</p>
                </div>
                
                <div id="audio-player-content">
                     <div class="audio-waveform-container">
                         <span class="audio-time audio-current-time">0:00</span>
                         <div class="audio-waveform">
                             <canvas id="audio-waveform-canvas"></canvas>
                             <div class="audio-waveform-dashed-line"></div>
                         </div>
                         <span class="audio-time audio-total-time">0:00</span>
                     </div>
                      <div class="audio-controls-group">
                         <button class="audio-skip-btn backward">
                             <svg viewBox="0 0 24 24"><path d="M11 16V8l-4 4 4 4zm4-12v16l7-8-7-8z"></path></svg>
                         </button>
                         <button class="audio-play-pause-btn-large">
                             <svg viewBox="0 0 24 24" class="play-icon"><path d="M8 5v14l11-7z"></path></svg>
                             <svg viewBox="0 0 24 24" class="pause-icon" style="display:none;"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path></svg>
                         </button>
                         <button class="audio-skip-btn forward">
                             <svg viewBox="0 0 24 24"><path d="M13 16V8l4 4-4 4zM9 4v16L2 12l7-8z"></path></svg>
                         </button>
                     </div>
                      <div class="audio-utility-controls">
                         <button class="audio-volume-btn">
                             <svg viewBox="0 0 24 24" class="volume-high-icon"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"></path></svg>
                             <svg viewBox="0 0 24 24" class="volume-mute-icon" style="display:none;"><path d="M7 9v6h4l5 5V4L11 9H7zM16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zM19 12c0 .94-.23 1.82-.68 2.6L19 14.88c.45-.88.7-1.88.7-2.88 0-4.01-2.99-7.14-7-8.05v2.06c2.89.86 5 3.54 5 6.71zM4.55 4L2 6.55 9.45 14H7v6h4l5 5V14.55l4.05 4.05L22 18 12 8 4.55 4z"></path></svg>
                         </button>
                         <button class="audio-speed-btn">1x</button>
                     </div>
                </div>
                <audio id="hidden-audio-player" style="display: none;"></audio>
            </div>
        </main>
    </div>

    <!-- Modals -->
    <div id="speaker-modal" class="modal-overlay">
        <div class="modal-dialog">
            <div class="modal-header">
                <h2>گالری گویندگان آلفا</h2>
                <button type="button" class="close-modal-btn" data-modal-id="speaker-modal">×</button>
            </div>
            <div id="speaker-grid"></div>
        </div>
    </div>
    <div id="info-modal" class="modal-overlay">
        <div class="modal-dialog" style="max-width: 520px;">
            <div class="modal-header">
                <h2>🌡️ خلاقیت و پویایی صدا</h2>
                <button type="button" class="close-modal-btn" data-modal-id="info-modal">×</button>
            </div>
            <div>
                 <p style="color: var(--text-secondary); line-height: 1.9;">این پارامتر، میزان "غیرقابل پیش‌بینی بودن" و تنوع در صدای خروجی را کنترل می‌کند.</p>
                 <p><strong>مقادیر بالاتر (نزدیک به ۱.۵):</strong> صدایی بسیار متنوع، احساسی و پویا ایجاد می‌کند. ایده‌آل برای محتوای خلاقانه و هنری.</p>
                 <p><strong>مقادیر پایین‌تر (نزدیک به ۰.۱):</strong> صدایی پایدار، یکنواخت و قابل پیش‌بینی‌تر تولید می‌کند. مناسب برای خوانش متون رسمی و خبری.</p>
            </div>
        </div>
    </div>
    <input type="hidden" id="selected_speaker_id_storage" value="Charon">

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        const HF_SPACE_URL = "https://hamed744-ttspro.hf.space";
        const JOIN_QUEUE_URL = `${HF_SPACE_URL}/gradio_api/queue/join`;
        const GET_DATA_URL_BASE = `${HF_SPACE_URL}/gradio_api/queue/data`;
        const FILE_URL_BASE = `${HF_SPACE_URL}/gradio_api/file=`;
        const FN_INDEX = 1;

        // UPDATED SPEAKERS ARRAY WITH NEW NAMES, GENDERS, AND IMAGE URLs
        const speakers = [
            { id: "Charon", name: "شهاب (مرد)", desc: "صدایی قدرتمند و رسا", imgUrl: "https://uploadkon.ir/uploads/a18705_25IMG-۲۰۲۵۰۷۰۵-۱۱۰۵۴۹.jpg" },
            { id: "Zephyr", name: "آوا (زن)", desc: "لطیف و دلنشین", imgUrl: "https://uploadkon.ir/uploads/029605_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۲۵۲.jpg" },
            { id: "Achird", name: "نوید (مرد)", desc: "جوان و پرانرژی", imgUrl: "https://uploadkon.ir/uploads/697e05_25IMG-۲۰۲۵۰۶۰۹-۰۶۴۶۳۷.jpg" },
            { id: "Zubenelgenubi", name: "آرمان (مرد)", desc: "گرم و صمیمی", imgUrl: "https://uploadkon.ir/uploads/a8a705_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۶۲۹.jpg" }, // Changed to male
            { id: "Vindemiatrix", name: "مهسا (زن)", desc: "باوقار و رسمی", imgUrl: "https://uploadkon.ir/uploads/d74d05_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۸۳۸.jpg" }, // Changed to female
            { id: "Sadachbia", name: "سامان (مرد)", desc: "شاداب و پویا", imgUrl: "https://uploadkon.ir/uploads/580205_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۳۳۰.jpg" }, // Changed to male
            { id: "Sadaltager", name: "آرش (مرد)", desc: "مطمئن و تاثیرگذار", imgUrl: "https://uploadkon.ir/uploads/c4db05_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۵۰۰.jpg" },
            { id: "Sulafat", name: "شبنم (زن)", desc: "آرام و متین", imgUrl: "https://uploadkon.ir/uploads/995005_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۶۱۱.jpg" },
            { id: "Laomedeia", name: "سحر (زن)", desc: "دوستانه و گیرا", imgUrl: "https://uploadkon.ir/uploads/660705_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۷۵۴.jpg" }, // Changed to female
            { id: "Achernar", name: "مریم (زن)", desc: "حرفه‌ای و واضح", imgUrl: "https://uploadkon.ir/uploads/4c2905_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۰۳۶.jpg" },
            { id: "Alnilam", name: "بهرام (مرد)", desc: "حماسی و نافذ", imgUrl: "https://uploadkon.ir/uploads/f0c205_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۲۲۰.jpg" },
            { id: "Schedar", name: "نیکان (مرد)", desc: "مهربان و شیرین", imgUrl: "https://uploadkon.ir/uploads/d37a05_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۳۲۵.jpg" }, // Changed to male
            { id: "Gacrux", name: "فرناز (زن)", desc: "پخته و قابل اعتماد", imgUrl: "https://uploadkon.ir/uploads/cff705_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۶۰۵.jpg" }, // Changed to female
            { id: "Pulcherrima", name: "سارا (زن)", desc: "جذاب و مدرن", imgUrl: "https://uploadkon.ir/uploads/acb105_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۷۴۳.jpg" },
            { id: "Umbriel", name: "مانی (مرد)", desc: "خلاق و متفاوت", imgUrl: "https://uploadkon.ir/uploads/68b505_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۹۱۴.jpg" },
            { id: "Algieba", name: "آرتین (مرد)", desc: "با اصالت و شیک", imgUrl: "https://uploadkon.ir/uploads/571005_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۰۳۹.jpg" }, // Changed to male
            { id: "Despina", name: "دلنواز (زن)", desc: "هنری و احساسی", imgUrl: "https://uploadkon.ir/uploads/5d7805_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۲۲۲.jpg" },
            { id: "Erinome", name: "روژان (زن)", desc: "شفاف و گویا", imgUrl: "https://uploadkon.ir/uploads/aa8805_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۳۴۹.jpg" }, // Changed to female
            { id: "Algenib", name: "امید (مرد)", desc: "انگیزه بخش و مثبت", imgUrl: "https://uploadkon.ir/uploads/a63c05_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۹۲۱.jpg" },
            { id: "Orus", name: "بردیا (مرد)", desc: "ورزشی و پرهیجان", imgUrl: "https://uploadkon.ir/uploads/8bc405_25IMG-۲۰۲۵۰۷۰۵-۱۲۱۴۳۳.jpg" },
            { id: "Aoede", name: "ترانه (زن)", desc: "موزیکال و خوش‌آهنگ", imgUrl: "https://uploadkon.ir/uploads/9cb405_25IMG-۲۰۲۵۰۷۰۵-۱۲۱۸۵۰.jpg" },
            { id: "Callirrhoe", name: "نیکو (زن)", desc: "روایتگر و قصه‌گو", imgUrl: "https://uploadkon.ir/uploads/ee5f05_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۰۴۷.jpg" }, // Changed to female
            { id: "Autonoe", name: "هستی (زن)", desc: "طبیعی و خودمانی", imgUrl: "https://uploadkon.ir/uploads/9b0505_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۲۲۲.jpg" },
            { id: "Enceladus", name: "کامیار (مرد)", desc: "مصمم و جدی", imgUrl: "https://uploadkon.ir/uploads/127805_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۴۱۴.jpg" },
            { id: "Iapetus", name: "کیانوش (مرد)", desc: "درخشان و گیرا", imgUrl: "https://uploadkon.ir/uploads/c98b05_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۶۰۵.jpg" }, // Changed to male
            { id: "Puck", name: "پویا (مرد)", desc: "بازیگوش و سرزنده", imgUrl: "https://uploadkon.ir/uploads/ca3605_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۸۳۹.jpg" },
            { id: "Kore", name: "مهتاب (زن)", desc: "نجواگر و آرامش‌بخش", imgUrl: "https://uploadkon.ir/uploads/b66605_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۰۳۵.jpg" },
            { id: "Fenrir", name: "سام (مرد)", desc: "جسور و بی‌باک", imgUrl: "https://uploadkon.ir/uploads/03c005_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۴۱۳.jpg" },
            { id: "Leda", name: "لیدا (زن)", desc: "کلاسیک و باوقار", imgUrl: "https://uploadkon.ir/uploads/710305_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۷۳۱.jpg" }
        ];

        // --- DOM Elements ---
        const form = document.getElementById('tts-form'); const textInput = document.getElementById('text-input'); const promptInput = document.getElementById('prompt-input'); const tempSlider = document.getElementById('temperature-slider'); const tempValueSpan = document.getElementById('temperature-value'); const generateBtn = document.getElementById('generate-btn'); const outputSection = document.getElementById('output-section'); const statusMessage = document.getElementById('status-message'); const loadingAnimationWrapper = document.getElementById('loading-animation-wrapper'); const selectedSpeakerIdStorage = document.getElementById('selected_speaker_id_storage'); const changeSpeakerBtn = document.getElementById('change-speaker-btn'); const selectedSpeakerCard = document.getElementById('selected-speaker-card'); const speakerGridInModal = document.getElementById('speaker-grid'); const selectedSpeakerImgDisplay = document.getElementById('selected-speaker-img'); const selectedSpeakerNameDisplay = document.getElementById('selected-speaker-name'); const selectedSpeakerDescDisplay = document.getElementById('selected-speaker-desc'); const speakerModal = document.getElementById('speaker-modal'); const infoModal = document.getElementById('info-modal'); const tempInfoIcon = document.getElementById('temp-info-icon'); const hiddenAudioPlayer = document.getElementById('hidden-audio-player'); const audioPlayerContent = document.getElementById('audio-player-content'); const audioCurrentTimeSpan = audioPlayerContent.querySelector('.audio-current-time'); const audioTotalTimeSpan = audioPlayerContent.querySelector('.audio-total-time'); const audioWaveformCanvas = document.getElementById('audio-waveform-canvas'); const waveformCtx = audioWaveformCanvas.getContext('2d'); const playPauseBtn = audioPlayerContent.querySelector('.audio-play-pause-btn-large'); const playIcon = playPauseBtn.querySelector('.play-icon'); const pauseIcon = playPauseBtn.querySelector('.pause-icon'); const skipBackwardBtn = audioPlayerContent.querySelector('.audio-skip-btn.backward'); const skipForwardBtn = audioPlayerContent.querySelector('.audio-skip-btn.forward'); const volumeBtn = audioPlayerContent.querySelector('.audio-volume-btn'); const volumeHighIcon = volumeBtn.querySelector('.volume-high-icon'); const volumeMuteIcon = volumeBtn.querySelector('.volume-mute-icon'); const speedBtn = audioPlayerContent.querySelector('.audio-speed-btn');
        let currentPlaybackSpeedIndex = 0; const playbackSpeeds = [1.0, 1.25, 1.5, 0.75]; let audioPeaks = []; let audioContext = null;

        // --- Character Counter ---
        const charCountSpan = document.getElementById('char-count'); const charMaxSpan = document.getElementById('char-max'); const MAX_CHARS = 50000;
        charMaxSpan.textContent = MAX_CHARS.toLocaleString('fa-IR');
        textInput.addEventListener('input', () => { const currentLength = textInput.value.length; charCountSpan.textContent = currentLength.toLocaleString('fa-IR'); charCountSpan.style.color = currentLength > MAX_CHARS ? 'red' : 'var(--accent-primary)'; });

        // --- Speaker Logic ---
        const getSpeakerById = (id) => speakers.find(s => s.id === id) || speakers[0];
        const getImageUrl = (speaker) => speaker.imgUrl;
        
        const updateSelectedSpeakerDisplay = (speakerId) => { const speaker = getSpeakerById(speakerId); selectedSpeakerImgDisplay.src = getImageUrl(speaker); selectedSpeakerNameDisplay.textContent = speaker.name; selectedSpeakerDescDisplay.textContent = speaker.desc; selectedSpeakerIdStorage.value = speaker.id; };
        const createSpeakerCardsInModal = () => { speakerGridInModal.innerHTML = ''; speakers.forEach((speaker) => { const cardLabel = document.createElement('label'); cardLabel.className = 'speaker-card'; cardLabel.setAttribute('for', `modal-speaker-${speaker.id}`); const isChecked = speaker.id === selectedSpeakerIdStorage.value ? 'checked' : ''; cardLabel.innerHTML = ` <input type="radio" name="modal_speaker_selection" value="${speaker.id}" id="modal-speaker-${speaker.id}" ${isChecked}> <div class="speaker-visual"> <img src="${getImageUrl(speaker)}" alt="${speaker.name}" loading="lazy"> </div> <div class="speaker-name">${speaker.name}</div> `; cardLabel.addEventListener('click', () => { updateSelectedSpeakerDisplay(speaker.id); hideModal(speakerModal); }); speakerGridInModal.appendChild(cardLabel); }); };

        // --- Modal Management ---
        const showModal = (modalElement) => { modalElement.classList.add('visible'); setTimeout(() => modalElement.querySelector('button')?.focus(), 50); }; const hideModal = (modalElement) => modalElement.classList.remove('visible'); changeSpeakerBtn.addEventListener('click', () => { createSpeakerCardsInModal(); showModal(speakerModal); }); selectedSpeakerCard.addEventListener('click', () => { createSpeakerCardsInModal(); showModal(speakerModal); }); tempInfoIcon.addEventListener('click', () => showModal(infoModal)); document.querySelectorAll('.modal-overlay').forEach(o => o.addEventListener('click', (e) => (e.target === o) && hideModal(o))); document.querySelectorAll('.close-modal-btn').forEach(b => b.addEventListener('click', () => hideModal(document.getElementById(b.dataset.modalId)))); document.addEventListener('keydown', (e) => (e.key === 'Escape') && document.querySelectorAll('.modal-overlay.visible').forEach(hideModal)); tempSlider.addEventListener('input', () => { tempValueSpan.textContent = tempSlider.value; });

        // --- Original Audio Player Logic (with Waveform Fix) ---
        const formatTime = (seconds) => { if (isNaN(seconds) || seconds < 0) return '0:00'; const minutes = Math.floor(seconds / 60); const remainingSeconds = Math.floor(seconds % 60); return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`; };
        
        function drawWaveform(progressRatio = 0) {
            const dpr = window.devicePixelRatio || 1;
            audioWaveformCanvas.width = audioWaveformCanvas.offsetWidth * dpr;
            audioWaveformCanvas.height = audioWaveformCanvas.offsetHeight * dpr;
            waveformCtx.scale(dpr, dpr);

            const width = audioWaveformCanvas.offsetWidth;
            const height = audioWaveformCanvas.offsetHeight;
            
            if (width === 0 || height === 0) return; // Extra safety check: Don't draw if canvas has no dimensions

            waveformCtx.clearRect(0, 0, width, height);

            const barWidth = 3; const barGap = 2; const totalBarAndGap = barWidth + barGap;
            const numBars = Math.floor(width / totalBarAndGap);
            const offset = (width - (numBars * totalBarAndGap)) / 2;

            const activeColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-active').trim();
            const inactiveColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-inactive').trim();

            // 1. Draw the entire waveform with the inactive color (as the base)
            waveformCtx.fillStyle = inactiveColor;
            for (let i = 0; i < numBars; i++) {
                const peak = audioPeaks[i] || 0;
                const barHeight = peak * height;
                const x = offset + i * totalBarAndGap;
                const y = (height - barHeight) / 2;
                waveformCtx.fillRect(x, y, barWidth, barHeight);
            }

            // 2. Create a linear gradient for the active part
            const activeFillEnd = progressRatio * width; // The absolute pixel position of the playback head
            const gradientFadeWidth = 80; // The width of the smooth transition zone in pixels
            const gradientSolidStart = Math.max(0, activeFillEnd - gradientFadeWidth); // Where active color is fully solid

            const activeGradient = waveformCtx.createLinearGradient(0, 0, width, 0);
            
            // Solid active color from left to gradientSolidStart
            activeGradient.addColorStop(0, activeColor);
            activeGradient.addColorStop(gradientSolidStart / width, activeColor);

            // Transition from active color to inactive color, ending at activeFillEnd
            activeGradient.addColorStop(activeFillEnd / width, inactiveColor);

            // 3. Apply this gradient as the fillStyle
            waveformCtx.fillStyle = activeGradient;

            // 4. Draw the waveform again on top. The gradient will automatically apply
            // to each bar based on its X position on the canvas, creating a smooth sweep effect.
            for (let i = 0; i < numBars; i++) {
                const peak = audioPeaks[i] || 0;
                const barHeight = peak * height;
                const x = offset + i * totalBarAndGap;
                const y = (height - barHeight) / 2;
                waveformCtx.fillRect(x, y, barWidth, barHeight);
            }
         }
        
        const updatePlayerUI = () => {
            playIcon.style.display = hiddenAudioPlayer.paused || hiddenAudioPlayer.ended ? 'block' : 'none';
            pauseIcon.style.display = !(hiddenAudioPlayer.paused || hiddenAudioPlayer.ended) ? 'block' : 'none';
            const currentTime = hiddenAudioPlayer.currentTime;
            const duration = hiddenAudioPlayer.duration;
            audioCurrentTimeSpan.textContent = formatTime(currentTime);
            if (isFinite(duration) && duration > 0) {
                audioTotalTimeSpan.textContent = formatTime(duration);
                // Schedule waveform redraw on the next animation frame
                requestAnimationFrame(() => drawWaveform(currentTime / duration));
            } else {
                audioTotalTimeSpan.textContent = '0:00';
                requestAnimationFrame(() => drawWaveform(0));
            }
        };
        
        async function processAudioForWaveform(audioBuffer) {
            if (!audioBuffer) { audioPeaks = []; return; }
            const channelData = audioBuffer.getChannelData(0);
            // Calculate numBars based on current visual width of the canvas
            const numBars = Math.floor(audioWaveformCanvas.offsetWidth / 5); // 5 = barWidth(3) + barGap(2)
            const samplesPerBar = Math.floor(channelData.length / numBars);
            const peaks = [];
            for (let i = 0; i < numBars; i++) {
                let maxPeak = 0;
                const start = i * samplesPerBar;
                // Ensure we don't read beyond the array bounds
                const end = Math.min(start + samplesPerBar, channelData.length);
                for (let j = start; j < end; j++) {
                    const value = Math.abs(channelData[j]);
                    if (value > maxPeak) maxPeak = value;
                }
                peaks.push(Math.min(1, Math.max(0, maxPeak * 1.5))); // Amplify for better visuals
            }
            audioPeaks = peaks;
            // Draw initial waveform on the next available frame to ensure canvas is ready
            requestAnimationFrame(() => drawWaveform(0));
        }
        
        playPauseBtn.addEventListener('click', () => hiddenAudioPlayer.paused ? hiddenAudioPlayer.play() : hiddenAudioPlayer.pause()); skipBackwardBtn.addEventListener('click', () => hiddenAudioPlayer.currentTime = Math.max(0, hiddenAudioPlayer.currentTime - 5)); skipForwardBtn.addEventListener('click', () => hiddenAudioPlayer.currentTime = Math.min(hiddenAudioPlayer.duration, hiddenAudioPlayer.currentTime + 5));
        volumeBtn.addEventListener('click', () => { hiddenAudioPlayer.muted = !hiddenAudioPlayer.muted; volumeHighIcon.style.display = hiddenAudioPlayer.muted ? 'none' : 'block'; volumeMuteIcon.style.display = hiddenAudioPlayer.muted ? 'block' : 'none'; });
        speedBtn.addEventListener('click', () => { currentPlaybackSpeedIndex = (currentPlaybackSpeedIndex + 1) % playbackSpeeds.length; const newSpeed = playbackSpeeds[currentPlaybackSpeedIndex]; hiddenAudioPlayer.playbackRate = newSpeed; speedBtn.textContent = `${newSpeed}x`; });
        hiddenAudioPlayer.addEventListener('timeupdate', updatePlayerUI); hiddenAudioPlayer.addEventListener('play', updatePlayerUI); hiddenAudioPlayer.addEventListener('pause', updatePlayerUI); hiddenAudioPlayer.addEventListener('ended', () => { hiddenAudioPlayer.currentTime = 0; updatePlayerUI(); });
        
        // IMPORTANT: Modified loadedmetadata listener for robust waveform display
        hiddenAudioPlayer.addEventListener('loadedmetadata', async () => {
            if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)();
            if (!hiddenAudioPlayer.src) { // If src is empty, clear waveform
                audioPeaks = [];
                requestAnimationFrame(() => drawWaveform(0));
                updatePlayerUI();
                return;
            }
            try {
                const response = await fetch(hiddenAudioPlayer.src);
                const arrayBuffer = await response.arrayBuffer();
                const decodedBuffer = await audioContext.decodeAudioData(arrayBuffer);
                await processAudioForWaveform(decodedBuffer);
            } catch (e) {
                console.error("Error decoding audio for waveform:", e);
                audioPeaks = [];
                requestAnimationFrame(() => drawWaveform(0)); // Ensure canvas is cleared on error
            }
            updatePlayerUI();
        });
        
        let resizeTimeout; window.addEventListener('resize', () => { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(() => { if (outputSection.classList.contains('has-content') && hiddenAudioPlayer.src) { requestAnimationFrame(() => drawWaveform(hiddenAudioPlayer.currentTime / hiddenAudioPlayer.duration)); } }, 250); });

        // --- State Management Functions ---
        const showLoadingState = () => { audioPlayerContent.style.display = 'none'; outputSection.classList.remove('has-content'); statusMessage.style.display = 'none'; loadingAnimationWrapper.style.display = 'flex'; generateBtn.disabled = true; generateBtn.innerHTML = ` <svg aria-hidden="true" role="status" fill="currentColor" viewBox="0 0 100 101" style="animation: spin 1s linear infinite;"> <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="#E5E7EB"/> <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0492C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentColor"/> </svg> در حال پردازش... `; };
        const showResultState = (isSuccess, message = '') => {
            loadingAnimationWrapper.style.display = 'none';
            if (isSuccess) {
                statusMessage.style.display = 'none'; audioPlayerContent.style.display = 'flex';
                outputSection.classList.add('has-content');
            } else {
                statusMessage.textContent = message || 'خطایی رخ داد. لطفاً دوباره تلاش کنید.';
                statusMessage.style.display = 'block'; audioPlayerContent.style.display = 'none';
                outputSection.classList.remove('has-content');
                hiddenAudioPlayer.src = ''; // Clear src on error
                audioPeaks = []; requestAnimationFrame(() => drawWaveform(0)); // Clear waveform
            }
            generateBtn.disabled = false; generateBtn.innerHTML = '✨ خلق صدا با آلفا';
        };

        // --- API Call ---
        async function generateAudio(event) {
            event.preventDefault(); showLoadingState();
            const text = textInput.value;
            if (!text.trim()) { showResultState(false, 'خطا: متن ورودی نمی‌تواند خالی باشد.'); return; }
            if (text.length > MAX_CHARS) { showResultState(false, `خطا: طول متن بیش از ${MAX_CHARS.toLocaleString('fa-IR')} نویسه است.`); return; }
            const payload = { fn_index: FN_INDEX, data: [false, null, text, promptInput.value, selectedSpeakerIdStorage.value, parseFloat(tempSlider.value)], event_data: null, session_hash: Math.random().toString(36).substring(2) };
            try {
                const joinQueueResponse = await fetch(JOIN_QUEUE_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
                if (!joinQueueResponse.ok) { throw new Error(`خطا در برقراری ارتباط با سرویس آلفا (کد: ${joinQueueResponse.status}).`); }
                let finalFilePath = null; const startTime = Date.now(); const timeoutDuration = 90000;
                while (Date.now() - startTime < timeoutDuration) {
                    const dataResponse = await fetch(`${GET_DATA_URL_BASE}?session_hash=${payload.session_hash}`);
                    if (!dataResponse.ok) { throw new Error(`خطا در دریافت داده از سرویس (کد: ${dataResponse.status})`); }
                    const responseText = await dataResponse.text(); const lines = responseText.trim().split('\n');
                    for (const line of lines) {
                        if (!line.startsWith('data:')) continue;
                        try {
                            const data = JSON.parse(line.substring(5));
                            if (data.msg === 'process_completed') {
                                if (data.success && data.output?.data?.[0] && (data.output.data[0].name || data.output.data[0].path)) { finalFilePath = data.output.data[0].name || data.output.data[0].path; } else { throw new Error(data.output?.error || 'خطای ناشناخته در پردازش سرور.'); }
                                break;
                            } else if (data.msg === 'queue_full') { throw new Error('صف پردازش پر است. لطفا کمی بعد تلاش کنید.'); }
                        } catch (e) { console.warn("Error parsing JSON from stream:", e, "Line:", line); }
                    }
                    if (finalFilePath) break;
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
                if (finalFilePath) {
                    // Force reload for robust waveform generation
                    hiddenAudioPlayer.src = ''; // Clear current source
                    hiddenAudioPlayer.load(); // Request browser to load it
                    hiddenAudioPlayer.src = `${FILE_URL_BASE}${finalFilePath}`; // Set new source
                    // loadedmetadata event listener will now handle processing and drawing
                    showResultState(true);
                } else if (Date.now() - startTime >= timeoutDuration) {
                    throw new Error('پردازش بیش از حد طول کشید و متوقف شد.');
                } else {
                    throw new Error('فایل صوتی از سرور دریافت نشد یا پردازش ناموفق بود.');
                }
            } catch (error) { console.error('خطا در فرآیند تولید صدا:', error); showResultState(false, error.message); }
        }

        // --- Initial Setup ---
        const defaultSpeakerId = speakers.length > 0 ? speakers[0].id : "Charon";
        updateSelectedSpeakerDisplay(selectedSpeakerIdStorage.value || defaultSpeakerId);
        form.addEventListener('submit', generateAudio);
        statusMessage.style.display = 'block'; loadingAnimationWrapper.style.display = 'none';
        audioPlayerContent.style.display = 'none'; outputSection.classList.remove('has-content');
    });
    </script>
</body>
</html>