File size: 162,245 Bytes
c66432a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
<!-- ==========================================
     PART 1: HTML SETUP & CSS ANIMATIONS
     تنظیمات اولیه، فونت‌ها و انیمیشن‌های CSS
     ========================================== -->
<!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 { --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); --accent-premium: #FFC107; --accent-premium-glow: rgba(255, 193, 7, 0.3); --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 fadeInOut { 0% { opacity: 0; transform: translateY(10px); } 10% { opacity: 1; transform: translateY(0); } 90% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-10px); } } 
        @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); } } 
        @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; } } 
        @keyframes badge-fade-in { from { opacity: 0; transform: translateY(-10px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } } 
        @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } 
        @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.05); } 100% { transform: scale(1); } }
        @keyframes pulse-gray { 0% { opacity: 0.6; } 50% { opacity: 1; } 100% { opacity: 0.6; } }
        @keyframes pulse-glow { 0% { box-shadow: 0 0 0 0 rgba(74, 108, 250, 0.4); } 70% { box-shadow: 0 0 0 20px rgba(74, 108, 250, 0); } 100% { box-shadow: 0 0 0 0 rgba(74, 108, 250, 0); } } 
        @keyframes shake { 0%, 100% { transform: rotate(0deg); } 10%, 30%, 50%, 70%, 90% { transform: rotate(-5deg); } 20%, 40%, 60%, 80% { transform: rotate(5deg); } } 
        @keyframes bounce { 0%, 20%, 50%, 80%, 100% {transform: translateY(0);} 40% {transform: translateY(-15px);} 60% {transform: translateY(-7px);} }
        @keyframes sound-wave { 0% { height: 2px; } 25% { height: 10px; } 50% { height: 5px; } 100% { height: 2px; } }

/* ==========================================
   PART 2: CSS GENERAL LAYOUT & FORM STYLES
   استایل‌های کلی بدنه، کانتینر اصلی و فرم‌ها
   ========================================== */
        html { scroll-behavior: smooth; } 
        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; } 
        .app-container { max-width: 820px; width: 92%; margin: 0 auto; } 
        .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 { position:relative; 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; } 
        .generate-btn { display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%; padding: 1.1rem 1.5rem; font-size: 1.25em; font-weight: 800; background: linear-gradient(95deg, var(--accent-secondary) 0%, var(--accent-primary) 100%); color: #fff; border: none; border-radius: var(--radius-btn); cursor: pointer; transition: all 0.3s ease; box-shadow: 0 6px 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: rgba(255,255,255,0.7); } 
        .generate-btn .spinner { width: 20px; height: 20px; border: 3px solid rgba(255, 255, 255, 0.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.8s linear infinite; display: none;} 
        .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: transparent; border-color: transparent; box-shadow: none; padding: 0; min-height: auto; } 
        .status-message { font-weight: 500; color: var(--text-secondary); text-align: center; font-size: 1.1em; } 
        .status-message.error { color: var(--text-primary); font-weight: 600; line-height: 1.9; }

/* ==========================================
   PART 3: CSS COMPONENTS & AUDIO PLAYER
   استایل‌های لودینگ، پلیر صدا و انتخاب گوینده
   ========================================== */
        .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 0.2s 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; } 
        .audio-player-content { display: none; width: 100%; padding: 1.5rem; box-sizing: border-box; flex-direction: column; gap: 1.2rem; animation: fadeIn 0.5s ease-out; background-color: var(--panel-bg); border: 1px solid var(--panel-border); box-shadow: var(--shadow-lg); border-radius: var(--radius-card); } 
        .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; 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 { background: none; border: none; cursor: pointer; padding: 8px; transition: transform 0.2s, opacity 0.2s; 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); } 
        .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); } 
        #selected-speaker-display { text-align: center; margin-top: 1.5rem; } 
        #selected-speaker-card { display: inline-flex; width: 320px; max-width: 100%; box-sizing: border-box; align-items: center; background: linear-gradient(135deg, var(--input-bg) 0%, var(--panel-bg) 100%); border-radius: 50px; padding: 8px; padding-right: 20px; box-shadow: var(--shadow-md); border: 1px solid var(--panel-border); transition: var(--transition-bounce); cursor: pointer; margin-bottom: 1.5rem; } 
        #selected-speaker-card img { width: 60px; height: 60px; border-radius: 50%; object-fit: cover; margin-left: 12px; border: 3px solid var(--accent-secondary); box-shadow: 0 0 15px -3px var(--accent-secondary-glow); transition: var(--transition-smooth); flex-shrink: 0; } 
        #selected-speaker-info { text-align: right; flex-grow: 1; min-width: 0; display: flex; flex-direction: column; justify-content: center; } 
        #selected-speaker-info h3, #selected-speaker-info p { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } 
        #selected-speaker-card:hover { transform: translateY(-6px) scale(1.03); box-shadow: var(--shadow-lg); border-color: var(--accent-primary); } 
        #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); }

/* ==========================================
   PART 4: CSS MODALS & UTILITY STYLES (MODIFIED)
   استایل‌های مودال‌ها، دکمه‌های دانلود و پاپ‌آپ‌ها
   ========================================== */
        .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; position: relative; } 
        .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; display: flex; flex-direction: column; } 
        #speaker-modal .modal-body { overflow-y: auto; } 
        #speaker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 1.5rem; padding-bottom: 0; transition: padding-bottom 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); } 
        .speaker-card { cursor: pointer; transition: var(--transition-smooth); text-align: center; position: relative; border-radius: var(--radius-card); padding: 0.5rem; } 
        .speaker-card:hover:not(.disabled) { transform: translateY(-8px); } 
        .speaker-card.disabled { opacity: 0.5; cursor: not-allowed; } 
        .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:not(.disabled) .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:not(.disabled) 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); } 
        .subscription-status-badge { display: inline-block; padding: 6px 16px; border-radius: 20px; font-size: 0.9em; font-weight: 700; margin-top: 1rem; letter-spacing: 0.5px; text-shadow: 0 1px 2px rgba(0,0,0,0.1); animation: badge-fade-in 0.6s 0.5s ease-out backwards; display: none; } 
        .subscription-status-badge.free-badge { background: linear-gradient(45deg, #6c757d, #495057); color: white; box-shadow: 0 4px 10px rgba(108, 117, 125, 0.3); } 
        .subscription-status-badge.paid-badge { background: linear-gradient(45deg, var(--accent-premium), #ffca2c); color: #333; box-shadow: 0 4px 10px var(--accent-premium-glow); } 
        #credit-status-message { text-align: center; color: var(--text-secondary); font-weight: 600; margin: 1rem 0; opacity: 0; transform: translateY(10px); transition: opacity 0.4s ease, transform 0.4s ease; height: 0; overflow: hidden; } 
        #credit-status-message.visible { opacity: 1; transform: translateY(0); height: auto; } 
        #upgrade-premium-btn { display: none; width: 100%; margin-top: 1.5rem; padding: 1rem; font-family: var(--app-font); font-size: 1.1em; font-weight: 800; color: #212529; background: linear-gradient(95deg, #FFD54F, var(--accent-premium) 100%); border: none; border-radius: var(--radius-btn); cursor: pointer; transition: transform 0.2s ease, box-shadow 0.2s ease; box-shadow: 0 8px 20px -5px var(--accent-premium-glow); } 
        #upgrade-premium-btn:hover { transform: translateY(-3px); box-shadow: 0 12px 25px -5px rgba(255, 193, 7, 0.4); }
        .download-wrapper { width: 100%; padding: 0 1.5rem 1.5rem; box-sizing: border-box; animation: fadeInUp 0.6s 0.2s ease-out backwards; display: flex; flex-direction: column; align-items: center; } 
        .beautiful-download-btn { display: flex; align-items: center; justify-content: center; gap: 12px; width: 100%; max-width: 400px; margin: 1.5rem auto 0.5rem auto; padding: 16px 24px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: #fff; border: none; border-radius: 14px; font-family: var(--app-font); font-weight: 800; font-size: 1.1em; cursor: pointer; position: relative; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.1), 0 2px 4px -1px rgba(37, 99, 235, 0.06); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); border-bottom: 4px solid #1d4ed8; }
        .beautiful-download-btn:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.2), 0 4px 6px -2px rgba(37, 99, 235, 0.1); filter: brightness(1.05); }
        .beautiful-download-btn:active:not(:disabled) { transform: translateY(2px); border-bottom-width: 0px; margin-top: calc(1.5rem + 4px); }
        .beautiful-download-btn:disabled { background: var(--text-tertiary); cursor: not-allowed; border-bottom-color: #999; }
        .beautiful-download-btn svg { width: 24px; height: 24px; fill: currentColor; }
        #clear-history-btn { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; max-width: 300px; margin: 1rem auto 0 auto; padding: 12px; background-color: #fff; border: 2px dashed #cbd5e0; color: #718096; font-family: var(--app-font); font-size: 0.95em; font-weight: 700; border-radius: 12px; cursor: pointer; transition: all 0.3s ease; }
        #clear-history-btn:hover { border-color: #fc8181; color: #e53e3e; background-color: #fff5f5; transform: translateY(-2px); }
        #clear-history-btn svg { width: 18px; height: 18px; fill: currentColor; }
        
        /* --- FIX STARTS HERE --- */
        #char-limit-modal .modal-dialog { text-align: center; max-width: 450px; overflow: hidden; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(15px); }
        /* --- FIX ENDS HERE --- */
        
        .premium-icon-wrapper { width: 100px; height: 100px; background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary)); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 1.5rem; box-shadow: 0 10px 30px rgba(74, 108, 250, 0.3); animation: pulse-glow 2s infinite; } 
        .premium-icon-wrapper svg { width: 50px; height: 50px; fill: white; animation: shake 3s infinite ease-in-out; } 
        .premium-title { font-size: 1.6em; font-weight: 900; margin-bottom: 0.5rem; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } 
        .premium-desc { color: var(--text-secondary); font-size: 1.05em; margin-bottom: 2rem; line-height: 1.6; padding: 0 1rem; } 
        .premium-action-btn { width: 100%; padding: 1rem; font-size: 1.1em; font-weight: 800; color: #fff; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); border: none; border-radius: var(--radius-btn); cursor: pointer; transition: all 0.3s; box-shadow: 0 5px 15px rgba(74, 108, 250, 0.3); margin-bottom: 0.8rem; } 
        .premium-action-btn:hover { transform: translateY(-3px); box-shadow: 0 8px 25px rgba(74, 108, 250, 0.4); } 
        .premium-close-link { font-size: 0.9em; color: var(--text-tertiary); text-decoration: none; font-weight: 500; cursor: pointer; } 
        .premium-close-link:hover { color: var(--text-secondary); } 
        #long-text-modal .modal-dialog { max-width: 600px; background: linear-gradient(160deg, #ffffff 0%, #f7f9fc 100%); border: 1px solid #e1e7ef; padding: 3rem 2.5rem; max-height: 90vh; overflow-y: auto; } 
        #long-text-modal .modal-header { border: none; justify-content: center; flex-direction: column; text-align: center; margin-bottom: 1.5rem; } 
        #long-text-modal h2 { font-size: 1.8rem; background: linear-gradient(90deg, #4A6CFA, #0FD4A8); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 0.5rem; } 
        #long-text-modal .header-icon { font-size: 3.5rem; margin-bottom: 1rem; animation: bounce 2s infinite; } 
        #long-text-modal p.desc { color: var(--text-secondary); font-size: 1rem; line-height: 1.8; margin-bottom: 1.5rem; text-align: center; } 
        .long-text-options { display: grid; grid-template-columns: 1fr; gap: 12px; } 
        .option-card { display: flex; align-items: center; background: #fff; border: 2px solid #e2e8f0; border-radius: 16px; padding: 12px; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); position: relative; overflow: hidden; gap: 12px; } 
        .option-card:hover { border-color: var(--accent-primary); transform: translateY(-3px); box-shadow: 0 8px 16px rgba(74, 108, 250, 0.1); } 
        .option-card:hover .option-icon { background: var(--accent-primary); color: #fff; transform: scale(1.1) rotate(-5deg); } 
        .option-icon { width: 45px; height: 45px; background: #edf2f7; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.4rem; color: var(--text-secondary); transition: all 0.3s ease; flex-shrink: 0; } 
        .option-content { flex-grow: 1; text-align: right; } 
        .option-title { font-weight: 800; font-size: 1rem; color: var(--text-primary); margin-bottom: 2px; } 
        .option-subtitle { font-size: 0.85rem; color: var(--text-secondary); line-height: 1.4; } 
        .option-arrow { color: var(--text-tertiary); transition: transform 0.3s ease; font-size: 1.2rem; } 
        .option-card:hover .option-arrow { color: var(--accent-primary); transform: translateX(-5px); } 
        .special-ai-card { background: linear-gradient(135deg, #f3f4f6 0%, #ffffff 100%); border-color: #d1d5db; box-shadow: 0 4px 6px rgba(0,0,0,0.05); } 
        .special-ai-card:hover { border-color: #8b5cf6; background: linear-gradient(135deg, #f5f3ff 0%, #ffffff 100%); box-shadow: 0 10px 20px rgba(139, 92, 246, 0.15); } 
        .special-ai-card .option-icon { background: #ede9fe; color: #8b5cf6; } 
        .special-ai-card:hover .option-icon { background: #8b5cf6; color: white; } 
        .special-ai-card .option-title { background: linear-gradient(90deg, #7c3aed, #4f46e5); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } 
        .coming-soon-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.9); backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; flex-direction: column; opacity: 0; pointer-events: none; transition: opacity 0.3s ease; z-index: 10; border-radius: 14px; } 
        .option-card.show-coming-soon .coming-soon-overlay { opacity: 1; pointer-events: auto; } 
        .coming-soon-text { font-weight: 800; font-size: 1.1rem; color: #7c3aed; margin-bottom: 5px; animation: pulse 1.5s infinite; } 
        .coming-soon-sub { font-size: 0.8rem; color: #6b7280; } 
        .sample-player-container { position: absolute; top: 50%; left: 4px; transform: translateY(-50%); display: flex; flex-direction: column; gap: 5px; z-index: 2; } 
        .sample-play-btn { width: 28px; height: 28px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 0; transition: var(--transition-smooth); background: linear-gradient(145deg, rgba(255, 255, 255, 0.25), rgba(0, 0, 0, 0.25)); border: 1px solid rgba(255, 255, 255, 0.15); border-top-color: rgba(255, 255, 255, 0.3); box-shadow: 0 3px 6px rgba(0, 0, 0, 0.4), inset 0 1px 1px rgba(255, 255, 255, 0.2); backdrop-filter: blur(5px); } 
        .sample-play-btn:hover { background: linear-gradient(145deg, rgba(255, 255, 255, 0.35), rgba(0, 0, 0, 0.3)); transform: scale(1.1); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5), inset 0 1px 1px rgba(255, 255, 255, 0.3); } 
        .sample-play-btn .play-icon-svg { width: 13px; height: 13px; fill: #fff; transition: opacity 0.2s ease; } 
        .sample-play-btn .playing-indicator { display: none; width: 12px; height: 10px; justify-content: space-between; align-items: flex-end; } 
        .sample-play-btn .playing-indicator span { width: 2px; height: 100%; background-color: #fff; border-radius: 1px; animation: sound-wave 1.2s ease-in-out infinite; } 
        .sample-play-btn .playing-indicator span:nth-child(2) { animation-delay: 0.2s; } 
        .sample-play-btn .playing-indicator span:nth-child(3) { animation-delay: 0.4s; } 
        .sample-play-btn.playing { background: var(--accent-secondary); border-color: rgba(255, 255, 255, 0.5); box-shadow: 0 0 12px var(--accent-secondary-glow), 0 0 8px var(--accent-secondary), inset 0 1px 1px rgba(255, 255, 255, 0.4); } 
        .sample-play-btn.playing .play-icon-svg { display: none; } 
        .sample-play-btn.playing .playing-indicator { display: flex; }
        #sample-text-display { position: fixed; bottom: 25px; left: 50%; width: 90%; max-width: 600px; background: rgba(255, 255, 255, 0.85); backdrop-filter: blur(16px) saturate(180%); border: 1px solid rgba(255, 255, 255, 0.6); border-radius: 20px; padding: 20px 24px; box-shadow: 0 20px 40px -10px rgba(0, 0, 0, 0.15); z-index: 2000; text-align: right; direction: rtl; display: flex; flex-direction: column; align-items: flex-start; opacity: 0; visibility: hidden; transform: translateX(-50%) translateY(30px) scale(0.95); transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1); } 
        #sample-text-display.active { opacity: 1; visibility: visible; transform: translateX(-50%) translateY(0) scale(1); } 
        #sample-text-display h4 { margin: 0 0 10px; color: var(--accent-primary); font-size: 0.8em; font-weight: 800; letter-spacing: 0.5px; display: flex; align-items: center; gap: 8px; text-transform: uppercase; } 
        #sample-text-display p { margin: 0; color: var(--text-primary); font-weight: 500; font-size: 0.9em; line-height: 1.7; }
        .confirm-modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(18, 24, 38, 0.6); backdrop-filter: blur(8px); display: flex; align-items: center; justify-content: center; z-index: 1001; opacity: 0; pointer-events: none; transition: opacity 0.3s ease; }
        .confirm-modal-overlay.visible { opacity: 1; pointer-events: auto; }
        .confirm-modal-dialog { background: var(--panel-bg); padding: 2.5rem; border-radius: var(--radius-card); width: 90%; max-width: 450px; box-shadow: var(--shadow-xl); border: 1px solid var(--panel-border); text-align: center; transform: scale(0.95); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        .confirm-modal-overlay.visible .confirm-modal-dialog { transform: scale(1); }
        .confirm-modal-dialog h3 { font-size: 1.5em; font-weight: 800; margin: 0 0 1rem 0; color: var(--text-primary); }
        .confirm-modal-dialog p { color: var(--text-secondary); margin: 0 0 2rem 0; line-height: 1.7; }
        .confirm-modal-actions { display: flex; gap: 1rem; justify-content: center; }
        .confirm-btn, .cancel-btn { font-family: var(--app-font); font-size: 1em; font-weight: 700; padding: 0.8rem 1.5rem; border-radius: var(--radius-btn); border: none; cursor: pointer; transition: all 0.2s ease; flex-grow: 1; }
        .confirm-btn { background-color: #e53e3e; color: white; box-shadow: 0 4px 10px -2px rgba(229, 62, 62, 0.4); }
        .confirm-btn:hover { background-color: #c53030; transform: translateY(-2px); box-shadow: 0 6px 14px -3px rgba(229, 62, 62, 0.5); }
        .cancel-btn { background-color: var(--input-bg); color: var(--text-primary); border: 1px solid var(--input-border); }
        .cancel-btn:hover { background-color: var(--panel-border); }

/* ==========================================
   PART 5: CSS PODCAST STUDIO & MEDIA QUERIES
   استایل‌های استودیوی پادکست و واکنش‌گرایی
   ========================================== */
        .podcast-studio-container { width: 100%; animation: fadeIn 0.5s ease-out; }
        .podcast-studio-container .form-group-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.2rem; }
        .podcast-studio-container #project-speakers-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 1.5rem; text-align: center; }
        .podcast-studio-container .speaker-display-card { position: relative; background-color: var(--input-bg); border-radius: var(--radius-card); padding: 1.5rem 1rem; border: 2px solid var(--input-border); transition: var(--transition-smooth); text-align: center; }
        .podcast-studio-container .speaker-display-card:hover:not(#add-speaker-card) { border-color: var(--accent-primary); transform: translateY(-5px); box-shadow: var(--shadow-md); }
        .podcast-studio-container .speaker-display-card img { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; margin: 0 auto 1rem auto; display: block; border: 4px solid var(--panel-bg); box-shadow: var(--shadow-md); }
        .podcast-studio-container .speaker-display-card h3 { margin: 0 0 0.25rem 0; font-size: 1.1em; font-weight: 800; }
        .podcast-studio-container .remove-speaker-btn { position: absolute; top: 12px; left: 12px; background: rgba(255, 255, 255, 0.7); backdrop-filter: blur(4px); border: 1px solid var(--panel-border); color: var(--text-secondary); width: 28px; height: 28px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; line-height: 1; transition: all 0.2s; z-index: 5; }
        .podcast-studio-container .remove-speaker-btn:hover { color: #e53e3e; transform: scale(1.1); background: #fff; }
        .podcast-studio-container #add-speaker-card { display: flex; flex-direction: column; align-items: center; justify-content: center; font-weight: 700; color: var(--accent-primary); border: 2px dashed var(--input-border); cursor: pointer; background-color: transparent; }
        .podcast-studio-container #add-speaker-card:hover { border-color: var(--accent-primary); background: var(--accent-primary-glow); }
        .podcast-studio-container #add-speaker-card .plus-icon { font-size: 2.5rem; line-height: 1; margin-bottom: 0.5rem; }
        .podcast-studio-container #podcast-script-container { border: 1px solid var(--input-border); border-radius: var(--radius-card); padding: 1rem; background-color: var(--input-bg); box-shadow: inset 0 2px 4px rgba(0,0,0,0.02); }
        .podcast-studio-container .script-turn { display: flex; gap: 1rem; margin-bottom: 1.5rem; background-color: var(--panel-bg); padding: 1rem; border-radius: var(--radius-input); border: 1px solid var(--panel-border); box-shadow: var(--shadow-md); }
        .podcast-studio-container .script-turn:last-child { margin-bottom: 0; }
        .podcast-studio-container .turn-speaker-selector { flex-shrink: 0; width: 180px; position: relative; }
        .podcast-studio-container .turn-content { flex-grow: 1; }
        .podcast-studio-container .turn-content textarea { width: 100%; min-height: 80px; resize: vertical; padding: 0.8rem 1rem; border-radius: var(--radius-input); border: 1px solid var(--input-border); background-color: #fff; font-family: var(--app-font); font-size: 1rem; box-sizing: border-box; }
        .podcast-studio-container .turn-content textarea:focus { outline: none; border-color: var(--accent-primary); box-shadow: 0 0 0 3px var(--accent-primary-glow); }
        .podcast-studio-container .remove-turn-btn { flex-shrink: 0; background: none; border: none; color: var(--text-tertiary); font-size: 1.5rem; cursor: pointer; align-self: center; transition: all 0.2s; }
        .podcast-studio-container .remove-turn-btn:hover { color: #e53e3e; transform: scale(1.1); }
        .podcast-studio-container #add-turn-btn { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; padding: 1rem; font-size: 1em; font-weight: 700; background: transparent; color: var(--text-primary); border: 2px dashed var(--input-border); border-radius: var(--radius-btn); cursor: pointer; margin-top: 1.5rem; transition: var(--transition-smooth); }
        .podcast-studio-container #add-turn-btn:hover { background: var(--panel-bg); border-color: var(--accent-primary); color: var(--accent-primary); }
        .podcast-studio-container .custom-select-trigger { display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem; border-radius: var(--radius-input); border: 1px solid var(--input-border); background-color: #fff; cursor: pointer; transition: var(--transition-smooth); height: 100%; box-sizing: border-box; }
        .podcast-studio-container .custom-select-trigger:hover { border-color: var(--accent-primary); }
        .podcast-studio-container .custom-select-trigger img { width: 40px; height: 40px; border-radius: 10px; object-fit: cover; }
        .podcast-studio-container .custom-select-trigger span { font-weight: 600; flex-grow: 1; }
        .podcast-studio-container .custom-select-trigger .arrow { margin-right: auto; width: 20px; height: 20px; color: var(--text-tertiary); transition: transform 0.2s; }
        .podcast-studio-container .custom-select-container.open .arrow { transform: rotate(180deg); }
        .podcast-studio-container .custom-select-options { position: absolute; top: calc(100% + 8px); left: 0; width: 100%; background: var(--panel-bg); border-radius: var(--radius-input); border: 1px solid var(--panel-border); box-shadow: var(--shadow-lg); z-index: 10; max-height: 250px; overflow-y: auto; opacity: 0; transform: translateY(10px); pointer-events: none; transition: all 0.25s ease-out; }
        .podcast-studio-container .custom-select-container.open .custom-select-options { opacity: 1; transform: translateY(0); pointer-events: auto; }
        .podcast-studio-container .custom-select-option { display: flex; align-items: center; gap: 0.75rem; padding: 0.75rem; cursor: pointer; }
        .podcast-studio-container .custom-select-option:hover { background-color: var(--input-bg); }
        .podcast-studio-container .custom-select-option img { width: 40px; height: 40px; border-radius: 10px; object-fit: cover; }
        .podcast-studio-container .custom-select-option span { font-weight: 500; }
        .podcast-studio-container #generation-progress-container { width: 100%; max-width: 500px; margin-top: 1rem; }
        .podcast-studio-container .progress-grid { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-top: 10px; }
        .podcast-studio-container .progress-item { width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border-radius: 8px; background-color: #EDF2F7; border: 1px solid #E2E8F0; font-size: 0.8em; font-weight: 700; color: #718096; transition: all 0.3s ease; }
        .podcast-studio-container .progress-item.pending { background-color: #EDF2F7; animation: pulse-gray 1.5s infinite; }
        .podcast-studio-container .progress-item.done { background-color: var(--accent-secondary); color: white; border-color: var(--accent-secondary); transform: scale(1.1); box-shadow: 0 2px 5px var(--accent-secondary-glow); }
        .podcast-studio-container .progress-item.error { background-color: #FC8181; color: white; border-color: #F56565; transform: scale(1.1); }
        .podcast-studio-container .turn-player-container { display: none; align-items: center; gap: 1rem; padding: 0.75rem; margin-top: 1rem; background-color: var(--input-bg); border-radius: var(--radius-input); border: 1px solid var(--panel-border); position: relative; }
        .podcast-studio-container .turn-player-container.visible { display: flex; }
        .podcast-studio-container .turn-play-btn { background: var(--accent-primary); color: white; border: none; width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: var(--transition-smooth); flex-shrink: 0; }
        .podcast-studio-container .turn-play-btn:hover { background: var(--accent-primary-hover); transform: scale(1.1); }
        .podcast-studio-container .turn-play-btn svg { width: 20px; height: 20px; fill: currentColor; }
        .podcast-studio-container .turn-play-btn .pause-icon { display: none; }
        .podcast-studio-container .turn-player-container.playing .turn-play-btn .play-icon { display: none; }
        .podcast-studio-container .turn-player-container.playing .turn-play-btn .pause-icon { display: block; }
        .podcast-studio-container .loading-state-wrapper { display: flex; align-items: center; gap: 6px; margin-right: auto; }
        .podcast-studio-container .loading-state-wrapper .spinner { width: 18px; height: 18px; border: 2px solid var(--text-tertiary); border-top-color: var(--accent-primary); border-radius: 50%; animation: spin 0.8s linear infinite; display: inline-block; }
        .podcast-studio-container .loading-state-wrapper .loading-text { font-size: 0.85em; font-weight: 600; color: var(--accent-primary); white-space: nowrap; transition: all 0.3s; }
        .podcast-studio-container .turn-retry-btn { font-family: var(--app-font); font-size: 0.85em; font-weight: 600; background: none; border: 1px solid var(--input-border); color: var(--text-secondary); padding: 0.4rem 0.8rem; border-radius: var(--radius-btn); cursor: pointer; transition: var(--transition-smooth); margin-right: auto; display: flex; align-items: center; gap: 6px; }
        .podcast-studio-container .turn-retry-btn:hover { border-color: var(--accent-secondary); color: var(--accent-secondary); background: var(--accent-secondary-glow); }
        .podcast-studio-container .turn-retry-btn svg { width: 16px; height: 16px; fill: currentColor; }
        .podcast-studio-container .replace-success-message, .podcast-studio-container .main-update-message { font-family: var(--app-font); font-size: 0.85em; font-weight: 600; padding: 0.4rem 0.8rem; border-radius: var(--radius-btn); white-space: nowrap; display: none; align-items: center; justify-content: center; margin-right: auto; }
        .podcast-studio-container .replace-success-message { background-color: var(--accent-secondary-glow); color: var(--accent-secondary); }
        .podcast-studio-container .main-update-message { background: linear-gradient(90deg, #e6fffa, #b2f5ea); color: #2c7a7b; border: 1px solid #81e6d9; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }

        @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); width: auto; } 
            #selected-speaker-card img { margin-left: 0; margin-bottom: 1rem; } 
            #speaker-grid { grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); }
        }
        @media (max-width: 768px) { 
            .podcast-studio-container .script-turn { flex-direction: column; } 
            .podcast-studio-container .remove-turn-btn { align-self: flex-end; margin-top: -1.5rem; margin-right: -0.5rem; } 
            .podcast-studio-container .turn-speaker-selector { width: 100%; } 
        }
    </style>
</head>

<!-- ==========================================
     PART 6: HTML MAIN STRUCTURE & FORM
     ساختار اصلی HTML، هدر، فرم اصلی و خروجی
     ========================================== -->
<body>
    <div class="app-container">
        <header class="app-header">
            <h1>مولد صدای هوشمند آلفا</h1>
            <p>کیفیت استودیو، قدرت هوش مصنوعی. صدایی فراتر از انتظار خلق کنید.</p>
            <div id="subscription-status-badge-standard" class="subscription-status-badge"></div>
        </header>
        <main class="main-content">
            <div id="standard-tts-form-container">
                <form id="standard-tts-form" onsubmit="return false;">
                    <div class="form-group">
                        <label for="text-input-standard">📝 متن اصلی</label>
                        <textarea id="text-input-standard" rows="5" placeholder="متن خود را برای تبدیل به گفتار اینجا وارد کنید. (پشتیبانی از تمام زبان های دنیا)"></textarea>
                        <div class="char-counter-wrapper"><span id="char-count">0</span> / <span id="char-max">۸۰,۰۰۰</span> نویسه</div>
                    </div>
                    <div class="form-group">
                        <label for="prompt-input-standard">🗣️ توصیف لحن و احساس (اختیاری)</label>
                        <input type="text" id="prompt-input-standard" 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>
                    <p id="credit-status-message"></p>
                    <button type="submit" id="generate-btn-standard" class="generate-btn"><span class="btn-text">✨ خلق صدا با آلفا</span><div class="spinner"></div></button>
                    <button type="button" id="upgrade-premium-btn">⭐️ ارتقا به نسخه کامل و نامحدود</button>
                </form>
            </div>
            <div id="output-section-standard" class="output-section">
                <div id="status-message-standard" class="status-message">صدای تولید شده در اینجا ظاهر خواهد شد.</div>
            </div>
        </main>
        
        <audio id="hidden-audio-player" style="display: none;"></audio>
        <audio id="sample-audio-player" style="display: none;"></audio>
    </div>
    
    <div id="sample-text-display">
        <h4>متن تبدیل شده⬇️</h4>
        <p id="sample-text-content">...</p>
    </div>

<!-- ==========================================
     PART 7: HTML MODALS & HIDDEN INPUTS
     کد HTML مربوط به پنجره‌های پاپ‌آپ و ورودی‌های مخفی
     ========================================== -->
    <div id="speaker-modal" class="modal-overlay">
        <div class="modal-dialog">
            <div class="modal-header"><h2>گالری گویندگان آلفا</h2><button type="button" class="close-modal-btn">×</button></div>
            <div class="modal-body">
                <div id="speaker-grid"></div>
            </div>
        </div>
    </div>
    
    <div id="char-limit-modal" class="modal-overlay">
        <div class="modal-dialog">
            <div class="premium-icon-wrapper">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20M8,12V14H10V12H8M8,16V18H10V16H8M12,12V14H16V12H12M12,16V18H16V16H12Z" /></svg>
            </div>
            <h2 class="premium-title">محدودیت تعداد کاراکتر</h2>
            <p class="premium-desc">کاربر گرامی، در نسخه رایگان شما تنها مجاز به تبدیل متن‌های کوتاه (زیر ۵۰۰ کاراکتر) هستید. متن شما طولانی‌تر از حد مجاز است. با ارتقاء به نسخه کامل همه بخش های برنامه برای شما در دسترس خواهد بود و امکان تبدیل متن به صدا همزمان تا ۸۰ هزار کاراکتر امکان پذیر است.</p>
            <button class="premium-action-btn" id="char-limit-upgrade-btn">ارتقا به نسخه نامحدود</button>
            <div class="premium-close-link" id="char-limit-close-link">متوجه شدم، متن را کوتاه می‌کنم</div>
        </div>
    </div>

    <div id="long-text-modal" class="modal-overlay">
        <div class="modal-dialog">
            <div class="modal-header">
                <div class="header-icon">📜</div>
                <h2>متن شما طولانی است</h2>
            </div>
            <p class="desc">متن شما بیشتر از 500 نویسه است. متن های بیشتر از 500 نویسه در چند مرحله ساخته می‌شود و نیاز به پردازش پیشرفته دارد. بهترین حالت برای متن های طولانی انتخاب دو گوینده(خانم/آقا) می‌باشد تا برای شنونده نیز جذاب باشد. لطفاً نحوه تبدیل را انتخاب کنید.</p>
            <div class="long-text-options">
                <div class="option-card" data-mode="single">
                    <div class="option-icon">👤</div>
                    <div class="option-content"><div class="option-title">با یک گوینده</div><div class="option-subtitle">متن به صورت یکپارچه با گوینده انتخابی شما خوانده می‌شود.</div></div>
                    <div class="option-arrow"></div>
                </div>
                <div class="option-card" data-mode="double">
                    <div class="option-icon">👥</div>
                    <div class="option-content"><div class="option-title">با دو گوینده</div><div class="option-subtitle">متن به صورت هوشمند بین دو گوینده تصادفی تقسیم می‌شود.</div></div>
                    <div class="option-arrow"></div>
                </div>
                <div class="option-card" data-mode="multi">
                    <div class="option-icon">🎭</div>
                    <div class="option-content"><div class="option-title">با چندین گوینده</div><div class="option-subtitle">هوش مصنوعی متن را تحلیل کرده و با چندین گوینده تصادفی اجرا می‌کند.</div></div>
                    <div class="option-arrow"></div>
                </div>
                <div class="option-card special-ai-card" data-mode="ai-podcast">
                    <div class="option-icon">🎙️</div>
                    <div class="option-content"><div class="option-title">تبدیل متن به پادکست</div><div class="option-subtitle">هوش مصنوعی آلفا متن شمارو به پادکست حرفه ای و سناریو منظم تبدیل میکند</div></div>
                    <div class="option-arrow"></div>
                </div>
            </div>
            <div style="text-align: center; margin-top: 1.5rem;">
                <button type="button" class="close-modal-btn" style="font-size: 1rem; color: var(--text-tertiary); border: 1px solid var(--input-border); padding: 0.5rem 1rem; border-radius: 8px;">انصراف</button>
            </div>
        </div>
    </div>
    
    <div id="confirm-delete-modal" class="confirm-modal-overlay">
        <div class="confirm-modal-dialog">
            <h3>تایید عملیات</h3>
            <p>آیا از حذف کامل سابقه گفتگو و بازنشانی پروژه به حالت اولیه مطمئن هستید؟ این عمل غیرقابل بازگشت است.</p>
            <div class="confirm-modal-actions">
                <button id="cancel-delete-btn" class="cancel-btn">انصراف</button>
                <button id="confirm-delete-action-btn" class="confirm-btn">بله، حذف کن</button>
            </div>
        </div>
    </div>

    <input type="hidden" id="selected_speaker_id_storage" value="Charon">

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        // ==========================================
        // PART 8: JS INDEXEDDB & STATE MANAGEMENT
        // مدیریت پایگاه داده داخلی و متغیرهای وضعیت
        // ==========================================
        let db;
        const DB_NAME = 'AlphaTTS_ProjectDB';
        const DB_VERSION = 1;

        function initDB() {
            return new Promise((resolve, reject) => {
                const request = indexedDB.open(DB_NAME, DB_VERSION);
                request.onupgradeneeded = (e) => {
                    db = e.target.result;
                    if (!db.objectStoreNames.contains('project')) {
                        db.createObjectStore('project');
                    }
                    if (!db.objectStoreNames.contains('audioSegments')) {
                        db.createObjectStore('audioSegments');
                    }
                };
                request.onsuccess = (e) => { db = e.target.result; resolve(db); };
                request.onerror = (e) => reject(e);
            });
        }

        function saveProjectState(data) {
            if(!db) return;
            const tx = db.transaction('project', 'readwrite');
            const store = tx.objectStore('project');
            store.put(data, 'currentState');
        }
        
        async function saveAudioSegment(index, blob) {
             if (!db) return;
             return new Promise((resolve, reject) => {
                const tx = db.transaction('audioSegments', 'readwrite');
                const store = tx.objectStore('audioSegments');
                const request = blob ? store.put(blob, index) : store.delete(index);
                tx.oncomplete = () => resolve();
                tx.onerror = () => reject(tx.error);
             });
        }

        function loadProjectState() {
             return new Promise((resolve, reject) => {
                if (!db) return resolve(null);
                const tx = db.transaction(['project', 'audioSegments'], 'readonly');
                const pStore = tx.objectStore('project');
                const aStore = tx.objectStore('audioSegments');

                const stateReq = pStore.get('currentState');
                const audioKeysReq = aStore.getAllKeys();
                const audioValuesReq = aStore.getAll();

                Promise.all([
                    new Promise(res => stateReq.onsuccess = () => res(stateReq.result)),
                    new Promise(res => audioKeysReq.onsuccess = () => res(audioKeysReq.result)),
                    new Promise(res => audioValuesReq.onsuccess = () => res(audioValuesReq.result))
                ]).then(([state, audioKeys, audioValues]) => {
                    const audioData = [];
                    if (audioKeys && audioValues) {
                        audioKeys.forEach((key, i) => {
                            audioData[key] = audioValues[i];
                        });
                    }
                    resolve({ state, audioData });
                }).catch(reject);
            });
        }
        
        async function clearProjectState() {
            localStorage.removeItem('alphaTtsMainText');
            localStorage.removeItem('alphaTtsMainSpeaker');

            return new Promise((resolve, reject) => {
                if(!db) return resolve();
                const tx = db.transaction(['project', 'audioSegments'], 'readwrite');
                tx.objectStore('project').clear();
                tx.objectStore('audioSegments').clear();
                tx.oncomplete = () => resolve();
                tx.onerror = () => reject(tx.error);
            });
        }
        
        async function clearPodcastDB() {
            return new Promise((resolve, reject) => {
                if(!db) return resolve();
                const tx = db.transaction(['project', 'audioSegments'], 'readwrite');
                tx.objectStore('project').clear();
                tx.objectStore('audioSegments').clear();
                tx.oncomplete = () => resolve();
                tx.onerror = () => reject(tx.error);
            });
        }

        let userSubscriptionStatus = 'free'; 
        let userFingerprint = null;
        let currentPodcastMode = null;
        const PREMIUM_PAGE_ID = '1149636'; 
        const PREMIUM_URL = '#/nav/online/news/getSingle/1149636/eyJpdiI6InZSVUdlLzBlR0FzOHZJdXFZeWhER0E9PSIsInZhbHVlIjoiWFhqRXBLc29vSFpHdk9nYmRjZGVuWHRHRHVSZHRlTG1BUENLaE5mNXBNVVRGWFg3ZWN0djJ5K1dIY1RqTHJGaCIsIm1hYyI6IjIzYzFlZTMwYmVmMTdkYjQ0YTQ4YWMxNmFhN2RmNWQ2OTc1NDIyNGVlZGI3ZjJjMjhkNmQxNjM4MDFlZTIxNmUiLCJ0YWciOiIifQ==/20934991';
        const LONG_TEXT_THRESHOLD = 500;
        const PODCAST_API_BASE = 'https://ezmarynoori-podgen.hf.space';
        
        // ==========================================
        // PART 9: JS SPEAKERS DATA
        // لیست کامل گویندگان و اطلاعات آنها
        // ==========================================
        const allSpeakers = [
            { id: "Charon", name: "شهاب (مرد)", gender: "male", desc: "صدایی قدرمند و رسا", imgUrl: "https://uploadkon.ir/uploads/a18705_25IMG-۲۰۲۵۰۷۰۵-۱۱۰۵۴۹.jpg", samples: ["https://uploadkon.ir/uploads/c17c06_26شهاب-یک-2-.mp3", "https://uploadkon.ir/uploads/af0d06_26شهاب-دو-2-.mp3", "https://uploadkon.ir/uploads/9e2806_26شهاب-سه-2-.mp3", "https://uploadkon.ir/uploads/35bd06_26شهاب-چهار-2-.mp3"], sampleTexts: ["", "", "هاهاها ﺗﺒﺪﯾﻞ  متن (خنده زیاد) شما ﺑﻪ ﺻﺪﺍﯾﯽ ﮐﻪ ﻫﻤﺪﻟﯽ ﻭ ﺩﺭﮎ ﺭﺍ ﺑﺮﻣﯽ‌ﺍﻧﮕﯿﺰﺩ.(خنده)", "ﺗﺒﺪﯾﻞ ﻣﺘﻦ ﺷﻤﺎﺑﻪ ﺻﺪﺍﯾﯽ ﮐﻪ ﻫﻤﺪﻟﯽ ﻭ ﺩﺭﮎ ﺭﺍ ﺑﺮﻣﯽ‌ﺍﻧﮕﯿﺰﺩ.(متن با صدای ترس و لرز بخون)"] },
            { id: "Zephyr", name: "آوا (زن)", gender: "female", desc: "لطیف و دلنشین", imgUrl: "https://uploadkon.ir/uploads/029605_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۲۵۲.jpg", samples: ["https://uploadkon.ir/uploads/920e06_26آوا-یک-2-.mp3", "https://uploadkon.ir/uploads/f50c06_26آوا-دو-2-.mp3", "https://uploadkon.ir/uploads/bc8e06_26آوا-سه-2-.mp3", "https://uploadkon.ir/uploads/1b2e06_26آوا-چهار-2-.mp3"], sampleTexts: ["", "", "هاهاها ﺗﺒﺪﯾﻞ ﻣﺘﻦ ﺷﻤﺎ(خنده زیاد) ﺑﻪ ﺻﺪﺍﯾﯽ ﮐﻪ ﻫﻤﺪﻟﯽ ﻭ ﺩﺭﮎ ﺭﺍ ﺑﺮﻣﯽ‌ﺍﻧﮕﯿﺰﺩ.(خنده)", "وای ﺗﺒﺪﯾﻞ ﻣﺘﻦ ﺷﻤﺎﺑﻪ ﺻﺪﺍﯾﯽ ﮐﻪ ﻫﻤﺪﻟﯽ ﻭ ﺩﺭﮎ ﺭﺍ ﺑﺮﻣﯽ‌ﺍﻧﮕﯿﺰﺩ.(با تعجب و هیجان زیاد)"] },
            { id: "Achird", name: "نوید (مرد)", gender: "male", desc: "جوان و پرانرژی", imgUrl: "https://uploadkon.ir/uploads/697e05_25IMG-۲۰۲۵۰۶۰۹-۰۶۴۶۳۷.jpg", samples: ["https://uploadkon.ir/uploads/f8b206_26نوید-یک-2-.mp3", "https://uploadkon.ir/uploads/9c0d06_26نوید-دو-2-.mp3", "https://uploadkon.ir/uploads/26f006_26نوید-سه-2-.mp3", "https://uploadkon.ir/uploads/5e0306_26نوید-چهار-2-.mp3"], sampleTexts: ["", "", "", "ﻫﺮ ﮐﻠﻤﻪ ﺍﺯ ﻧﻮﺷﺘﻪ‌ﻫﺎﯾﺘﺎﻥ، ﺑﺎ ﺁﺭﺍﻣﺸﯽ ﻋﻤﯿﻖ ﺩﺭ ﻗﺎﻟﺐ ﺻﺪﺍ ﺟﺎﺭﯼ ﻣﯽ‌ﺷﻮﺩ.(ﺁﺭﺍﻣﺶ‌ﺑﺨﺶ ﻭ ﺗﺴﮑﯿﻦ‌ﺩﻫﻨﺪﻩ)"] },
            { id: "Zubenelgenubi", name: "آرمان (مرد)", gender: "male", desc: "گرم و صمیمی", imgUrl: "https://uploadkon.ir/uploads/a8a705_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۶۲۹.jpg", samples: ["https://uploadkon.ir/uploads/bf9406_26آرمان-یک-2-.mp3", "https://uploadkon.ir/uploads/edaf06_26آرمان-دو-2-.mp3", "https://uploadkon.ir/uploads/2e7a06_26آرمان-سه-2-.mp3", "https://uploadkon.ir/uploads/456306_26آرمان-چهار-2-.mp3"], sampleTexts: ["", "دستورات را به وضوح و بدون هیچ ابهامی صادر کنید.(با لحنی قاطع، محکم و فرماندهانه، شبیه به یک افسر ارتش که دستور عملیات می‌دهد) 🎖️", "آخرین اخبار و تحولات مهم را با دقت و بی‌طرفی کامل به اطلاع عموم برسانید. (با لحنی رسمی، خنثی و خبری، همانند یک مجری خبر حرفه‌ای در بخش خبری شبانگاهی)", "این غیرقابل تحمل است! دیگر نمی‌توانم این وضعیت را تحمل کنم! (با صدای بلند، خشمگین و همراه با فریاد، مناسب برای دیالوگ یک شخصیت در اوج عصبانیت در یک صحنه دراماتیک فیلم)"] },
            { id: "Vindemiatrix", name: "مهسا (زن)", gender: "female", desc: "باوقار و رسمی", imgUrl: "https://uploadkon.ir/uploads/d74d05_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۸۳۸.jpg", samples: ["https://uploadkon.ir/uploads/749806_26مهسا-یک-2-.mp3", "https://uploadkon.ir/uploads/15c706_26مهسا-دو-2-.mp3", "https://uploadkon.ir/uploads/fc2406_26مهسا-سه-2-.mp3", "https://uploadkon.ir/uploads/978506_26مهسا-چهار-2-.mp3"], sampleTexts: ["", "به سرعت و با دقت، تمامی جزئیات را برای شروع ماموریت نهایی بررسی کنید. (با لحنی هیجان‌زده و کمی اضطراب‌آور، شبیه به یک عامل مخفی که دستورات فوری دریافت می‌کند)", "و در پایان، با آرزوی بهترین‌ها برای شما، این برنامه به اتمام می‌رسد. (با لحنی آرام، ملایم و دلنشین، مانند یک گوینده کتاب صوتی در پایان یک داستان آرامش‌بخش) 📚", "وای خدای من! باورم نمیشه این اتفاق افتاد! نه، این امکان نداره! (با صدایی مملو از تعجب و ناباوری شدید، همراه با کمی ترس یا شوک، مناسب برای یک صحنه غیرمنتظره در فیلم) 😲"] },
            { id: "Rasalgethi", name: "دانا (مرد)", gender: "male", desc: "خبری و آموزنده", imgUrl: "https://uploadkon.ir/uploads/57e425_25IMG-20250925-112825-749.jpg", samples: ["https://uploadkon.ir/uploads/2a0a06_26دانا-یک-2-.mp3", "https://uploadkon.ir/uploads/6daa06_26دانا-دو-2-.mp3", "https://uploadkon.ir/uploads/fb3a06_26دانا-سه-2-.mp3", "https://uploadkon.ir/uploads/5b0c06_26دانا-چهار-2-.mp3"], sampleTexts: ["", "به یاد داشته باشید، هر قدمی که برمی‌داریم، ما را به هدف نزدیک‌تر می‌کند. مصمم باشید! (با لحنی انگیزشی و الهام‌بخش، شبیه به یک مربی زندگی که به شاگردانش روحیه می‌دهد) 🚀", "در این شب مهتابی، داستان‌های کهن از دل تاریخ سر برمی‌آورند و خاطرات را زنده می‌کنند.  (با لحنی مرموز و کمی وهم‌آلود، مناسب برای روایت یک داستان شبح‌وار یا افسانه قدیمی)", "من به شما هشدار داده بودم! اما شما گوش نکردید! حالا همه چیز از دست رفته است!  (با صدایی پر از یاس و ناامیدی، همراه با حس سرزنش و پشیمانی شدید، مناسب برای دیالوگ یک شخصیت در یک موقعیت بحرانی) "] },
            { id: "Sadachbia", name: "سامان (مرد)", gender: "male", desc: "شاداب و پویا", imgUrl: "https://uploadkon.ir/uploads/580205_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۳۳۰.jpg", samples: ["https://uploadkon.ir/uploads/2f4b06_26سامان-یک-2-.mp3", "https://uploadkon.ir/uploads/bbc806_26سامان-دو-2-.mp3", "https://uploadkon.ir/uploads/0a9906_26سامان-سه-2-.mp3", "https://uploadkon.ir/uploads/c94b06_26سامان-چهار-2-.mp3"], sampleTexts: ["", "تو باید قوی باشی! هیچ چیز نمی‌تواند تو را از رسیدن به هدفت باز دارد! (با لحنی حماسی، قهرمانانه و بسیار تشویق‌کننده، شبیه به یک رهبر که در لحظه نبرد به سربازانش روحیه می‌دهد) ⚔️", "و حالا، لحظاتی را با موسیقی کلاسیک و آرامش‌بخش، در کنار ما سپری کنید. (با لحنی بسیار ملایم، آرام و موزون، شبیه به گوینده یک برنامه رادیویی آرامش‌بخش شبانه) 🎶", "وای! این چه بویی بود؟! حالم داره بد میشه!  (با صدایی که نشان‌دهنده انزجار شدید، تهوع و چندش است، مناسب برای واکنش به یک بوی بسیار بد یا منظره‌ای ناخوشایند)"] },
            { id: "Sadaltager", name: "آرش (مرد)", gender: "male", desc: "مطمئن و تاثیرگذار", imgUrl: "https://uploadkon.ir/uploads/c4db05_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۵۰۰.jpg", samples: ["https://uploadkon.ir/uploads/7a9406_26آرش-یک-2-.mp3", "https://uploadkon.ir/uploads/efe806_26آرش-دو-2-.mp3", "https://uploadkon.ir/uploads/278506_26آرش-سه-2-.mp3", "https://uploadkon.ir/uploads/8a7506_26آرش-چهار-2-.mp3"], sampleTexts: ["", "توجه! توجه! خطر نزدیک است! همه به پناهگاه بروید! (با لحنی اضطراری، بلند و هشداردهنده، شبیه به اعلام وضعیت قرمز در یک سیستم هشدار عمومی) 🚨", "و اینگونه بود که هر دو عاشق، در زیر نور ماه، عهد ابدی بستند.  (با لحنی عاشقانه، لطیف و رؤیایی، مناسب برای روایت یک داستان عاشقانه یا شعر احساسی) ", "هاهاها! چه شوخی مسخره‌ای! واقعاً فکر کردی من باور می‌کنم؟ (با صدای خنده تمسخرآمیز و کنایه‌آلود، همراه با حس بی‌اعتقادی و ریشخند) 😂"] },
            { id: "Sulafat", name: "شبنم (زن)", gender: "female", desc: "آرام و متین", imgUrl: "https://uploadkon.ir/uploads/995005_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۶۱۱.jpg", samples: ["https://uploadkon.ir/uploads/014706_26شبنم-یک-2-.mp3", "https://uploadkon.ir/uploads/098c06_26شبنم-دو-2-.mp3", "https://uploadkon.ir/uploads/2c0706_26شبنم-سه-2-.mp3", "https://uploadkon.ir/uploads/66bd06_26شبنم-چهار-2-.mp3"], sampleTexts: ["", "گزارش نهایی را با دقت و جزئیات کامل، برای بررسی فوری ارائه دهید. (با لحنی جدی، رسمی و کمی آمرانه، شبیه به یک بازپرس که از یک مأمور اطلاعات می‌خواهد)", "آه، چه منظره‌ی زیبایی! گویی نقاشی‌ای از بهشت پیش روی من است. (با صدایی مملو از تحسین، شگفتی و ذوق‌زدگی، هنگام دیدن چیزی بسیار زیبا) 😍", "من که به تو گفتم! این کار را نکن! حالا ببین چه بلایی سرمان آمد! (با لحنی پشیمان، سرزنش‌کننده و همراه با حس \"من گفته بودم\"، مناسب برای موقعیتی که پیش‌بینی منفی به حقیقت پیوسته است)"] },
            { id: "Laomedeia", name: "سحر (زن)", gender: "female", desc: "دوستانه و گیرا", imgUrl: "https://uploadkon.ir/uploads/660705_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۷۵۴.jpg", samples: ["https://uploadkon.ir/uploads/836c06_26سحر-یک-2-.mp3", "https://uploadkon.ir/uploads/b0ce06_26سحر-دو-2-.mp3", "https://uploadkon.ir/uploads/e2d306_26سحر-سه-2-.mp3", "https://uploadkon.ir/uploads/1f3306_26سحر-چهار-2-.mp3"], sampleTexts: ["", "تو تنها امید ما هستی! باید این مأموریت را به پایان برسانی، به هر قیمتی! (با لحنی دراماتیک، التماس‌آمیز و پر از امید، شبیه به یک شخصیت که از قهرمان داستان کمک می‌خواهد)", "صبح بخیر ایران! امروز با یک خبر فوق‌العاده دیگر در خدمت شما هستیم. (با لحنی شاد، پرانرژی و صبحگاهی، مانند یک مجری رادیو در ابتدای برنامه) ☀️", "آاااخ! پام گیر کرد! افتادم! خیلی درد می‌کنه! (با صدای جیغ، ناله و درد شدید، مناسب برای واکنش به یک حادثه ناگهانی و آسیب دیدن)"] },
            { id: "Achernar", name: "مریم (زن)", gender: "female", desc: "حرفه‌ای و واضح", imgUrl: "https://uploadkon.ir/uploads/4c2905_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۰۳۶.jpg", samples: ["https://uploadkon.ir/uploads/9bd906_26مریم-یک-2-.mp3", "https://uploadkon.ir/uploads/c15006_26مریم-دو-2-.mp3", "https://uploadkon.ir/uploads/b00106_26مریم-سه-2-.mp3", "https://uploadkon.ir/uploads/8a2806_26مریم-چهار-2-.mp3"], sampleTexts: ["", "", "تمامی واحدها، به موقعیت اعلام‌شده اعزام شوید! تکرار می‌کنم، اعزام شوید! (با لحنی قاطع، محکم و اضطراری، شبیه به فرمانده عملیات در بیسیم) 🚨", "اوه، واقعاً؟ من که اصلاً تعجب نکردم! (با لحنی بی‌تفاوت، طعنه‌آمیز و کمی کنایه‌آلود)"] },
            { id: "Alnilam", name: "بهرام (مرد)", gender: "male", desc: "حماسی و نافذ", imgUrl: "https://uploadkon.ir/uploads/f0c205_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۲۲۰.jpg", samples: ["https://uploadkon.ir/uploads/7f8306_26بهرام-یک-2-.mp3", "https://uploadkon.ir/uploads/35ee06_26بهرام-دو-2-.mp3", "https://uploadkon.ir/uploads/77fd06_26بهرام-سه-2-.mp3", "https://uploadkon.ir/uploads/3e1106_26بهرام-چهار-2-.mp3"], sampleTexts: ["", "", "واقعاً فکر می‌کنی من این داستان رو باور می‌کنم؟ (با لحنی تمسخرآمیز و بی‌باور) 🤨", "هی، گوش کن! یه راز دارم که فقط به تو می‌گم. (با لحنی مرموز، شیطنت‌آمیز و نجواگونه)"] },
            { id: "Schedar", name: "نیکان (مرد)", gender: "male", desc: "مهربان و شیرین", imgUrl: "https://uploadkon.ir/uploads/d37a05_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۳۲۵.jpg", samples: ["https://uploadkon.ir/uploads/390a06_26نیکان-یک-2-.mp3", "https://uploadkon.ir/uploads/0e6d06_26نیکان-دو-2-.mp3", "https://uploadkon.ir/uploads/f72606_26نیکان-سه-2-.mp3", "https://uploadkon.ir/uploads/5cb006_26نیکان-چهار-2-.mp3"], sampleTexts: ["", "", "این دیگر واقعاً شورش را درآورده است! بس کن! (با لحنی خسته، کلافه و عصبی از تکرار یک موضوع) ", "واو! این فوق‌العاده است! هرگز فکر نمی‌کردم چنین چیزی ممکن باشد! (با لحنی سرشار از هیجان، شگفتی و ذوق‌زدگی) 🤩"] },
            { id: "Gacrux", name: "فرناز (زن)", gender: "female", desc: "پخته و قابل اعتماد", imgUrl: "https://uploadkon.ir/uploads/495b09_25IMG-20251109-104135-304.jpg", samples: ["https://uploadkon.ir/uploads/7d4b06_26فرناز-یک-2-.mp3", "https://uploadkon.ir/uploads/df5806_26فرناز-دو-2-.mp3", "https://uploadkon.ir/uploads/023d06_26فرناز-سه-2-.mp3", "https://uploadkon.ir/uploads/328f06_26فرناز-چهار-2-.mp3"], sampleTexts: ["", "", "این دیگر واقعاً غیرقابل قبوله! باید یه کاری بکنیم! (با لحنی معترض، خشمگین و مطالبه‌گر)", "آیا واقعاً این امکان‌پذیر است؟ من که باورم نمی‌شود! (با لحنی کنجکاو، کمی شکاک و متعجب) 🤔"] },
            { id: "Pulcherrima", name: "سارا (زن)", gender: "female", desc: "جذاب و مدرن", imgUrl: "https://uploadkon.ir/uploads/acb105_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۷۴۳.jpg", samples: ["https://uploadkon.ir/uploads/142c06_26سارا-یک-2-.mp3", "https://uploadkon.ir/uploads/246c06_26سارا-دو-2-.mp3", "https://uploadkon.ir/uploads/4baa06_26سارا-سه-2-.mp3", "https://uploadkon.ir/uploads/6c5406_26سارا-چهار-2-.mp3"], sampleTexts: ["", "", "هر سرباز باید آماده نبرد باشد! هیچ شکی در کار نیست! (با لحنی قاطع، جدی و آماده برای مبارزه، شبیه به یک فرمانده نظامی در میدان جنگ) 🪖", "واای! این دیگه چه فیلمی بود؟! اصلاً نفهمیدم چی شد! (با لحنی گیج، کمی ناامید و متعجب از یک اتفاق غیرمنتظره یا نامفهوم) "] },
            { id: "Umbriel", name: "مانی (مرد)", gender: "male", desc: "خلاق و متفاوت", imgUrl: "https://uploadkon.ir/uploads/68b505_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۹۱۴.jpg", samples: ["https://uploadkon.ir/uploads/62e006_26مانی-یک-2-.mp3", "https://uploadkon.ir/uploads/8af206_26مانی-دو-2-.mp3", "https://uploadkon.ir/uploads/a1f406_26مانی-سه-2-.mp3", "https://uploadkon.ir/uploads/4d2506_26مانی-چهار-2-.mp3"], sampleTexts: ["", "", "وای! این بهترین هدیه‌ای بود که تا به حال گرفتم! ممنونم، ممنونم! (با لحنی سرشار از ذوق، شادی کودکانه و تشکر فراوان) 🎁", "ببینید، این موضوع بسیار ساده است، فقط کافیست کمی دقت کنید. (با لحنی آموزش‌دهنده، کمی از بالا به پایین و صبورانه) "] },
            { id: "Algieba", name: "آرتین (مرد)", gender: "male", desc: "با اصالت و شیک", imgUrl: "https://uploadkon.ir/uploads/571005_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۰۳۹.jpg", samples: ["https://uploadkon.ir/uploads/dbed06_26آرتین-یک-2-.mp3", "https://uploadkon.ir/uploads/865706_26آرتین-دو-2-.mp3", "https://uploadkon.ir/uploads/5e5806_26آرتین-سه-2-.mp3", "https://uploadkon.ir/uploads/0d8206_26آرتین-چهار-2-.mp3"], sampleTexts: ["", "", "تو جرئت نداری این کار رو بکنی! من بهت هشدار میدم! (با لحنی پر از تهدید، خشم و اخطار جدی) ", "خب، پس قرار شد ساعت ۸ شب، جلوی سینما باشیم، درسته؟ (با لحنی معمولی، دوستانه و تأییدکننده برای یک قرار ملاقات) 🗓️🤝"] },
            { id: "Despina", name: "دلنواز (زن)", gender: "female", desc: "هنری و احساسی", imgUrl: "https://uploadkon.ir/uploads/5d7805_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۲۲۲.jpg", samples: ["https://uploadkon.ir/uploads/a3b506_26دلنواز-یک-2-.mp3", "https://uploadkon.ir/uploads/f67c06_26دلنواز-دو-2-.mp3", "https://uploadkon.ir/uploads/180106_26دلنواز-سه-2-.mp3", "https://uploadkon.ir/uploads/d31f06_26دلنواز-چهار-2-.mp3"], sampleTexts: ["", "", "آیا واقعاً این تنها راه حل است؟ من فکر نمی‌کنم. (با لحنی متفکر، شکاک و کمی ناامید)", "من که گفتم! این یک پیروزی بزرگ برای تیم ماست! آفرین به همه! (با لحنی پرشور، شاد و با صدای بلند و هیجان‌زده، شبیه به یک مربی ورزشی پس از برد) 🏆🎉"] },
            { id: "Erinome", name: "روژان (زن)", gender: "female", desc: "شفاف و گویا", imgUrl: "https://uploadkon.ir/uploads/aa8805_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۳۴۹.jpg", samples: ["https://uploadkon.ir/uploads/dea706_26روژان-یک-2-.mp3", "https://uploadkon.ir/uploads/496b06_26روژان-دو-2-.mp3", "https://uploadkon.ir/uploads/185e06_26روژان-سه-2-.mp3", "https://uploadkon.ir/uploads/b2f306_26روژان-چهار-2-.mp3"], sampleTexts: ["", "", "فکر می‌کنم این بهترین فرصتی است که تا به حال داشته‌ایم؛ نباید آن را از دست بدهیم. (با لحنی امیدوار، متفکر و کمی محرمانه) ", "من به شما هشدار داده بودم که این مسیر پرخطر است، اما شما گوش نکردید. (با لحنی سرزنش‌آمیز، همراه با حس تأسف و من گفته بودم) "] },
            { id: "Algenib", name: "امید (مرد)", gender: "male", desc: "انگیزه بخش و مثبت", imgUrl: "https://uploadkon.ir/uploads/a63c05_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۹۲۱.jpg", samples: ["https://uploadkon.ir/uploads/3e9806_26امید-یک-2-.mp3", "https://uploadkon.ir/uploads/6c3306_26امید-دو-2-.mp3", "https://uploadkon.ir/uploads/65fc06_26امید-سه-2-.mp3", "https://uploadkon.ir/uploads/367f06_26امید-چهار-2-.mp3"], sampleTexts: ["", "", "نه، نه! این امکان نداره! ما باید همین الان فرار کنیم! اونا دارن میان! (با لحنی مملو از ترس، وحشت و اضطراب شدید، شبیه به یک شخصیت که در حال فرار از خطر است) ", "فکر می‌کنم بهترین راه اینه که یواشکی وارد بشیم و کسی هم متوجه نشه. (با لحنی آرام، مرموز و شیطنت‌آمیز، مناسب برای برنامه‌ریزی یک کار مخفیانه) "] },
            { id: "Orus", name: "بردیا (مرد)", gender: "male", desc: "ورزشی و پرهیجان", imgUrl: "https://uploadkon.ir/uploads/8bc405_25IMG-۲۰۲۵۰۷۰۵-۱۲۱۴۳۳.jpg", samples: ["https://uploadkon.ir/uploads/699d06_26بردیا-یک-2-.mp3", "https://uploadkon.ir/uploads/b6ad06_26بردیا-دو-2-.mp3", "https://uploadkon.ir/uploads/6a6506_26بردیا-سه-2-.mp3", "https://uploadkon.ir/uploads/8a1006_26بردیا-چهار-2-.mp3"], sampleTexts: ["", "", "تبریک می‌گویم! این موفقیت بزرگ، نتیجه تلاش بی‌وقفه و اراده قوی شماست! (با لحنی سرشار از شادی، تحسین و تبریک صمیمانه) ", "من که بهت گفته بودم این کار رو نکن! حالا ببین چه بلایی سرمون اومد! (با لحنی سرزنش‌آمیز و همراه با حس من گفته بودم، کمی خشمگین و ناامید) "] },
            { id: "Aoede", name: "ترانه (زن)", gender: "female", desc: "موزیکال و خوش‌آهنگ", imgUrl: "https://uploadkon.ir/uploads/9cb405_25IMG-۲۰۲۵۰۷۰۵-۱۲۱۸۵۰.jpg", samples: ["https://uploadkon.ir/uploads/b67306_26ترانه-یک-2-.mp3", "https://uploadkon.ir/uploads/154806_26ترانه-دو-2-.mp3", "https://uploadkon.ir/uploads/ee3806_26ترانه-سه-2-.mp3", "https://uploadkon.ir/uploads/b53806_26ترانه-چهار-2-.mp3"], sampleTexts: ["", "", "به هیچ وجه کوتاه نمی‌آیم! این حق من است و باید به دستش بیاورم! (با لحنی سرسخت، مصمم و بسیار با اراده، شبیه به کسی که برای حقش می‌جنگد) ", "من واقعاً نمی‌دانم چه کار کنم! کاملاً گیج شده‌ام و راه حلی پیدا نمی‌کنم! (با صدایی مملو از سردرگمی، استیصال و ناامیدی) "] },
            { id: "Callirrhoe", name: "نیکو (زن)", gender: "female", desc: "روایتگر و قصه‌گو", imgUrl: "https://uploadkon.ir/uploads/ee5f05_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۰۴۷.jpg", samples: ["https://uploadkon.ir/uploads/b53806_26نیکو-یک-2-.mp3", "https://uploadkon.ir/uploads/e1aa06_26نیکو-دو-2-.mp3", "https://uploadkon.ir/uploads/d74f06_26نیکو-سه-2-.mp3", "https://uploadkon.ir/uploads/32fe06_26نیکو-چهار-2-.mp3"], sampleTexts: ["", "", "باید هرچه سریع‌تر به نقطه امن برسیم! زمان زیادی نداریم! (با لحنی مضطرب، قاطع و سراسیمه، شبیه به کسی که در حال فرار از خطر است) 🏃‍♀️", "عجب! واقعاً انتظار داشتی که این اتفاق بیفته؟ من که از اول می‌دونستم! (با لحنی طعنه‌آمیز، همراه با حس من گفته بودم و کمی خستگی از پیش‌بینی درست) "] },
            { id: "Autonoe", name: "هستی (زن)", gender: "female", desc: "طبیعی و خودمانی", imgUrl: "https://uploadkon.ir/uploads/9b0505_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۲۲۲.jpg", samples: ["https://uploadkon.ir/uploads/758506_26هستی-یک-2-.mp3", "https://uploadkon.ir/uploads/b69e06_26هستی-دو-2-.mp3", "https://uploadkon.ir/uploads/9dce06_26هستی-سه-2-.mp3", "https://uploadkon.ir/uploads/ccee06_26هستی-چهار-2-.mp3"], sampleTexts: ["", "", "هرگز از جستجوی دانش دست نکش، زیرا نور خرد راهگشای تاریکی‌هاست. (با لحنی آرام، حکیمانه و پر از تجربه، شبیه به یک استاد پیر) ", "وااای! ببین! یه پروانه خیلی خوشگل نشست رو دستم! باورم نمیشه! (با لحنی سرشار از شگفتی، ذوق کودکانه و هیجان محض) 🦋🤩"] },
            { id: "Enceladus", name: "کامیار (مرد)", gender: "male", desc: "مصمم و جدی", imgUrl: "https://uploadkon.ir/uploads/127805_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۴۱۴.jpg", samples: ["https://uploadkon.ir/uploads/566606_26کامیار-یک-2-.mp3", "https://uploadkon.ir/uploads/882806_26کامیار-دو-2-.mp3", "https://uploadkon.ir/uploads/32b006_26کامیار-سه-2-.mp3", "https://uploadkon.ir/uploads/843506_26کامیار-چهار-2-.mp3"], sampleTexts: ["", "", "توجه، توجه! یک پیام فوری از ستاد فرماندهی! آماده دریافت دستورات جدید باشید! (با لحنی رسمی، قاطع و کمی اضطراری، شبیه به اعلامیه نظامی) 📢", "من که گفتم! این تصمیم کاملاً اشتباه بود و حالا همه باید عواقبش رو تحمل کنیم! (با لحنی مأیوس، سرزنش‌گر و همراه با حس من می‌دانستم)"] },
            { id: "Iapetus", name: "کیانوش (مرد)", gender: "male", desc: "درخشان و گیرا", imgUrl: "https://uploadkon.ir/uploads/c98b05_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۶۰۵.jpg", samples: ["https://uploadkon.ir/uploads/63fd06_26کیانوش-یک-2-.mp3", "https://uploadkon.ir/uploads/f6f406_26کیانوش-دو-2-.mp3", "https://uploadkon.ir/uploads/1b2106_26کیانوش-سه-2-.mp3", "https://uploadkon.ir/uploads/33f206_26کیانوش-چهار-2-.mp3"], sampleTexts: ["", "", "و در سمت راست شما، می‌توانید منظره‌ای بی‌نظیر از آبشار نیاگارا را مشاهده کنید. (با لحنی هیجان‌زده، اطلاعاتی و راهنمایانه، شبیه به یک تورلیدر پرشور) 🏞️", "آه! دیگر بس است! چقدر باید این حرف‌ها را تکرار کنم؟ (با صدایی مملو از کلافگی، خستگی مفرط و عصبانیت از تکرار) "] },
            { id: "Puck", name: "پویا (مرد)", gender: "male", desc: "بازیگوش و سرزنده", imgUrl: "https://uploadkon.ir/uploads/ca3605_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۸۳۹.jpg", samples: ["https://uploadkon.ir/uploads/7d1306_26پویا-یک-2-.mp3", "https://uploadkon.ir/uploads/681206_26پویا-دو-2-.mp3", "https://uploadkon.ir/uploads/c90b06_26پویا-سه-2-.mp3", "https://uploadkon.ir/uploads/12e906_26پویا-چهار-2-.mp3"], sampleTexts: ["", "", "من هرگز نمی‌توانم نبود او را باور کنم؛ جای خالی‌اش همیشه در قلب من خواهد بود و مرا آزار می‌دهد. (با لحنی غمگین، حزن‌انگیز و مملو از اندوه عمیق)", "هی، یه فکری به سرم زده! بیا یه ماجراجویی کوچیک داشته باشیم، کسی هم خبردار نشه! (با لحنی شیطنت‌آمیز، وسوسه‌کننده و کمی مخفیانه، شبیه به کسی که قصد کاری هیجان‌انگیز دارد) "] },
            { id: "Kore", name: "مهتاب (زن)", gender: "female", desc: "نجواگر و آرامش‌بخش", imgUrl: "https://uploadkon.ir/uploads/b66605_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۰۳۵.jpg", samples: ["https://uploadkon.ir/uploads/9bfc06_26مهتاب-یک-2-.mp3", "https://uploadkon.ir/uploads/e31006_26مهتاب-دو-2-.mp3", "https://uploadkon.ir/uploads/fdc506_26مهتاب-سه-2-.mp3", "https://uploadkon.ir/uploads/071d06_26مهتاب-چهار-2-.mp3"], sampleTexts: ["", "", "هرگز اجازه ندهید ترس، شما را از رسیدن به آرزوهایتان باز دارد. شجاع باشید! (با لحنی الهام‌بخش، قدرتمند و تشویق‌کننده، شبیه به یک سخنران انگیزشی)", "خب، فکر کنم وقتشه که این راز رو فاش کنیم؛ دیگه نمی‌تونм بیشتر از این نگهش دارم! (با لحنی هیجان‌زده، کمی مرموز و همراه با حس افشاگری) "] },
            { id: "Fenrir", name: "سام (مرد)", gender: "male", desc: "جسور و بی‌باک", imgUrl: "https://uploadkon.ir/uploads/03c005_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۴۱۳.jpg", samples: ["https://uploadkon.ir/uploads/467f06_26سام-یک-2-.mp3", "https://uploadkon.ir/uploads/793c06_26سام-دو-2-.mp3", "https://uploadkon.ir/uploads/937606_26سام-سه-2-.mp3", "https://uploadkon.ir/uploads/bcc006_26سام-چهار-2-.mp3"], sampleTexts: ["", "", "توجه! یک موجود ناشناخته در حال نزدیک شدن است! همه هوشیار باشید! (با لحنی هراس‌آلود، اضطراری و هشداردهنده، شبیه به اعلام خطر در یک فیلم علمی-تخیلی) 👽🚨", "آه خدای من! این چه غذای لذیذی است! هرگز چیزی به این خوشمزگی نخورده بودم! (با لحنی سرشار از رضایت، لذت و شگفتی از طعم یک غذا) "] },
            { id: "Leda", name: "لیدا (زن)", gender: "female", desc: "کلاسیک و باوقار", imgUrl: "https://uploadkon.ir/uploads/710305_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۷۳۱.jpg", samples: ["https://uploadkon.ir/uploads/547606_26لیدا-یک-2-.mp3", "https://uploadkon.ir/uploads/f9b706_26لیدا-دو-2-.mp3", "https://uploadkon.ir/uploads/312706_26لیدا-سه-2-.mp3", "https://uploadkon.ir/uploads/07e006_26لیدا-چهار-2-.mp3"], sampleTexts: ["", "", "توجه! تمامی سیستم‌ها در حالت اضطراری قرار گیرند! نفوذ شناسایی شد! (با لحنی کاملاً فنی، بی‌احساس و هشداردهنده، شبیه به صدای یک کامپیوتر مرکزی در حالت خطر) 🤖🚨", "\"واو! این معرکه است! اصلاً فکرش رو هم نمی‌کردم که اینقدر خوب باشه!\" (با لحنی هیجان‌زده، پر از تحسین و کمی شوک مثبت)"] }
        ];

        // ==========================================
        // PART 10-1: INITIALIZATION & UTILITY FUNCTIONS
        // متغیرهای اصلی، دیتابیس و توابع پایه
        // ==========================================
        const mainFormContainer = document.getElementById('standard-tts-form-container');
        const mainOutputSection = document.getElementById('output-section-standard');
        const mainAudioPlayer = document.getElementById('hidden-audio-player');
        const sampleAudioPlayer = document.getElementById('sample-audio-player');
        
        const modals = {
            speaker: document.getElementById('speaker-modal'),
            charLimit: document.getElementById('char-limit-modal'),
            longText: document.getElementById('long-text-modal'),
            confirmDelete: document.getElementById('confirm-delete-modal')
        };
        
        const speakerGridInModal = document.getElementById('speaker-grid');
        const selectedSpeakerIdStorage = document.getElementById('selected_speaker_id_storage');
        
        let activePodcastSpeakers = [];
        let podcastMasterAudioBlobs = [];
        let speakerToReplaceId = null;
        let currentlyPlayingTurnPlayer = null;
        let mainAudioPeaks = [];
        let podcastAudioPlayer = new Audio();
        let podcastAudioPeaks = [];
        let lastAddedSpeakerIndex = -1;
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        let isMainSelectorAction = false; 

        const showModal = (modal) => modal.classList.add('visible');
        const hideModal = (modal) => {
            modal.classList.remove('visible');
            if (modal.id === 'speaker-modal') {
                sampleAudioPlayer.pause();
                document.getElementById('sample-text-display').classList.remove('active');
            }
        };

        const formatTime = (s) => { if (isNaN(s) || s < 0) return '0:00'; const m = Math.floor(s / 60); return `${m}:${Math.floor(s % 60).toString().padStart(2, '0')}`; };

        const blobToAudioBuffer = async (blob) => {
            if (!blob) return null;
            const arrayBuffer = await blob.arrayBuffer();
            if (audioContext.state === 'suspended') await audioContext.resume();
            try {
                return await audioContext.decodeAudioData(arrayBuffer);
            } catch (e) {
                console.error("Error decoding audio data:", e);
                return null;
            }
        };

        // ==========================================
        // PART 10-2: AUDIO PLAYER & WAVEFORM LOGIC
        // پردازش نمودار صدا و ایجاد پلیرها
        // ==========================================
        const processAudioForWaveform = (audioBuffer) => {
            if (!audioBuffer) return [];
            const data = audioBuffer.getChannelData(0);
            const samples = Math.floor(audioBuffer.duration * 40);
            if (samples === 0) return [];
            const peaks = [];
            const sampleSize = Math.floor(data.length / samples);
            for (let i = 0; i < samples; i++) {
                let max = 0;
                const start = i * sampleSize;
                for (let j = 0; j < sampleSize; j++) {
                    const val = Math.abs(data[start + j]);
                    if (val > max) max = val;
                }
                peaks.push(Math.min(1, Math.max(0, max * 1.5)));
            }
            return peaks;
        };

        const drawWaveform = (canvas, peaks, progressRatio) => {
            if (!canvas || !peaks || peaks.length === 0) return;
            const ctx = canvas.getContext('2d'); const dpr = window.devicePixelRatio || 1; canvas.width = canvas.offsetWidth * dpr; canvas.height = canvas.offsetHeight * dpr; ctx.scale(dpr, dpr); const width = canvas.offsetWidth, height = canvas.offsetHeight; ctx.clearRect(0, 0, width, height); const barWidth = 3, barGap = 2, totalBarWidth = barWidth + barGap; const numBars = Math.floor(width / totalBarWidth); const offset = (width - numBars * totalBarWidth) / 2;
            const inactiveColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-inactive').trim();
            const activeColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-active').trim();
            ctx.fillStyle = inactiveColor;
            for (let i = 0; i < numBars; i++) { const idx = Math.floor((i / numBars) * peaks.length); const barH = (peaks[idx] || 0) * height; ctx.fillRect(offset + i * totalBarWidth, (height - barH) / 2, barWidth, barH); }
            const activeFillEnd = progressRatio * width;
            if (activeFillEnd > 0) {
                ctx.save(); ctx.beginPath(); ctx.rect(0, 0, activeFillEnd, height); ctx.clip(); ctx.fillStyle = activeColor;
                for (let i = 0; i < numBars; i++) { const idx = Math.floor((i / numBars) * peaks.length); const barH = (peaks[idx] || 0) * height; ctx.fillRect(offset + i * totalBarWidth, (height - barH) / 2, barWidth, barH); }
                ctx.restore();
            }
        };
        
        function createPlayerInstance(container, player, getPeaksCallback, setPeaksCallback) {
            container.innerHTML = `<div class="audio-waveform-container"><span class="audio-time audio-current-time">0:00</span><div class="audio-waveform"><canvas class="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 type="button" class="audio-skip-btn backward" title="پرش به عقب"><svg viewBox="0 0 24 24"><path d="M11 16V8l-4 4 4 4zm4-12v16l7-8-7-8z"></path></svg></button><button type="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 type="button" class="audio-skip-btn forward" title="پرش به جلو"><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 type="button" class="audio-volume-btn" title="قطع/وصل صدا"><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 type="button" class="audio-speed-btn" title="سرعت پخش">1x</button></div>`;
            
            const updateUI = () => {
                const isPlaying = !(player.paused || player.ended);
                container.querySelectorAll('.play-icon').forEach(i => i.style.display = isPlaying ? 'none' : 'block');
                container.querySelectorAll('.pause-icon').forEach(i => i.style.display = isPlaying ? 'block' : 'none');
                container.querySelector('.audio-current-time').textContent = formatTime(player.currentTime);
                container.querySelector('.audio-total-time').textContent = isFinite(player.duration) ? formatTime(player.duration) : '0:00';
                const canvas = container.querySelector('.audio-waveform-canvas');
                if (canvas) {
                    const progress = isFinite(player.duration) && player.duration > 0 ? player.currentTime / player.duration : 0;
                    requestAnimationFrame(() => drawWaveform(canvas, getPeaksCallback(), progress));
                }
            };

            player.addEventListener('loadeddata', async () => {
                const blob = await fetch(player.src).then(res => res.blob());
                const audioBuffer = await blobToAudioBuffer(blob);
                setPeaksCallback(processAudioForWaveform(audioBuffer));
                updateUI();
            });
            ['timeupdate', 'play', 'pause', 'ended'].forEach(e => player.addEventListener(e, updateUI));
            window.addEventListener('resize', updateUI);
            
            container.querySelector('.audio-play-pause-btn-large').addEventListener('click', () => player.paused ? player.play() : player.pause());

            container.querySelector('.audio-skip-btn.backward').addEventListener('click', () => {
                player.currentTime = Math.max(0, player.currentTime - 5);
            });
            container.querySelector('.audio-skip-btn.forward').addEventListener('click', () => {
                player.currentTime = Math.min(player.duration || 0, player.currentTime + 5);
            });

            const speedBtn = container.querySelector('.audio-speed-btn');
            const speeds = [1, 1.25, 1.5, 2, 0.75];
            let currentSpeedIndex = 0;
            speedBtn.addEventListener('click', () => {
                currentSpeedIndex = (currentSpeedIndex + 1) % speeds.length;
                const newSpeed = speeds[currentSpeedIndex];
                player.playbackRate = newSpeed;
                speedBtn.textContent = `${newSpeed}x`;
            });

            const volumeBtn = container.querySelector('.audio-volume-btn');
            const volHighIcon = volumeBtn.querySelector('.volume-high-icon');
            const volMuteIcon = volumeBtn.querySelector('.volume-mute-icon');

            volumeBtn.addEventListener('click', () => {
                player.muted = !player.muted;
            });

            const updateVolumeIcon = () => {
                if (player.muted || player.volume === 0) {
                    volHighIcon.style.display = 'none';
                    volMuteIcon.style.display = 'block';
                } else {
                    volHighIcon.style.display = 'block';
                    volMuteIcon.style.display = 'none';
                }
            };
            player.addEventListener('volumechange', updateVolumeIcon);
            updateVolumeIcon(); 
        };
        
        async function handleDownloadRequest(button, audioPlayer) {
            if (!audioPlayer.src) return;
            button.disabled = true; button.textContent = 'در حال آماده‌سازی...';
            try {
                let blob;
                if (audioPlayer.src.startsWith('blob:')) {
                     blob = await (await fetch(audioPlayer.src)).blob();
                } else {
                     const resp = await fetch(audioPlayer.src);
                     if (!resp.ok) throw new Error('Fetch failed');
                     blob = await resp.blob();
                }
                
                const blobUrl = URL.createObjectURL(blob);
                
                window.parent.postMessage({ 
                    type: 'INITIATE_DOWNLOAD_FROM_URL', 
                    payload: { audioUrl: blobUrl } 
                }, '*');
                
                setTimeout(() => {
                    button.disabled = false; 
                    button.textContent = 'دانلود با کیفیت اصلی';
                }, 2000);
                
            } catch(e) {
                alert("دانلود با خطا مواجه شد.");
                button.disabled = false; 
                button.textContent = 'دانلود با کیفیت اصلی';
            }
        }

        window.addEventListener('message', (event) => {
            if (event.data?.type === 'DOWNLOAD_COMPLETE') { }
            if (event.data?.type === 'DOWNLOAD_FAILED') {
                alert(event.data.payload.error || 'خطا در دانلود.');
            }
            if (event.data?.type === 'USER_STATUS_RESPONSE') {
                try {
                    const userObject = JSON.parse(event.data.payload);
                    updateUIForSubscriptionStatus(isUserPaid(userObject) ? 'paid' : 'free');
                } catch (e) { updateUIForSubscriptionStatus('free'); }
            }
        });

        async function getBrowserFingerprint() {
            const components = [navigator.userAgent, navigator.language, screen.width + 'x' + screen.height, new Date().getTimezoneOffset()];
            try { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx.fillText("a1b2c3d4e5f6g7h8i9j0_!@#$%^&*()", 2, 15); components.push(canvas.toDataURL()); } catch (e) { components.push("canvas-error"); }
            const fingerprintString = components.join('~~~'); let hash = 0;
            for (let i = 0; i < fingerprintString.length; i++) { hash = ((hash << 5) - hash) + fingerprintString.charCodeAt(i); hash |= 0; }
            return 'fp_' + Math.abs(hash).toString(16);
        }

        function isUserPaid(userObject) { return userObject?.isLogin && userObject.accessible_pages?.includes(PREMIUM_PAGE_ID); }
        
        // ===================================================================
        // START: REPLACEMENT FOR PARTS 10-3
        // این بلوک کامل را جایگزین سه پارت آخر اسکریپت خود کنید
        // ===================================================================

        // PART 10-3: USER STATUS & STANDARD TTS (MODIFIED)
        async function updateUIWithServerStatus() {
            const creditMsg = document.getElementById('credit-status-message');
            const upgradeBtn = document.getElementById('upgrade-premium-btn');
            if (!userFingerprint || userSubscriptionStatus === 'paid') {
                creditMsg.classList.remove('visible');
                document.querySelectorAll('.generate-btn').forEach(btn => btn.disabled = false);
                upgradeBtn.style.display = 'none'; return;
            }
            creditMsg.textContent = 'در حال بررسی اعتبار...'; creditMsg.classList.add('visible');
            try {
                const response = await fetch('/api/check-credit-tts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ fingerprint: userFingerprint, subscriptionStatus: userSubscriptionStatus }) });
                const result = await response.json();
                if (result.limit_reached) { 
                    document.querySelectorAll('.generate-btn').forEach(btn => btn.disabled = true); 
                    upgradeBtn.style.display = 'block'; 
                    creditMsg.textContent = 'اعتبار تولید رایگان امروز شما تمام شده است.'; 
                } else { 
                    document.querySelectorAll('.generate-btn').forEach(btn => btn.disabled = false); 
                    upgradeBtn.style.display = 'none'; 
                    creditMsg.textContent = `شما ${result.credits_remaining} اعتبار تولید رایگان برای امروز دارید.`; 
                }
            } catch (error) { creditMsg.textContent = "خطا در بررسی اعتبار."; }
        }
        
        function updateUIForSubscriptionStatus(status) {
            userSubscriptionStatus = status;
            document.querySelectorAll('.subscription-status-badge').forEach(badge => {
                badge.textContent = status === 'paid' ? 'نسخه نامحدود' : 'نسخه رایگان';
                badge.className = `subscription-status-badge ${status === 'paid' ? 'paid-badge' : 'free-badge'}`;
                badge.style.display = 'inline-block';
            });
            updateUIWithServerStatus();
        }

        // NEW Reusable function to render the standard player UI
        function renderStandardPlayer(audioSrc) {
            mainOutputSection.innerHTML = ''; 
            mainOutputSection.classList.add('has-content');
            const playerContent = document.createElement('div'); 
            playerContent.className = 'audio-player-content'; 
            playerContent.style.display = 'flex';
            const downloadWrapper = document.createElement('div'); 
            downloadWrapper.className = 'download-wrapper'; 
            downloadWrapper.innerHTML = `
                <button class="beautiful-download-btn" id="standard-download-btn">
                    <svg viewBox="0 0 24 24"><path d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"></path></svg>
                    دانلود با کیفیت اصلی
                </button>
                <button type="button" id="clear-history-btn">
                    <svg viewBox="0 0 24 24"><path d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"></path></svg>
                    حذف کامل پروژه و شروع مجدد
                </button>
            `;
            mainOutputSection.appendChild(playerContent); 
            mainOutputSection.appendChild(downloadWrapper);
            
            mainAudioPlayer.src = audioSrc;
            createPlayerInstance(playerContent, mainAudioPlayer, () => mainAudioPeaks, (p) => mainAudioPeaks = p);
            
            downloadWrapper.querySelector('#standard-download-btn').addEventListener('click', (e) => handleDownloadRequest(e.currentTarget, mainAudioPlayer));
            downloadWrapper.querySelector('#clear-history-btn').addEventListener('click', () => showModal(modals.confirmDelete));
        }

        function handleStandardTTS() {
            const form = document.getElementById('standard-tts-form');
            const textInput = document.getElementById('text-input-standard');
            const promptInput = document.getElementById('prompt-input-standard');
            const generateBtn = document.getElementById('generate-btn-standard');

            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                if (generateBtn.disabled) return;
                const text = textInput.value.trim();
                const promptText = promptInput.value.trim();
                const speakerId = selectedSpeakerIdStorage.value;

                if (!text) { alert('متن ورودی خالی است.'); return; }
                
                if (text.length > LONG_TEXT_THRESHOLD) {
                    if (userSubscriptionStatus !== 'paid') {
                        showModal(modals.charLimit);
                        return;
                    }
                    showModal(modals.longText);
                    return;
                }
                
                await clearProjectState(); // Clear previous project (podcast or standard) before starting a new one.
                localStorage.setItem('alphaTtsMainText', text); 
                localStorage.setItem('alphaTtsMainSpeaker', speakerId);

                showLoadingState(mainOutputSection, "در حال تولید صدا...");
                const spinner = generateBtn.querySelector(".spinner"); 
                const btnText = generateBtn.querySelector(".btn-text");
                spinner.style.display = 'inline-block'; 
                btnText.textContent = 'در حال ساخت...'; 
                generateBtn.disabled = true;

                try {
                    const response = await fetch('/api/generate', {
                        method: 'POST', headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ 
                            text: text, 
                            speaker: speakerId, 
                            temperature: 1.5,
                            prompt: promptText,
                            fingerprint: userFingerprint, 
                            subscriptionStatus: userSubscriptionStatus 
                        })
                    });

                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.message || 'خطا در ارسال درخواست.');
                    }
                    const data = await response.json();
                    
                    const poll = setInterval(async () => {
                        let statusData;
                        try {
                            const statusRes = await fetch('/api/check_status', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: data.job_id }) });
                            statusData = await statusRes.json();
                            if (statusData.status === 'completed') {
                                clearInterval(poll);
                                
                                // **MODIFICATION START: Save audio and state to IndexedDB**
                                const audioBlob = await fetch(statusData.proxy_url).then(res => res.blob());
                                await saveAudioSegment('main_audio', audioBlob);
                                await saveProjectState({
                                    mode: 'standard',
                                    text: text,
                                    speaker: speakerId,
                                    prompt: promptText
                                });
                                // **MODIFICATION END**

                                renderStandardPlayer(statusData.proxy_url); // Use the new reusable function
                                updateUIWithServerStatus();
                            } else if (statusData.status === 'error') {
                                clearInterval(poll);
                                showErrorState(mainOutputSection, statusData.result);
                            }
                        } catch (pollError) {
                            clearInterval(poll);
                            showErrorState(mainOutputSection, "خطا در بررسی وضعیت.");
                        } finally {
                            if (statusData && (statusData.status === 'completed' || statusData.status === 'error')) {
                                spinner.style.display = 'none'; 
                                btnText.textContent = '✨ خلق صدا با آلفا'; 
                                generateBtn.disabled = false; // Re-enable button
                                updateUIWithServerStatus();
                            }
                        }
                    }, 3000);
                } catch (error) {
                    showErrorState(mainOutputSection, error.message);
                    spinner.style.display = 'none'; 
                    btnText.textContent = '✨ خلق صدا با آلفا'; 
                    generateBtn.disabled = false;
                    updateUIWithServerStatus();
                }
            });
        }
        
        function splitText(text, maxLength = 450) {
            const sentences = text.match(/[^.!?]+[.!?]*\s*/g) || [text];
            const chunks = [];
            let currentChunk = "";
            for (const sentence of sentences) {
                if (currentChunk.length + sentence.length <= maxLength) {
                    currentChunk += sentence;
                } else {
                    if (currentChunk) chunks.push(currentChunk.trim());
                    currentChunk = sentence;
                }
            }
            if (currentChunk) chunks.push(currentChunk.trim());
            return chunks;
        }

        // PART 10-4: PODCAST CORE LOGIC (MODIFIED)
        function triggerSave() {
             const scriptData = Array.from(document.querySelectorAll('.podcast-studio-container .script-turn')).map((turn, index) => ({
                speakerId: turn.querySelector('.custom-select-container').dataset.selectedId,
                dialogue: turn.querySelector('textarea').value
            }));
            const activeSpeakers = activePodcastSpeakers.map(s => s.id);
            const originalText = document.getElementById('text-input-standard').value;

            if(scriptData.length > 0) {
                saveProjectState({
                    mode: 'podcast',
                    originalText: originalText,
                    scriptData: scriptData,
                    activeSpeakers: activeSpeakers
                });
            }
        }

        function setupPodcastInterface(scriptData, container) {
            container.innerHTML = '';
            container.classList.add('has-content');
            
            const studioContainer = document.createElement('div');
            studioContainer.className = 'podcast-studio-container';
            studioContainer.innerHTML = `
                <div class="form-group"><label>🎤 تیم گویندگان</label><div id="project-speakers-container"><div id="add-speaker-card" class="speaker-display-card"><div class="plus-icon">+</div><h3>افزودن گوینده</h3></div></div></div>
                <div class="form-group">
                    <label>📜 سناریوی گفتگو</label>
                    <div id="podcast-script-container"></div>
                    <button type="button" id="add-turn-btn">+ افزودن نوبت گفتگو</button>
                </div>
                <button type="submit" id="generate-btn-podcast" class="generate-btn"><span class="btn-text">🎙️ ساخت فایل صوتی نهایی</span><div class="spinner"></div></button>
                <div id="podcast-output-section" class="output-section" style="margin-top: 2rem;">
                     <div id="status-message-podcast" class="status-message">فایل نهایی در اینجا ظاهر خواهد شد.</div>
                     <div class="download-wrapper" style="padding-top: 1.5rem;">
                        <button type="button" id="clear-history-btn">
                            <svg viewBox="0 0 24 24"><path d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"></path></svg>
                            حذف کامل پروژه و شروع مجدد
                        </button>
                    </div>
                </div>
            `;
            container.appendChild(studioContainer);
            
            if (activePodcastSpeakers.length === 0) {
                 activePodcastSpeakers = [...new Set(scriptData.map(item => item.speakerId))].map(id => allSpeakers.find(s => s.id === id)).filter(Boolean);
            }

            if (activePodcastSpeakers.length === 0 && scriptData.length > 0) {
                 activePodcastSpeakers = [allSpeakers[0]]; 
            }
            lastAddedSpeakerIndex = -1;

            renderActivePodcastSpeakers();
            const scriptContainer = studioContainer.querySelector('#podcast-script-container');
            scriptData.forEach(turn => addPodcastScriptTurn(turn.speakerId, turn.dialogue, scriptContainer));

            studioContainer.querySelector('#add-speaker-card').addEventListener('click', () => { isMainSelectorAction = false; speakerToReplaceId = null; createSpeakerCardsInModal(); showModal(modals.speaker); });
            studioContainer.querySelector('#add-turn-btn').addEventListener('click', () => {
                if (activePodcastSpeakers.length === 0) return alert('لطفا ابتدا یک گوینده به پروژه اضافه کنید.');
                lastAddedSpeakerIndex = (lastAddedSpeakerIndex + 1) % activePodcastSpeakers.length;
                addPodcastScriptTurn(activePodcastSpeakers[lastAddedSpeakerIndex].id, '', scriptContainer);
                triggerSave(); 
            });
            studioContainer.querySelector('#generate-btn-podcast').addEventListener('click', generatePodcastAudio);
            studioContainer.querySelector('#clear-history-btn').addEventListener('click', () => showModal(modals.confirmDelete));
            
            triggerSave();
            studioContainer.scrollIntoView({ behavior: 'smooth' });
        }

        async function initiateAiPodcastGeneration(userText) {
            hideModal(modals.longText);
            await clearProjectState(); 
            activePodcastSpeakers = [];
            podcastMasterAudioBlobs = [];
            currentPodcastMode = 'ai-podcast';
            localStorage.setItem('alphaTtsMainText', userText);
            mainOutputSection.innerHTML = '';
            mainOutputSection.classList.remove('has-content');
            showLoadingState(mainOutputSection, "در حال اتصال به هوش مصنوعی نویسنده...");
            
            const systemPrompt = `تو یک سناریو نویس و طراح خلاق پادکست هستی. وظیفه تو این است که متن زیر را به یک سناریوی پادکست فوق‌العاده صمیمی، عمیق، پر از جزئیات و بسیار طولانی تبدیل کنی.

قوانین سخت‌گیرانه‌ای که باید رعایت کنی:
۱. فقط و فقط ۲ گوینده (ترجیحاً یک زن و یک مرد) از بین لیست گویندگان در دسترس انتخاب کن. با توجه به متن کاربر گوینده ها می‌تونه بیشتر از دو نفر مثلا سه یا حد اکثر چهار نفر باشد.
۲. سناریو باید دقیقاً شبیه به یک پادکست واقعی و زنده باشد؛ یعنی گویندگان مدام با هم دیالوگ‌های کوتاه رد و بدل کنند، از هم سوال بپرسند، صحبت‌های یکدیگر را تایید یا تکمیل کنند و با هم شوخی یا صمیمیت پادکستی داشته باشند. به هیچ وجه اجازه نده یکی از گویندگان متن‌های خیلی طولانی و خسته‌کننده به صورت یک‌طرفه (مونولوگ) بخواند.
۳. تمام مفاهیم، نکات و اطلاعات موجود در متن را کاملاً تشریح کن و شاخ و برگ بده تا طول سناریو طولانی و پرمحتوا شود.

متن اصلی برای خلق سناریوی پادکست دو نفره:
${userText}`;
            try {
                // اصلاح اول: ارسال درخواست به پروکسی پایتون خودمان به جای لینک مستقیم
                const response = await fetch('/api/create-full-podcast', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        prompt: systemPrompt, 
                        available_speakers: [...allSpeakers]
    .map(s => ({ id: s.id, name: s.name, gender: s.gender }))
    .sort(() => Math.random() - 0.5) 
                    })
                });
                
                if (!response.ok) throw new Error('خطا در ارتباط با سرور هوش مصنوعی.');
                const data = await response.json();
                const taskId = data.task_id;
                
                showLoadingState(mainOutputSection, "هوش مصنوعی در حال نوشتن سناریو و انتخاب گویندگان...");
                
                const pollInterval = setInterval(async () => {
                    try {
                        // اصلاح دوم: دریافت وضعیت از پروکسی پایتون خودمان
                        const statusRes = await fetch(`/api/podcast-status/${taskId}`);
                        const result = await statusRes.json();
                        
                        if (result.status === 'completed') {
                            clearInterval(pollInterval);
                            const aiScriptData = result.data.script.map(turn => ({
                                speakerId: turn.speaker_id,
                                dialogue: turn.dialogue
                            }));
                            setupPodcastInterface(aiScriptData, mainOutputSection);
                        } else if (result.status === 'failed') {
                            clearInterval(pollInterval);
                            showErrorState(mainOutputSection, "هوش مصنوعی موفق به پردازش متن نشد.");
                        }
                    } catch (e) {
                        clearInterval(pollInterval);
                        showErrorState(mainOutputSection, "خطا در دریافت وضعیت.");
                    }
                }, 3000);
            } catch (error) {
                showErrorState(mainOutputSection, error.message);
            }
        }

        async function initiatePodcastConversion(mode) {
            if (mode === 'ai-podcast') {
                const text = document.getElementById('text-input-standard').value.trim();
                initiateAiPodcastGeneration(text);
                return;
            }
            hideModal(modals.longText);
            await clearProjectState();
            activePodcastSpeakers = [];
            podcastMasterAudioBlobs = [];
            currentPodcastMode = mode;
            const text = document.getElementById('text-input-standard').value.trim();
            const chunks = splitText(text);
            let scriptData = [];
            let speakersPool = [];
            const mainSpeaker = allSpeakers.find(s => s.id === selectedSpeakerIdStorage.value);
            if (mode === 'single') {
                speakersPool.push(mainSpeaker);
            } else {
                const numSpeakers = (mode === 'double') ? 2 : 3;
                while (speakersPool.length < numSpeakers) {
                    let randomSpeaker = allSpeakers[Math.floor(Math.random() * allSpeakers.length)];
                    if (!speakersPool.some(s => s.id === randomSpeaker.id)) {
                        speakersPool.push(randomSpeaker);
                    }
                }
            }
            chunks.forEach((chunk, index) => {
                const speaker = speakersPool[index % speakersPool.length];
                scriptData.push({ speakerId: speaker.id, dialogue: chunk });
            });
            setupPodcastInterface(scriptData, mainOutputSection);
        }

        function renderActivePodcastSpeakers() {
            const container = document.getElementById('project-speakers-container');
            if (!container) return;
            container.querySelectorAll('.speaker-display-card:not(#add-speaker-card)').forEach(c => c.remove());
            activePodcastSpeakers.forEach(speaker => {
                const card = document.createElement('div');
                card.className = 'speaker-display-card';
                card.innerHTML = `<button type="button" class="remove-speaker-btn">×</button><img src="${speaker.imgUrl}" alt="${speaker.name}"><h3>${speaker.name}</h3>`;
                container.insertBefore(card, container.querySelector('#add-speaker-card'));
                card.querySelector('.remove-speaker-btn').addEventListener('click', (e) => { e.stopPropagation(); removePodcastSpeaker(speaker.id); });
                card.addEventListener('click', () => { isMainSelectorAction = false; speakerToReplaceId = speaker.id; createSpeakerCardsInModal(); showModal(modals.speaker); });
            });
            document.querySelectorAll('.podcast-studio-container .custom-select-container').forEach(c => updatePodcastTurnSelect(c, c.dataset.selectedId));
        }

        function removePodcastSpeaker(speakerId) {
            if (activePodcastSpeakers.length <= 1) { alert("پروژه باید حداقل یک گوینده داشته باشد."); return; }
            const oldSpeakerId = speakerId;
            activePodcastSpeakers = activePodcastSpeakers.filter(s => s.id !== speakerId);
            const newSpeakerId = activePodcastSpeakers[0].id;
            document.querySelectorAll(`.podcast-studio-container .custom-select-container[data-selected-id="${oldSpeakerId}"]`).forEach(sel => {
                updatePodcastTurnSelect(sel, newSpeakerId);
            });
            renderActivePodcastSpeakers();
            triggerSave();
        }

        function addPodcastScriptTurn(speakerId, text, container) {
            const turnDiv = document.createElement('div');
            turnDiv.className = 'script-turn';
            const turnIndex = container.children.length;
            turnDiv.innerHTML = `
                <div class="turn-speaker-selector">
                    <div class="custom-select-container" data-selected-id="${speakerId}">
                        <div class="custom-select-trigger"></div>
                        <div class="custom-select-options"></div>
                    </div>
                </div>
                <div class="turn-content">
                    <textarea>${text || ''}</textarea>
                    <div class="turn-player-container">
                        <button type="button" class="turn-play-btn">
                            <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"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path></svg>
                        </button>
                        <audio class="turn-audio" style="display:none;"></audio>
                        <div class="loading-state-wrapper" style="display:none;">
                            <div class="spinner"></div>
                            <span class="loading-text">در حال جایگزینی...</span>
                        </div>
                        <button type="button" class="turn-retry-btn">
                            <svg viewBox="0 0 24 24"><path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"></path></svg>
                            جایگزین قطعه
                        </button>
                        <span class="replace-success-message">فایل جدید جایگزین شد</span>
                        <span class="main-update-message">فایل اصلی بروز شد</span>
                    </div>
                </div>
                <button type="button" class="remove-turn-btn" title="حذف نوبت">×</button>`;
            container.appendChild(turnDiv);
            
            const textarea = turnDiv.querySelector('textarea');
            textarea.addEventListener('input', triggerSave);
            
            updatePodcastTurnSelect(turnDiv.querySelector('.custom-select-container'), speakerId);
            turnDiv.querySelector('.turn-retry-btn').addEventListener('click', () => handleRetry(turnDiv, turnIndex));
            turnDiv.querySelector('.remove-turn-btn').addEventListener('click', async () => {
                const index = Array.from(container.children).indexOf(turnDiv);
                if (index > -1) {
                    podcastMasterAudioBlobs[index] = null;
                    await saveAudioSegment(index, null); 
                    turnDiv.remove();
                    Array.from(container.children).forEach((child, newIndex) => {
                        child.querySelector('.turn-retry-btn').onclick = () => handleRetry(child, newIndex);
                    });
                    if (podcastAudioPlayer.src) {
                        await rebuildFinalAudio(false);
                    }
                    triggerSave(); 
                }
            });
        }

        function updatePodcastTurnSelect(container, selectedId) {
            if(!container) return;
            const trigger = container.querySelector('.custom-select-trigger');
            const optionsDiv = container.querySelector('.custom-select-options');
            optionsDiv.innerHTML = '';
            
            let selectedSpeaker = activePodcastSpeakers.find(s => s.id === selectedId);
            if (!selectedSpeaker && activePodcastSpeakers.length > 0) {
                selectedSpeaker = activePodcastSpeakers[0];
                selectedId = selectedSpeaker.id;
            }
            if(!selectedSpeaker) return;

            trigger.innerHTML = `<img src="${selectedSpeaker.imgUrl}"><span>${selectedSpeaker.name}</span><svg class="arrow" viewBox="0 0 24 24"><path fill="currentColor" d="M7,10L12,15L17,10H7Z"></path></svg>`;
            activePodcastSpeakers.forEach(s => {
                const opt = document.createElement('div');
                opt.className = 'custom-select-option';
                opt.dataset.id = s.id;
                opt.innerHTML = `<img src="${s.imgUrl}"><span>${s.name}</span>`;
                opt.addEventListener('click', (e) => {
                     const newId = e.currentTarget.dataset.id;
                     const selectContainer = e.currentTarget.closest('.custom-select-container');
                     selectContainer.dataset.selectedId = newId;
                     triggerSave();
                });
                optionsDiv.appendChild(opt);
            });
            container.dataset.selectedId = selectedId;
        }
        
        async function generateSegmentWithRetry(segment, loadingTextElement, totalSegments, completedCounter) {
            if (podcastMasterAudioBlobs[segment.index]) {
                const progressItem = document.getElementById(`progress-segment-${segment.index}`);
                if (progressItem) progressItem.className = 'progress-item done';
                completedCounter.count++;
                if (loadingTextElement) loadingTextElement.textContent = `در حال پردازش (${completedCounter.count} از ${totalSegments} تکمیل شده)`;
                setupTurnPlayer(segment.element, segment.index);
                return;
            }

            while (true) {
                try {
                    const payload = {
                        text: segment.dialogue, 
                        speaker: segment.speakerId,
                        temperature: 1.5,
                        prompt: '',
                        fingerprint: userFingerprint,
                        subscriptionStatus: userSubscriptionStatus
                    };
                    const response = await fetch('/api/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
                    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                    const data = await response.json();

                    return await new Promise((resolve, reject) => {
                        const poll = setInterval(async () => {
                            try {
                                const statusRes = await fetch('/api/check_status', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: data.job_id }) });
                                const statusData = await statusRes.json();
                                if (statusData.status === 'completed') {
                                    clearInterval(poll);
                                    const audioBlob = await fetch(statusData.proxy_url).then(res => res.blob());
                                    podcastMasterAudioBlobs[segment.index] = audioBlob;
                                    
                                    await saveAudioSegment(segment.index, audioBlob);
                                    setupTurnPlayer(segment.element, segment.index); 

                                    const progressItem = document.getElementById(`progress-segment-${segment.index}`);
                                    if(progressItem) progressItem.className = 'progress-item done';
                                    
                                    completedCounter.count++;
                                    if(loadingTextElement) loadingTextElement.textContent = `در حال پردازش (${completedCounter.count} از ${totalSegments} تکمیل شده)`;

                                    resolve();
                                } else if (statusData.status === 'error') {
                                    clearInterval(poll);
                                    const progressItem = document.getElementById(`progress-segment-${segment.index}`);
                                    if(progressItem) progressItem.className = 'progress-item error';
                                    reject(new Error(`Segment ${segment.index + 1} failed: ${statusData.result}`));
                                }
                            } catch (pollError) {
                                clearInterval(poll);
                                reject(pollError);
                            }
                        }, 3000);
                    });
                } catch (error) {
                    console.error(`Attempt for segment ${segment.index} failed: ${error.message}. Retrying...`);
                    await new Promise(res => setTimeout(res, 3000));
                }
            }
        }
        
        async function asyncPool(poolLimit, array, iteratorFn) {
            const ret = [];
            const executing = [];
            for (const item of array) {
                const p = iteratorFn(item).catch(e => e); 
                ret.push(p);
                if (poolLimit <= array.length) {
                    const e = p.then(() => executing.splice(executing.indexOf(e), 1));
                    executing.push(e);
                    if (executing.length >= poolLimit) {
                        await Promise.race(executing);
                    }
                }
            }
            return Promise.all(ret);
        }

        async function generatePodcastAudio() {
            const generateBtn = document.getElementById('generate-btn-podcast');
            const outputSection = document.getElementById('podcast-output-section');
            if (generateBtn.disabled) return;

            triggerSave();

            const scriptData = Array.from(document.querySelectorAll('.podcast-studio-container .script-turn')).map((turn, index) => ({
                element: turn,
                index: index,
                speakerId: turn.querySelector('.custom-select-container').dataset.selectedId,
                dialogue: turn.querySelector('textarea').value.trim()
            }));

            showLoadingState(outputSection, `در حال پردازش (0 از ${scriptData.length} تکمیل شده)`, true, scriptData.length);
            const loadingTextElement = document.getElementById('podcast-loading-text');

            const spinner = generateBtn.querySelector(".spinner");
            const btnText = generateBtn.querySelector(".btn-text");
            spinner.style.display = 'inline-block';
            btnText.textContent = 'در حال ساخت...';
            generateBtn.disabled = true;

            let completedCounter = { count: 0 };

            try {
                const MAX_BROWSER_CONCURRENCY = 20; 
                
                await asyncPool(MAX_BROWSER_CONCURRENCY, scriptData, (segment) => 
                    generateSegmentWithRetry(segment, loadingTextElement, scriptData.length, completedCounter)
                );

                for(let i = 0; i < scriptData.length; i++){
                    if(!podcastMasterAudioBlobs[i]){
                        throw new Error(`قطعه شماره ${i + 1} ساخته نشد. لطفا صفحه را رفرش کرده و مجددا تلاش کنید تا فقط قطعات باقی مانده ساخته شوند.`);
                    }
                }
                
                showLoadingState(outputSection, "در حال ترکیب نهایی صدا...");
                await rebuildFinalAudio(true);

            } catch (error) {
                showErrorState(outputSection, error.message);
            } finally {
                spinner.style.display = 'none';
                btnText.textContent = '🎙️ ساخت فایل صوتی نهایی';
                generateBtn.disabled = false;
            }
        }
        
        async function handleRetry(turnDiv, turnIndex) {
            const playerContainer = turnDiv.querySelector('.turn-player-container');
            const retryBtn = playerContainer.querySelector('.turn-retry-btn');
            const loadingWrapper = playerContainer.querySelector('.loading-state-wrapper');
            const successMsg = playerContainer.querySelector('.replace-success-message');
            const mainMsg = playerContainer.querySelector('.main-update-message');

            retryBtn.style.display = 'none';
            loadingWrapper.style.display = 'flex';
            successMsg.style.display = 'none';
            mainMsg.style.display = 'none';

            try {
                const payload = {
                    text: turnDiv.querySelector('textarea').value.trim(),
                    speaker: turnDiv.querySelector('.custom-select-container').dataset.selectedId,
                    temperature: 1.5,
                    prompt: '',
                    fingerprint: userFingerprint,
                    subscriptionStatus: userSubscriptionStatus
                };
                const response = await fetch('/api/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
                if (!response.ok) throw new Error('Failed to start job.');
                const data = await response.json();

                const finalBlob = await new Promise((resolve, reject) => {
                    const poll = setInterval(async () => {
                        try {
                            const statusRes = await fetch('/api/check_status', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ job_id: data.job_id })});
                            const statusData = await statusRes.json();
                            if (statusData.status === 'completed') {
                                clearInterval(poll);
                                const audioBlob = await fetch(statusData.proxy_url).then(res => res.blob());
                                resolve(audioBlob);
                            } else if (statusData.status === 'error') {
                                clearInterval(poll);
                                reject(new Error('Generation failed.'));
                            }
                        } catch {
                            clearInterval(poll);
                            reject(new Error('Polling failed.'));
                        }
                    }, 3000);
                });
                
                podcastMasterAudioBlobs[turnIndex] = finalBlob;
                await saveAudioSegment(turnIndex, finalBlob);

                setupTurnPlayer(turnDiv, turnIndex);
                loadingWrapper.style.display = 'none';

                successMsg.style.display = 'flex';
                successMsg.style.animation = 'none';
                void successMsg.offsetWidth; 
                successMsg.style.animation = 'fadeInOut 2.5s forwards';

                setTimeout(async () => {
                    successMsg.style.display = 'none';
                    if (podcastMasterAudioBlobs.every(b => b)) {
                        mainMsg.style.display = 'flex';
                        mainMsg.style.animation = 'none';
                        void mainMsg.offsetWidth;
                        mainMsg.style.animation = 'fadeInOut 2.5s forwards';
                        await rebuildFinalAudio(false);
                    }
                    setTimeout(() => {
                        mainMsg.style.display = 'none';
                        retryBtn.style.display = 'flex';
                    }, 2500);
                }, 2500);

            } catch (error) {
                alert("جایگزینی قطعه با خطا مواجه شد.");
                loadingWrapper.style.display = 'none';
                retryBtn.style.display = 'flex';
            }
        }
        
        async function rebuildFinalAudio(isInitialBuild = false) {
            const outputSection = document.getElementById('podcast-output-section');
            if (!outputSection) return;

            const mergedBlob = await mergeAudioBlobs(podcastMasterAudioBlobs.filter(Boolean));
            
            if (mergedBlob) {
                outputSection.innerHTML = '';
                outputSection.classList.add('has-content');

                const playerContent = document.createElement('div');
                playerContent.className = 'audio-player-content';
                playerContent.style.display = 'flex';

                const downloadWrapper = document.createElement('div');
                downloadWrapper.className = 'download-wrapper';
                downloadWrapper.innerHTML = `
                    <button class="beautiful-download-btn" id="podcast-download-btn">
                        <svg viewBox="0 0 24 24"><path d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"></path></svg>
                        دانلود با کیفیت اصلی
                    </button>
                    <button type="button" id="clear-history-btn">
                        <svg viewBox="0 0 24 24"><path d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"></path></svg>
                        حذف کامل پروژه و شروع مجدد
                    </button>
                `;

                outputSection.appendChild(playerContent);
                outputSection.appendChild(downloadWrapper);

                podcastAudioPlayer.src = URL.createObjectURL(mergedBlob);
                createPlayerInstance(playerContent, podcastAudioPlayer, () => podcastAudioPeaks, (p) => podcastAudioPeaks = p);
                
                downloadWrapper.querySelector('#podcast-download-btn').addEventListener('click', (e) => handleDownloadRequest(e.currentTarget, podcastAudioPlayer));
                downloadWrapper.querySelector('#clear-history-btn').addEventListener('click', () => showModal(modals.confirmDelete));
                
                if (isInitialBuild) {
                    document.querySelectorAll('.podcast-studio-container .script-turn').forEach((turn, index) => {
                        setupTurnPlayer(turn, index);
                    });
                }
            } else if (isInitialBuild) {
                 showErrorState(outputSection, "خطا در ترکیب فایل نهایی.");
            }
        }

        function setupTurnPlayer(turnDiv, index) {
            const playerContainer = turnDiv.querySelector('.turn-player-container');
            const playBtn = playerContainer.querySelector('.turn-play-btn');
            const audio = playerContainer.querySelector('.turn-audio');
            
            const blob = podcastMasterAudioBlobs[index];
            if (blob) {
                if (audio.src) URL.revokeObjectURL(audio.src);
                audio.src = URL.createObjectURL(blob);
                playerContainer.classList.add('visible');

                playBtn.onclick = () => {
                    if (currentlyPlayingTurnPlayer && currentlyPlayingTurnPlayer !== audio) {
                        currentlyPlayingTurnPlayer.pause();
                    }
                    if (audio.paused) {
                        audio.play();
                        currentlyPlayingTurnPlayer = audio;
                    } else {
                        audio.pause();
                    }
                };
                audio.onplay = () => playerContainer.classList.add('playing');
                audio.onpause = audio.onended = () => {
                    playerContainer.classList.remove('playing');
                    if(currentlyPlayingTurnPlayer === audio) currentlyPlayingTurnPlayer = null;
                };
            }
        }
        
        async function mergeAudioBlobs(blobs) {
            const decodedBuffers = await Promise.all(blobs.filter(b => b).map(blobToAudioBuffer));
            const validBuffers = decodedBuffers.filter(b => b);
            if (validBuffers.length === 0) return null;
            const totalLength = validBuffers.reduce((total, buffer) => total + buffer.length, 0);
            const outputBuffer = audioContext.createBuffer(validBuffers[0].numberOfChannels, totalLength, validBuffers[0].sampleRate);
            let offset = 0;
            for (const buffer of validBuffers) {
                for (let channel = 0; channel < buffer.numberOfChannels; channel++) {
                    outputBuffer.getChannelData(channel).set(buffer.getChannelData(channel), offset);
                }
                offset += buffer.length;
            }
            return bufferToWavBlob(outputBuffer);
        }

        function bufferToWavBlob(buffer) {
            const numOfChan = buffer.numberOfChannels, length = buffer.length * numOfChan * 2 + 44;
            const bufferArr = new ArrayBuffer(length), view = new DataView(bufferArr);
            let pos = 0;
            const writeString = s => { for (let i = 0; i < s.length; i++) view.setUint8(pos++, s.charCodeAt(i)); };
            writeString('RIFF'); view.setUint32(pos, 36 + length - 8, true); pos += 4; writeString('WAVE');
            writeString('fmt '); view.setUint32(pos, 16, true); pos += 4; view.setUint16(pos, 1, true); pos += 2;
            view.setUint16(pos, numOfChan, true); pos += 2; view.setUint32(pos, buffer.sampleRate, true); pos += 4;
            view.setUint32(pos, buffer.sampleRate * 2 * numOfChan, true); pos += 4;
            view.setUint16(pos, numOfChan * 2, true); pos += 2; view.setUint16(pos, 16, true); pos += 2;
            writeString('data'); view.setUint32(pos, length - pos - 4, true); pos += 4;
            const channels = [];
            for (let i = 0; i < buffer.numberOfChannels; i++) channels.push(buffer.getChannelData(i));
            let offset = 0;
            while (pos < length) {
                for (let i = 0; i < numOfChan; i++) {
                    let s = Math.max(-1, Math.min(1, channels[i][offset]));
                    s = s < 0 ? s * 0x8000 : s * 0x7FFF;
                    view.setInt16(pos, s, true);
                    pos += 2;
                }
                offset++;
            }
            return new Blob([view], { type: 'audio/wav' });
        }


        function showLoadingState(container, message, showProgressGrid = false, segmentCount = 0) {
            container.classList.remove('has-content');
            let progressGridHTML = '';
            if (showProgressGrid) {
                let items = '';
                for (let i = 0; i < segmentCount; i++) {
                    items += `<div class="progress-item pending" id="progress-segment-${i}">${i + 1}</div>`;
                }
                progressGridHTML = `<div id="generation-progress-container"><div class="progress-grid">${items}</div></div>`;
            }
            container.innerHTML = `
                <div class="loading-animation-wrapper" style="display: flex;">
                    <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 class="loading-text" id="podcast-loading-text">${message}</p>
                    ${progressGridHTML}
                </div>`;
        }
        
        function showErrorState(container, message) {
            container.classList.remove('has-content');
            container.innerHTML = `<div class="status-message error">${message || 'خطا در پردازش.'}</div>`;
        }

        // ==========================================
        // PART 10-5: MODAL LOGIC, EVENTS & BOOTSTRAP (MODIFIED)
        // مدیریت مودال، رویدادها و شروع برنامه
        // ==========================================
        function createSpeakerCardsInModal() {
            speakerGridInModal.innerHTML = '';
            const isPodcastMode = !!document.querySelector('.podcast-studio-container');
            const activeIdsInPodcast = activePodcastSpeakers.map(s => s.id);

            allSpeakers.forEach((speaker) => {
                const card = document.createElement('label'); card.className = 'speaker-card';
                
                if (!isMainSelectorAction && isPodcastMode && activeIdsInPodcast.includes(speaker.id) && speaker.id !== speakerToReplaceId) {
                    card.classList.add('disabled');
                }
                
                let samplesHTML = speaker.samples?.map((sampleUrl, index) => `<button type="button" class="sample-play-btn" data-src="${sampleUrl}" data-text-index="${index}" data-speaker-id="${speaker.id}"><svg class="play-icon-svg" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg><div class="playing-indicator"><span></span><span></span><span></span></div></button>`).join('') || '';
                card.innerHTML = `<input type="radio" name="modal_speaker_selection" value="${speaker.id}"><div class="speaker-visual"><img src="${speaker.imgUrl}" alt="${speaker.name}" loading="lazy"><div class="sample-player-container">${samplesHTML}</div></div><div class="speaker-name">${speaker.name}</div>`;
                
                if (!card.classList.contains('disabled')) {
                    const radio = card.querySelector('input');
                    radio.checked = isMainSelectorAction ? speaker.id === selectedSpeakerIdStorage.value : false;
                    
                    card.addEventListener('click', (e) => {
                        if (e.target.closest('.sample-play-btn')) return;
                        e.preventDefault();

                        const newSpeakerId = e.currentTarget.querySelector('input').value;

                        if (isMainSelectorAction) {
                            document.getElementById('selected_speaker_id_storage').value = newSpeakerId;
                            localStorage.setItem('alphaTtsMainSpeaker', newSpeakerId);
                            updateSelectedSpeakerDisplay(); 
                        } else {
                            const speakerToAdd = allSpeakers.find(s => s.id === newSpeakerId);
                            if (speakerToReplaceId) {
                                const idx = activePodcastSpeakers.findIndex(s => s.id === speakerToReplaceId);
                                if (idx > -1) activePodcastSpeakers[idx] = speakerToAdd;
                                document.querySelectorAll(`.podcast-studio-container .custom-select-container[data-selected-id="${speakerToReplaceId}"]`).forEach(sel => updatePodcastTurnSelect(sel, newSpeakerId));
                                speakerToReplaceId = null;
                            } else {
                                if (!activePodcastSpeakers.some(s => s.id === newSpeakerId)) {
                                    activePodcastSpeakers.push(speakerToAdd);
                                }
                            }
                            renderActivePodcastSpeakers();
                            triggerSave();
                        }
                        hideModal(modals.speaker);
                    });
                }
                speakerGridInModal.appendChild(card);
            });
        }
        
        function updateSelectedSpeakerDisplay() {
            const speakerId = selectedSpeakerIdStorage.value;
            const speaker = allSpeakers.find(s => s.id === speakerId) || allSpeakers[0];
            if(speaker) {
                document.getElementById('selected-speaker-img').src = speaker.imgUrl;
                document.getElementById('selected-speaker-name').textContent = speaker.name;
                document.getElementById('selected-speaker-desc').textContent = speaker.desc;
            }
        }

        function setupEventListeners() {
            const mainTextInput = document.getElementById('text-input-standard');
            mainTextInput.addEventListener('input', (e) => {
                const text = e.target.value;
                document.getElementById('char-count').textContent = text.length.toLocaleString('fa-IR');
                localStorage.setItem('alphaTtsMainText', text);
                const outputSection = document.getElementById('output-section-standard');
                if (text.trim() && !outputSection.querySelector('.audio-player-content') && !outputSection.querySelector('.podcast-studio-container')) {
                    if (!outputSection.querySelector('#clear-history-btn')) {
                         showConditionalDeleteButton(outputSection);
                    }
                } else if (!text.trim()) {
                    const btn = outputSection.querySelector('#clear-history-btn');
                    if(btn) btn.parentElement.remove();
                }
            });

            document.getElementById('change-speaker-btn').addEventListener('click', () => { 
                isMainSelectorAction = true; 
                speakerToReplaceId = null; 
                createSpeakerCardsInModal(); 
                showModal(modals.speaker); 
            });
            document.getElementById('selected-speaker-card').addEventListener('click', () => { 
                isMainSelectorAction = true; 
                speakerToReplaceId = null; 
                createSpeakerCardsInModal(); 
                showModal(modals.speaker); 
            });
            
            document.querySelectorAll('.modal-overlay').forEach(o => o.addEventListener('click', e => { if (e.target === o) hideModal(o); }));
            document.querySelectorAll('.close-modal-btn').forEach(b => b.addEventListener('click', () => hideModal(b.closest('.modal-overlay'))));
            document.getElementById('char-limit-upgrade-btn').addEventListener('click', () => window.parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM', payload: { url: PREMIUM_URL } }, '*'));
            document.getElementById('upgrade-premium-btn').addEventListener('click', () => window.parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM', payload: { url: PREMIUM_URL } }, '*'));
            document.getElementById('char-limit-close-link').addEventListener('click', () => hideModal(modals.charLimit));
            
            modals.longText.querySelectorAll('.option-card').forEach(card => card.addEventListener('click', (e) => {
                initiatePodcastConversion(e.currentTarget.dataset.mode);
            }));

            document.getElementById('cancel-delete-btn').addEventListener('click', () => hideModal(modals.confirmDelete));
            document.getElementById('confirm-delete-action-btn').addEventListener('click', async () => {
                await clearProjectState();
                hideModal(modals.confirmDelete);
                window.location.reload();
            });

            document.body.addEventListener('click', (e) => {
                if (e.target.closest('.sample-play-btn')) {
                    e.preventDefault(); e.stopPropagation();
                    const btn = e.target.closest('.sample-play-btn');
                    const audioSrc = btn.dataset.src;
                    const playingBtn = document.querySelector('.sample-play-btn.playing');
                    
                    const speakerId = btn.dataset.speakerId;
                    const textIndex = btn.dataset.textIndex;
                    const speaker = allSpeakers.find(s => s.id === speakerId);
                    const textDisplay = document.getElementById('sample-text-display');
                    
                    if (playingBtn && playingBtn === btn) {
                        sampleAudioPlayer.pause();
                        textDisplay.classList.remove('active'); 
                    } else {
                        if (playingBtn) playingBtn.classList.remove('playing');
                        sampleAudioPlayer.src = audioSrc;
                        sampleAudioPlayer.play();
                        btn.classList.add('playing');
                        
                        if (speaker && speaker.sampleTexts && speaker.sampleTexts[textIndex]) {
                            document.getElementById('sample-text-content').textContent = speaker.sampleTexts[textIndex];
                            textDisplay.classList.add('active');
                        } else {
                            textDisplay.classList.remove('active');
                        }
                    }
                } else if (e.target.closest('.podcast-studio-container .custom-select-trigger')) {
                    e.target.closest('.custom-select-container').classList.toggle('open');
                } else if (e.target.closest('.podcast-studio-container .custom-select-option')) {
                    const option = e.target.closest('.custom-select-option');
                    const container = option.closest('.custom-select-container');
                    updatePodcastTurnSelect(container, option.dataset.id);
                    container.classList.remove('open');
                    triggerSave();
                } else {
                    document.querySelectorAll('.podcast-studio-container .custom-select-container.open').forEach(c => c.classList.remove('open'));
                }
            });
            
            sampleAudioPlayer.addEventListener('pause', () => {
                document.querySelector('.sample-play-btn.playing')?.classList.remove('playing');
                document.getElementById('sample-text-display').classList.remove('active');
            });
            sampleAudioPlayer.addEventListener('ended', () => {
                document.querySelector('.sample-play-btn.playing')?.classList.remove('playing');
                document.getElementById('sample-text-display').classList.remove('active');
            });
        }
        
        function showConditionalDeleteButton(container) {
            if (container.querySelector('#clear-history-btn')) return;
            
            const deleteBtnHTML = `<div class="download-wrapper" style="padding: 1.5rem 0;">
                        <button type="button" id="clear-history-btn">
                            <svg viewBox="0 0 24 24"><path d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"></path></svg>
                            حذف کامل پروژه و شروع مجدد
                        </button>
                    </div>`;
            container.innerHTML += deleteBtnHTML;
            container.querySelector('#clear-history-btn').addEventListener('click', () => showModal(modals.confirmDelete));
        }

        async function initializeApp() {
            userFingerprint = await getBrowserFingerprint();
            
            await initDB();
            const savedData = await loadProjectState();
            
            const mainTextInput = document.getElementById('text-input-standard');
            let savedText = localStorage.getItem('alphaTtsMainText');
            let savedSpeaker = localStorage.getItem('alphaTtsMainSpeaker');

            if (savedData?.state?.mode === 'podcast') {
                if (savedData.state.originalText) mainTextInput.value = savedData.state.originalText;
                if(savedSpeaker) selectedSpeakerIdStorage.value = savedSpeaker;
                
                podcastMasterAudioBlobs = savedData.audioData || [];
                if (savedData.state.activeSpeakers) {
                     activePodcastSpeakers = savedData.state.activeSpeakers.map(id => allSpeakers.find(s => s.id === id)).filter(Boolean);
                }
                
                setupPodcastInterface(savedData.state.scriptData, mainOutputSection);
                
                document.querySelectorAll('.podcast-studio-container .script-turn').forEach((turn, index) => {
                   if(podcastMasterAudioBlobs[index]) setupTurnPlayer(turn, index);
                });

                if(podcastMasterAudioBlobs.filter(Boolean).length > 0) await rebuildFinalAudio(false);

            } else if (savedData?.state?.mode === 'standard') {
                mainTextInput.value = savedData.state.text;
                selectedSpeakerIdStorage.value = savedData.state.speaker;
                if (savedData.state.prompt) document.getElementById('prompt-input-standard').value = savedData.state.prompt;

                const mainAudioBlob = await new Promise(res => {
                    const tx = db.transaction('audioSegments', 'readonly');
                    const store = tx.objectStore('audioSegments');
                    const request = store.get('main_audio');
                    request.onsuccess = e => res(e.target.result);
                    request.onerror = () => res(null);
                });

                if (mainAudioBlob) {
                    const blobUrl = URL.createObjectURL(mainAudioBlob);
                    renderStandardPlayer(blobUrl);
                }
            } else {
                if (savedText) mainTextInput.value = savedText;
                if(savedSpeaker) selectedSpeakerIdStorage.value = savedSpeaker;
                if ((savedText && savedText.trim() !== '') || (savedSpeaker && savedSpeaker !== 'Charon')) {
                    showConditionalDeleteButton(mainOutputSection);
                }
            }

            handleStandardTTS();
            parent.postMessage({ type: 'REQUEST_USER_STATUS' }, '*');
            updateSelectedSpeakerDisplay();
            
            // **MODIFICATION: Attach listeners BEFORE dispatching the event**
            setupEventListeners(); 
            mainTextInput.dispatchEvent(new Event('input')); 
        }
        
        initializeApp();
    });
    </script>
</body>
</html>