Voice_tts.vue 121 KB
Newer Older
litzh's avatar
litzh committed
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
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
<template>
  <!-- 模态框遮罩和容器 - Apple 极简风格 -->
  <div class="fixed inset-0 bg-black/50 dark:bg-black/60 backdrop-blur-sm z-[60] flex items-center justify-center p-2">
    <div class="relative w-full h-full max-w-6xl max-h-[100vh] bg-white/95 dark:bg-[#1e1e1e]/95 backdrop-blur-[40px] backdrop-saturate-[180%] border border-black/10 dark:border-white/10 rounded-3xl shadow-[0_20px_60px_rgba(0,0,0,0.2)] dark:shadow-[0_20px_60px_rgba(0,0,0,0.6)] overflow-hidden flex flex-col">
      <!-- 模态框头部 - Apple 风格 -->
      <div class="flex items-center justify-between px-6 py-4 border-b border-black/8 dark:border-white/8 bg-white/50 dark:bg-[#1e1e1e]/50 backdrop-blur-[20px] flex-shrink-0">
        <div class="flex items-center gap-3">
          <h3 class="text-xl font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] flex items-center gap-3 tracking-tight">
            <i class="fas fa-volume-up text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
            <span>{{ t('voiceSynthesis') }}</span>
          </h3>
          <!-- 模式切换开关 -->
          <div class="flex items-center gap-2">
            <button
              @click="toggleMode"
              class="relative w-14 h-7 rounded-full transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-[color:var(--brand-primary)]/20 dark:focus:ring-[color:var(--brand-primary-light)]/20"
              :class="isMultiSegmentMode ? 'bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)]' : 'bg-[#86868b]/30 dark:bg-[#98989d]/30'"
              :title="isMultiSegmentMode ? t('tts.switchToSingleSegmentMode') : t('tts.switchToMultiSegmentMode')"
            >
              <!-- 滑动圆点 -->
              <span
                class="absolute top-0.5 left-0.5 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 flex items-center justify-center"
                :class="{ 'translate-x-7': isMultiSegmentMode, 'translate-x-0': !isMultiSegmentMode }"
              >
                <i :class="isMultiSegmentMode ? 'fas fa-layer-group text-[8px] text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]' : 'fas fa-exchange-alt text-[8px] text-[#86868b] dark:text-[#98989d]'"></i>
              </span>
            </button>
            <span class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight" :class="{ 'text-[#86868b] dark:text-[#98989d]': !isMultiSegmentMode }">
              {{ isMultiSegmentMode? t('tts.multiSegmentMode') : t('tts.singleSegmentMode') }}</span>
          </div>
          <button
            v-show="!isMultiSegmentMode"
            @click="openHistoryPanel"
            class="w-9 h-9 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] rounded-full transition-all duration-200 hover:scale-110 active:scale-100"
            :title="t('ttsHistoryTitle')"
          >
            <i class="fas fa-history text-sm"></i>
          </button>
        </div>
        <div class="flex items-center gap-2">
          <!-- 应用按钮 - Apple 风格 -->
          <button
            @click="isMultiSegmentMode ? applyMergedAudio() : applySelectedVoice()"
            :disabled="isMultiSegmentMode ? (audioSegments.filter(s => s.audioBlob).length === 0) : (!selectedVoice || !inputText.trim() || isGenerating)"
            class="w-9 h-9 flex items-center justify-center bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white rounded-full transition-all duration-200 hover:scale-110 active:scale-100 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"
            :title="isMultiSegmentMode ? t('applyMergedAudio') : t('applySelectedVoice')">
            <i class="fas fa-check text-sm"></i>
          </button>
          <!-- 关闭按钮 - Apple 风格 -->
          <button @click="closeModal"
            class="w-9 h-9 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] rounded-full transition-all duration-200 hover:scale-110 active:scale-100">
            <i class="fas fa-times text-sm"></i>
          </button>
        </div>
      </div>

      <!-- 多段模式预览区 -->
      <div v-if="isMultiSegmentMode && audioSegments.length > 0" class="flex-shrink-0 bg-[#f5f5f7]/30 dark:bg-[#1c1c1e]/30">
        <div class="max-w-5xl mx-auto px-6 py-5">
          <div class="bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl p-4">
            <!-- 合并音频播放器 -->
            <div v-if="mergedAudioDuration > 0" class="mb-4">
              <div class="flex items-center gap-3 mb-3">
                <button
                  @click="toggleMergedAudioPlayback"
                  class="w-10 h-10 bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white rounded-full flex items-center justify-center cursor-pointer hover:scale-110 transition-all duration-200"
                >
                  <i :class="isPlayingMerged ? 'fas fa-pause' : 'fas fa-play'" class="text-sm ml-0.5"></i>
                </button>
                <div class="flex-1">
                  <div class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7]">{{ t('tts.mergedAudio') }}</div>
                  <div class="text-xs text-[#86868b] dark:text-[#98989d]">{{ formatAudioTime(mergedCurrentTime) }} / {{ formatAudioTime(mergedAudioDuration) }}</div>
                </div>
              </div>
              <input
                v-if="mergedAudioDuration > 0"
                type="range"
                :min="0"
                :max="mergedAudioDuration"
                :value="mergedCurrentTime"
                @input="onMergedProgressChange"
                class="w-full h-1 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full"
              />
            </div>
            <!-- 分段进度条 - 水平排列 -->
            <div class="flex items-start gap-4 flex-wrap max-h-[200px] overflow-y-auto main-scrollbar">
              <div
                v-for="(segment, index) in audioSegments"
                :key="segment.id"
                class="flex flex-col gap-2 flex-1 min-w-[140px] max-w-[200px]"
                :class="{ 'opacity-50': segment.isGenerating }"
              >
                <!-- 段落编号和播放按钮 -->
                <div class="flex items-center gap-2">
                  <span class="text-xs font-semibold text-[#86868b] dark:text-[#98989d] w-5 text-center">{{ index + 1 }}</span>
                  <button
                    @click.stop="playSegment(index)"
                    :disabled="!segment.audioUrl || segment.isGenerating"
                    class="w-7 h-7 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 rounded-full text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0"
                    :class="{ 'bg-[color:var(--brand-primary)]/20 dark:bg-[color:var(--brand-primary-light)]/20 border-[color:var(--brand-primary)]/30 dark:border-[color:var(--brand-primary-light)]/30 text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]': playingSegmentIndex === index && segmentAudioElements[index] && !segmentAudioElements[index].paused }"
                  >
                    <i v-if="segment.isGenerating" class="fas fa-spinner fa-spin text-[10px]"></i>
                    <i v-else-if="playingSegmentIndex === index && segmentAudioElements[index] && !segmentAudioElements[index].paused" class="fas fa-pause text-[10px]"></i>
                    <i v-else class="fas fa-play text-[10px] ml-0.5"></i>
                  </button>
                  <div class="text-xs text-[#86868b] dark:text-[#98989d] flex-shrink-0 font-mono">
                    {{ formatAudioTime(segment.currentTime || 0) }} / {{ formatAudioTime(segment.duration || 0) }}
                  </div>
                </div>
                <!-- 可点击的进度条 -->
                <div
                  @click.stop="handleSegmentProgressClick(index, $event)"
                  class="w-full h-3 bg-black/6 dark:bg-white/15 rounded-full relative overflow-hidden cursor-pointer hover:h-3.5 transition-all duration-200 group"
                  :class="{ 'ring-2 ring-[color:var(--brand-primary)]/50 dark:ring-[color:var(--brand-primary-light)]/50 ring-offset-1': playingSegmentIndex === index && segmentAudioElements[index] && !segmentAudioElements[index].paused }"
                >
                  <div
                    class="h-full bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] rounded-full transition-all duration-100"
                    :style="{ width: segment.duration > 0 ? `${((segment.currentTime || 0) / segment.duration) * 100}%` : '0%' }"
                  ></div>
                  <!-- 悬停时显示时间提示 -->
                  <div class="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                    <span class="text-[10px] text-[#1d1d1f] dark:text-[#f5f5f7] font-medium bg-white/95 dark:bg-[#2c2c2e]/95 px-2 py-1 rounded shadow-sm">
                      {{ segment.duration > 0 ? formatAudioTime(segment.duration) : '--:--' }}
                    </span>
                  </div>
                </div>
                <audio
                  v-if="segment.audioUrl"
                  :ref="el => { if (el) segmentAudioElements[index] = el }"
                  :src="segment.audioUrl"
                  @loadedmetadata="() => onSegmentAudioLoaded(index)"
                  @timeupdate="() => onSegmentTimeUpdate(index)"
                  @ended="() => onSegmentAudioEnded(index)"
                  class="hidden"
                ></audio>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 固定区域:音频播放器和设置面板 - Apple 极简风格 -->
      <div v-if="!isMultiSegmentMode && (audioUrl || selectedVoice)" class="flex-shrink-0 bg-[#f5f5f7]/30 dark:bg-[#1c1c1e]/30">
        <div class="max-w-5xl mx-auto px-6 py-5">
          <div class="flex flex-col lg:flex-row gap-6 lg:gap-8">
            <!-- 音频播放器卡片 - Apple 风格 -->
            <div v-if="audioUrl || isGenerating" class="flex-1 lg:w-1/2">
              <div class="bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl transition-all duration-200 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_12px_rgba(0,0,0,0.08)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.2)] p-4">
                <div class="relative flex items-center mb-3">
                  <!-- 头像容器 -->
                  <div class="relative mr-3 flex-shrink-0">
                    <!-- 透明白色头像 -->
                    <div class="w-12 h-12 rounded-full bg-white/40 dark:bg-white/20 border border-white/30 dark:border-white/20 transition-all duration-200"></div>
                    <!-- Loading 指示器 - Apple 风格 -->
                    <div v-if="isGenerating" class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 bg-[color:var(--brand-primary)]/90 dark:bg-[color:var(--brand-primary-light)]/90 rounded-full flex items-center justify-center text-white z-20">
                      <i class="fas fa-spinner fa-spin text-xs"></i>
                    </div>
                    <!-- 播放/暂停按钮 -->
                    <button
                      v-else
                      @click="toggleAudioPlayback"
                      class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 bg-[color:var(--brand-primary)]/90 dark:bg-[color:var(--brand-primary-light)]/90 rounded-full flex items-center justify-center text-white cursor-pointer hover:scale-110 transition-all duration-200 z-20 shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.3)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.4)]"
                    >
                      <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'" class="text-xs ml-0.5"></i>
                    </button>
                  </div>

                  <!-- 音频信息 -->
                  <div class="flex-1 min-w-0">
                    <div class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight truncate">
                      {{ t('synthesizedAudio') }}<span v-if="selectedVoiceData"> - {{ selectedVoiceData.name }}</span>
                    </div>
                  </div>

                  <!-- 音频时长 -->
                  <div class="text-xs font-medium text-[#86868b] dark:text-[#98989d] tracking-tight flex-shrink-0">
                    {{ formatAudioTime(currentTime) }} / {{ formatAudioTime(audioDuration) }}
                  </div>
                </div>

                <!-- 进度条 -->
                <div class="flex items-center gap-2" v-if="audioDuration > 0">
                  <input
                    type="range"
                    :min="0"
                    :max="audioDuration"
                    :value="currentTime"
                    @input="onProgressChange"
                    @change="onProgressChange"
                    @mousedown="isDragging = true"
                    @mouseup="onProgressEnd"
                    @touchstart="isDragging = true"
                    @touchend="onProgressEnd"
                    class="flex-1 h-1 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                  />
                </div>
              </div>
              <!-- 隐藏的音频元素 -->
              <audio
                v-if="audioUrl"
                ref="audioElement"
                :src="audioUrl"
                @loadedmetadata="onAudioLoaded"
                @timeupdate="onTimeUpdate"
                @ended="onAudioEnded"
                @play="isPlaying = true"
                @pause="isPlaying = false"
                class="hidden"
              ></audio>
            </div>

            <!-- 设置面板 - Apple 极简风格(无卡片,直接显示) -->
            <div v-if="selectedVoice" class="flex-shrink-0 lg:w-1/2">
              <div class="space-y-3">
                <!-- 语速控制 -->
                <div class="flex items-center gap-3">
                  <label class="text-xs font-medium text-[#86868b] dark:text-[#98989d] w-14 tracking-tight">{{ t('speechRate') }}</label>
                  <input
                    type="range"
                    min="-50"
                    max="100"
                    v-model="speechRate"
                    class="flex-1 h-0.5 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3.5 [&::-webkit-slider-thumb]:h-3.5 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                  />
                  <span class="text-xs font-medium text-[#1d1d1f] dark:text-[#f5f5f7] w-12 text-right tracking-tight">{{ getSpeechRateDisplayValue(speechRate) }}</span>
                </div>
                <!-- 音量控制 -->
                <div class="flex items-center gap-3">
                  <label class="text-xs font-medium text-[#86868b] dark:text-[#98989d] w-14 tracking-tight">{{ t('volume') }}</label>
                  <input
                    type="range"
                    min="-50"
                    max="100"
                    v-model="loudnessRate"
                    class="flex-1 h-0.5 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3.5 [&::-webkit-slider-thumb]:h-3.5 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                  />
                  <span class="text-xs font-medium text-[#1d1d1f] dark:text-[#f5f5f7] w-12 text-right tracking-tight">{{ getLoudnessDisplayValue(loudnessRate) }}</span>
                </div>
                <!-- 音调控制 -->
                <div class="flex items-center gap-3">
                  <label class="text-xs font-medium text-[#86868b] dark:text-[#98989d] w-14 tracking-tight">{{ t('pitch') }}</label>
                  <input
                    type="range"
                    min="-12"
                    max="12"
                    v-model="pitch"
                    class="flex-1 h-0.5 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3.5 [&::-webkit-slider-thumb]:h-3.5 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                  />
                  <span class="text-xs font-medium text-[#1d1d1f] dark:text-[#f5f5f7] w-12 text-right tracking-tight">{{ getPitchDisplayValue(pitch) }}</span>
                </div>
                <!-- 情感控制 - 仅当音色支持时显示 -->
                <div v-if="selectedVoiceData && selectedVoiceData.emotions && selectedVoiceData.emotions.length > 0" class="flex items-center gap-3">
                  <label class="text-xs font-medium text-[#86868b] dark:text-[#98989d] w-14 tracking-tight">{{ t('emotionIntensity') }}</label>
                  <input
                    type="range"
                    min="1"
                    max="5"
                    v-model="emotionScale"
                    class="flex-1 h-0.5 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3.5 [&::-webkit-slider-thumb]:h-3.5 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                  />
                  <span class="text-xs font-medium text-[#1d1d1f] dark:text-[#f5f5f7] w-12 text-right tracking-tight">{{ emotionScale }}</span>
                </div>
                <div v-if="selectedVoiceData && selectedVoiceData.emotions && selectedVoiceData.emotions.length > 0" class="flex items-center gap-3">
                  <label class="text-xs font-medium text-[#86868b] dark:text-[#98989d] w-14 tracking-tight">{{ t('emotionType') }}</label>
                  <div class="flex-1">
                    <DropdownMenu
                      :items="emotionItems"
                      :selected-value="selectedEmotion"
                      :placeholder="t('neutral')"
                      @select-item="handleEmotionSelect"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 装饰性分割线 - Apple 风格(带V形图标) -->
        <div class="relative flex items-center justify-center py-3">
          <!-- 左侧线条 -->
          <div class="flex-1 h-px bg-gradient-to-r from-transparent via-black/20 dark:via-white/20 to-black/20 dark:to-white/20"></div>
          <!-- 中间V形图标 -->
          <div class="mx-4 flex items-center justify-center w-6 h-6 rounded-full bg-white/60 dark:bg-[#2c2c2e]/60 border border-black/10 dark:border-white/10">
            <i class="fas fa-chevron-down text-[8px] text-[#86868b] dark:text-[#98989d]"></i>
          </div>
          <!-- 右侧线条 -->
          <div class="flex-1 h-px bg-gradient-to-l from-transparent via-black/20 dark:via-white/20 to-black/20 dark:to-white/20"></div>
        </div>
      </div>

      <!-- 模态框内容 - Apple 风格(可滚动区域) -->
      <div class="flex-1 overflow-y-auto p-6 main-scrollbar">
        <div class="max-w-5xl mx-auto space-y-6">
          <!-- 多段模式输入区域 -->
          <template v-if="isMultiSegmentMode">
            <!-- 分割线 - 音频预览和段落输入区域之间 -->
            <div v-if="isMultiSegmentMode && audioSegments.length > 0" class="relative flex items-center justify-center py-3">
              <!-- 左侧线条 -->
              <div class="flex-1 h-px bg-gradient-to-r from-transparent via-black/20 dark:via-white/20 to-black/20 dark:to-white/20"></div>
              <!-- 中间V形图标 -->
              <div class="mx-4 flex items-center justify-center w-6 h-6 rounded-full bg-white/60 dark:bg-[#2c2c2e]/60 border border-black/10 dark:border-white/10">
                <i class="fas fa-chevron-down text-[8px] text-[#86868b] dark:text-[#98989d]"></i>
              </div>
              <!-- 右侧线条 -->
              <div class="flex-1 h-px bg-gradient-to-l from-transparent via-black/20 dark:via-white/20 to-black/20 dark:to-white/20"></div>
            </div>
            <!-- 添加段落按钮 -->
            <button
              @click="addSegment"
              class="w-full py-4 bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 border-dashed rounded-xl text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] transition-all duration-200 flex items-center justify-center gap-2 mb-6"
            >
              <i class="fas fa-plus text-sm"></i>
              <span class="text-sm font-medium">{{ t('tts.addSegment') }}</span>
            </button>
            <div
              v-for="(item, reversedIndex) in reversedSegments"
              :key="item.segment.id"
              class="space-y-4"
            >
              <div
                class="bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl p-4 transition-all duration-200"
                :class="{
                  'opacity-50 scale-95': draggingSegmentIndex === item.originalIndex,
                  'border-[color:var(--brand-primary)]/50 dark:border-[color:var(--brand-primary-light)]/50 ring-2 ring-[color:var(--brand-primary)]/20 dark:ring-[color:var(--brand-primary-light)]/20': dragOverSegmentIndex === item.originalIndex && draggingSegmentIndex !== item.originalIndex
                }"
                :draggable="audioSegments.length > 1"
                @dragstart="handleDragStart(item.originalIndex, $event)"
                @dragend="handleDragEnd"
                @dragover.prevent="handleDragOver(item.originalIndex, $event)"
                @dragleave="handleDragLeave(item.originalIndex)"
                @drop="handleDrop(item.originalIndex, $event)"
                style="position: relative; overflow: visible;"
              >
                <div class="flex items-center gap-3 mb-3">
                  <!-- 拖拽手柄 -->
                  <div
                    v-if="audioSegments.length > 1"
                    class="cursor-move text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] transition-colors"
                    :title="t('dragToReorder')"
                  >
                    <i class="fas fa-grip-vertical text-sm"></i>
                  </div>
                  <span class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7]">{{ t('tts.segmentNumber', { index: item.originalIndex + 1 }) }}</span>
                  <button
                    @click="copySegment(item.originalIndex, $event)"
                    class="w-8 h-8 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] rounded-full transition-all duration-200"
                    :title="t('tts.copySegment')"
                  >
                    <i class="fas fa-copy text-xs"></i>
                  </button>
                  <button
                    v-if="audioSegments.length > 1"
                    @click="removeSegment(item.originalIndex)"
                    class="w-8 h-8 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-red-500 dark:text-red-400 rounded-full hover:bg-red-50 dark:hover:bg-red-500/10 transition-all duration-200"
                    :title="t('tts.deleteSegment')"
                  >
                    <i class="fas fa-trash text-xs"></i>
                  </button>
                  <div class="flex-1"></div>
                  <div
                    class="relative voice-selector-container"
                    :data-segment-index="item.originalIndex"
                    :ref="el => setSegmentVoiceSelectorRef(item.originalIndex, el)"
                  >
                    <button
                      @click.stop="selectVoiceForSegment(item.originalIndex)"
                      class="flex items-center gap-2 px-4 py-2 bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 rounded-lg text-sm text-[#1d1d1f] dark:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] transition-all duration-200 whitespace-nowrap"
                    >
                      <!-- 头像显示 -->
                      <div v-if="item.segment.voiceData" class="relative flex-shrink-0">
                        <img
                          v-if="isFemaleVoice(item.segment.voiceData.voice_type)"
                          src="../../public/female.svg"
                          alt="Female Avatar"
                          class="w-6 h-6 rounded-full object-cover bg-white"
                        />
                        <img
                          v-else
                          src="../../public/male.svg"
                          alt="Male Avatar"
                          class="w-6 h-6 rounded-full object-cover bg-white"
                        />
                      </div>
                      <span>{{ item.segment.voiceData?.name || t('tts.selectVoice') }}</span>
                    </button>
                  </div>
                  <!-- 调节按钮 -->
                  <button
                    @click.stop="toggleSegmentSettings(item.originalIndex)"
                    class="w-8 h-8 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] rounded-full transition-all duration-200"
                    :title="t('tts.adjustSettings')"
                    :class="{ 'bg-[color:var(--brand-primary)]/20 dark:bg-[color:var(--brand-primary-light)]/20 border-[color:var(--brand-primary)]/30 dark:border-[color:var(--brand-primary-light)]/30 text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]': showSegmentSettings === item.originalIndex }"
                  >
                    <i class="fas fa-sliders-h text-xs"></i>
                  </button>
                  <button
                    @click="handleSegmentGenerateOrPlay(item.originalIndex)"
                    :disabled="!item.segment.text.trim() || !item.segment.voice || item.segment.isGenerating"
                    class="w-10 h-10 flex items-center justify-center bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white rounded-full hover:scale-110 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"
                    :title="item.segment.isGenerating ? t('tts.generating') : (item.segment.audioUrl ? (playingSegmentIndex === item.originalIndex && segmentAudioElements[item.originalIndex] && !segmentAudioElements[item.originalIndex].paused ? '暂停' : '播放') : t('tts.generate'))"
                  >
                    <i v-if="item.segment.isGenerating" class="fas fa-spinner fa-spin text-sm"></i>
                    <i v-else-if="item.segment.audioUrl && playingSegmentIndex === item.originalIndex && segmentAudioElements[item.originalIndex] && !segmentAudioElements[item.originalIndex].paused" class="fas fa-pause text-sm"></i>
                    <i v-else class="fas fa-play text-sm"></i>
                  </button>
                </div>
                <!-- 文本输入区域 -->
                <div class="mb-3">
                  <label class="block text-xs text-[#86868b] dark:text-[#98989d] mb-1.5">{{ t('tts.text') }}</label>
                  <textarea
                    v-model="item.segment.text"
                    :placeholder="t('tts.placeholder')"
                    class="w-full bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-lg px-4 py-3 text-sm text-[#1d1d1f] dark:text-[#f5f5f7] placeholder-[#86868b] dark:placeholder-[#98989d] focus:outline-none focus:border-[color:var(--brand-primary)]/50 dark:focus:border-[color:var(--brand-primary-light)]/60 transition-all duration-200 resize-none"
                    rows="2"
                  ></textarea>
                </div>
                <!-- 语音指令输入仅2.0音色显示 -->
                <div v-if="item.segment.voiceData?.version === '2.0'" class="mt-3">
                  <label class="block text-xs text-[#86868b] dark:text-[#98989d] mb-1.5">{{ t('tts.voiceInstructionOptional') }}</label>
                  <textarea
                    v-model="item.segment.contextText"
                    :placeholder="t('tts.voiceInstructionPlaceholder')"
                    class="w-full bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-lg px-4 py-2 text-sm text-[#1d1d1f] dark:text-[#f5f5f7] placeholder-[#86868b] dark:placeholder-[#98989d] focus:outline-none focus:border-[color:var(--brand-primary)]/50 dark:focus:border-[color:var(--brand-primary-light)]/60 transition-all duration-200 resize-none"
                    rows="2"
                  ></textarea>
                </div>
                <!-- 设置面板 -->
                <div v-if="showSegmentSettings === item.originalIndex" class="mt-3 p-4 bg-white/50 dark:bg-[#2c2c2e]/50 backdrop-blur-[10px] border border-black/6 dark:border-white/6 rounded-xl space-y-3">
                  <!-- 语速控制 -->
                  <div class="flex items-center gap-3">
                    <label class="text-xs font-medium text-[#86868b] dark:text-[#98989d] w-14 tracking-tight">{{ t('speechRate') }}</label>
                    <input
                      type="range"
                      min="-50"
                      max="100"
                      v-model.number="item.segment.speechRate"
                      class="flex-1 h-0.5 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3.5 [&::-webkit-slider-thumb]:h-3.5 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                    />
                    <span class="text-xs font-medium text-[#1d1d1f] dark:text-[#f5f5f7] w-12 text-right tracking-tight">{{ getSpeechRateDisplayValue(item.segment.speechRate || 0) }}</span>
                  </div>
                  <!-- 音量控制 -->
                  <div class="flex items-center gap-3">
                    <label class="text-xs font-medium text-[#86868b] dark:text-[#98989d] w-14 tracking-tight">{{ t('volume') }}</label>
                    <input
                      type="range"
                      min="-50"
                      max="100"
                      v-model.number="item.segment.loudnessRate"
                      class="flex-1 h-0.5 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3.5 [&::-webkit-slider-thumb]:h-3.5 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                    />
                    <span class="text-xs font-medium text-[#1d1d1f] dark:text-[#f5f5f7] w-12 text-right tracking-tight">{{ getLoudnessDisplayValue(item.segment.loudnessRate || 0) }}</span>
                  </div>
                  <!-- 音调控制 -->
                  <div class="flex items-center gap-3">
                    <label class="text-xs font-medium text-[#86868b] dark:text-[#98989d] w-14 tracking-tight">{{ t('pitch') }}</label>
                    <input
                      type="range"
                      min="-12"
                      max="12"
                      v-model.number="item.segment.pitch"
                      class="flex-1 h-0.5 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3.5 [&::-webkit-slider-thumb]:h-3.5 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                    />
                    <span class="text-xs font-medium text-[#1d1d1f] dark:text-[#f5f5f7] w-12 text-right tracking-tight">{{ getPitchDisplayValue(item.segment.pitch || 0) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- 单段模式输入区域 - Apple 风格 -->
          <template v-else>
            <!-- 文本输入区域 - Apple 风格 -->
            <div>
              <div class="flex items-center justify-between mb-3">
                <div class="flex items-center gap-2">
                  <i class="fas fa-keyboard text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
                  <span class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight">{{ t('enterTextToConvert') }}</span>

                  <button
                    @click="openTextHistoryPanel"
                    class="w-8 h-8 flex items-center justify-center rounded-full bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] transition-all duration-200"
                    :title="t('ttsHistoryTabText')"
                  >
                    <i class="fas fa-history text-xs"></i>
                  </button>
                </div>
              </div>
              <textarea
                v-model="inputText"
                :placeholder="t('tts.placeholder')"
                class="w-full bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl px-5 py-4 text-[15px] text-[#1d1d1f] dark:text-[#f5f5f7] placeholder-[#86868b] dark:placeholder-[#98989d] tracking-tight hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 focus:outline-none focus:border-[color:var(--brand-primary)]/50 dark:focus:border-[color:var(--brand-primary-light)]/60 focus:shadow-[0_4px_16px_rgba(var(--brand-primary-rgb),0.12)] dark:focus:shadow-[0_4px_16px_rgba(var(--brand-primary-light-rgb),0.2)] transition-all duration-200 resize-none min-h-[100px]"
                rows="4"
              ></textarea>
            </div>

            <!-- 语音指令区域 - Apple 风格 -->
            <div>
              <div class="flex items-center justify-between mb-3">
                <div class="flex items-center gap-2">
                  <i class="fas fa-magic text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
                  <span class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight">{{ t('voiceInstruction') }}</span>
                  <span class="text-xs text-[#86868b] dark:text-[#98989d]">{{ t('voiceInstructionHint') }}</span>

                  <button
                    @click="openInstructionHistoryPanel"
                    class="w-8 h-8 flex items-center justify-center rounded-full bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] transition-all duration-200"
                    :title="t('ttsHistoryTabInstruction')"
                  >
                    <i class="fas fa-history text-xs"></i>
                  </button>
                </div>
              </div>
              <textarea
                v-model="contextText"
                :placeholder="t('voiceInstructionPlaceholder')"
                class="w-full bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl px-5 py-3 text-[15px] text-[#1d1d1f] dark:text-[#f5f5f7] placeholder-[#86868b] dark:placeholder-[#98989d] tracking-tight hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 focus:outline-none focus:border-[color:var(--brand-primary)]/50 dark:focus:border-[color:var(--brand-primary-light)]/60 focus:shadow-[0_4px_16px_rgba(var(--brand-primary-rgb),0.12)] dark:focus:shadow-[0_4px_16px_rgba(var(--brand-primary-light-rgb),0.2)] transition-all duration-200 resize-none"
                rows="3"
              ></textarea>
            </div>

            <!-- 音色选择区域 - 使用复用组件 -->
            <VoiceSelectorPanel
              :filtered-voices="filteredVoices"
              :cloned-voices="clonedVoices"
              :selected-voice="selectedVoice"
              :is-generating="isGenerating"
              :search-query="searchQuery"
              :initial-tab="voiceTab"
              :show-history-button="true"
              :show-delete-button="true"
              search-box-width="w-52"
              :is-female-voice="isFemaleVoice"
              :get-language-display-name="getLanguageDisplayName"
              :format-date="formatDate"
              :t="t"
              @select-voice="onVoiceSelect"
              @select-clone-voice="onCloneVoiceSelect"
              @open-clone-modal="openCloneModal"
              @delete-clone-voice="handleDeleteVoiceClone"
              @open-history="openVoiceHistoryPanel"
              @toggle-filter="toggleFilterPanel"
              @update:searchQuery="searchQuery = $event"
              @update:tab="voiceTab = $event"
            />
          </template>
        </div>
      </div>
    </div>
  </div>

  <!-- 音色克隆Modal -->
  <VoiceCloneModal
    v-if="showCloneModal"
    @close="closeCloneModal"
    @saved="handleVoiceCloneSaved"
  />

  <!-- Confirm Dialog -->
  <Confirm />

  <!-- 合并音频元素 - 放在模态框最外层确保 ref 始终绑定 -->
  <audio
    ref="mergedAudioElement"
    :src="mergedAudioUrl"
    @loadedmetadata="onMergedAudioLoaded"
    @timeupdate="onMergedTimeUpdate"
    @ended="onMergedAudioEnded"
    @play="isPlayingMerged = true"
    @pause="isPlayingMerged = false"
    class="hidden"
  ></audio>

  <VoiceTtsHistoryPanel
    :visible="showHistoryPanel"
    :history="ttsHistory"
    mode="combined"
    :get-voice-name="getHistoryVoiceName"
    @close="closeHistoryPanel"
    @apply="applyCombinedHistoryEntry"
    @delete="handleDeleteHistoryEntry"
  />

  <VoiceTtsHistoryPanel
    :visible="showTextHistoryPanel"
    :history="ttsHistory"
    mode="text"
    @close="closeTextHistoryPanel"
    @apply="applyTextHistoryEntry"
  />

  <VoiceTtsHistoryPanel
    :visible="showInstructionHistoryPanel"
    :history="ttsHistory"
    mode="instruction"
    @close="closeInstructionHistoryPanel"
    @apply="applyInstructionHistoryEntry"
  />

  <VoiceTtsHistoryPanel
    :visible="showVoiceHistoryPanel"
    :history="ttsHistory"
    mode="voice"
    :get-voice-name="getHistoryVoiceName"
    @close="closeVoiceHistoryPanel"
    @apply="applyVoiceHistoryEntry"
  />

  <!-- 音色选择下拉菜单 - 直接在组件内渲染使用固定定位 -->
  <!-- 段落音色选择面板 - Apple 风格 -->
  <div v-if="showVoiceSelector && selectedSegmentIndex >= 0 && audioSegments && audioSegments[selectedSegmentIndex]" class="fixed inset-0 bg-black/50 dark:bg-black/60 backdrop-blur-sm z-[100] flex items-center justify-center p-4" @click="closeSegmentVoiceSelector">
    <div class="bg-white/95 dark:bg-[#1e1e1e]/95 backdrop-blur-[40px] backdrop-saturate-[180%] border border-black/10 dark:border-white/10 rounded-3xl w-full max-w-4xl max-h-[85vh] overflow-hidden shadow-[0_20px_60px_rgba(0,0,0,0.2)] dark:shadow-[0_20px_60px_rgba(0,0,0,0.6)] flex flex-col" @click.stop>
      <!-- 面板头部 - Apple 风格 -->
      <div class="flex items-center justify-between px-6 py-4 border-b border-black/8 dark:border-white/8 bg-white/50 dark:bg-[#1e1e1e]/50 backdrop-blur-[20px] flex-shrink-0">
        <h3 class="text-lg font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] flex items-center gap-2 tracking-tight">
          <i class="fas fa-microphone-alt text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
          <span>{{ t('selectVoice') }}</span>
        </h3>
        <button @click="closeSegmentVoiceSelector"
          class="w-9 h-9 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] rounded-full transition-all duration-200 hover:scale-110 active:scale-100">
          <i class="fas fa-times text-sm"></i>
        </button>
      </div>

      <!-- 面板内容 -->
      <div class="flex-1 overflow-y-auto p-6 main-scrollbar">
        <VoiceSelectorPanel
          :filtered-voices="segmentFilteredVoices"
          :cloned-voices="clonedVoices"
          :selected-voice="getSegmentSelectedVoice()"
          :is-generating="audioSegments[selectedSegmentIndex]?.isGenerating || false"
          :search-query="segmentSearchQuery"
          :initial-tab="segmentVoiceTab"
          :show-history-button="false"
          :show-delete-button="false"
          search-box-width="flex-1 max-w-xs"
          :is-female-voice="isFemaleVoice"
          :get-language-display-name="getLanguageDisplayName"
          :format-date="formatDate"
          :t="t"
          @select-voice="onVoiceSelectForSegment"
          @select-clone-voice="onCloneVoiceSelectForSegment"
          @open-clone-modal="openCloneModal"
          @toggle-filter="toggleFilterPanel"
          @update:searchQuery="segmentSearchQuery = $event"
          @update:tab="segmentVoiceTab = $event"
        />
      </div>
    </div>
  </div>

  <!-- 筛选面板遮罩 - Apple 风格 -->
  <div v-if="showFilterPanel" class="fixed inset-0 bg-black/50 dark:bg-black/60 backdrop-blur-sm z-[100] flex items-center justify-center p-4" @click="closeFilterPanel">
    <div class="bg-white/95 dark:bg-[#1e1e1e]/95 backdrop-blur-[40px] backdrop-saturate-[180%] border border-black/10 dark:border-white/10 rounded-3xl w-full max-w-2xl max-h-[85vh] overflow-hidden shadow-[0_20px_60px_rgba(0,0,0,0.2)] dark:shadow-[0_20px_60px_rgba(0,0,0,0.6)] flex flex-col" @click.stop>
      <!-- 筛选面板头部 - Apple 风格 -->
      <div class="flex items-center justify-between px-6 py-4 border-b border-black/8 dark:border-white/8 bg-white/50 dark:bg-[#1e1e1e]/50 backdrop-blur-[20px]">
        <h3 class="text-lg font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] flex items-center gap-2 tracking-tight">
          <i class="fas fa-filter text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
          <span>{{ t('filterVoices') }}</span>
        </h3>
        <button @click="closeFilterPanel"
          class="w-9 h-9 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] rounded-full transition-all duration-200 hover:scale-110 active:scale-100">
          <i class="fas fa-times text-sm"></i>
        </button>
      </div>

      <!-- 筛选内容 - Apple 风格 -->
      <div class="flex-1 overflow-y-auto p-6 main-scrollbar">
        <div class="space-y-6">
          <!-- 场景筛选 -->
          <div>
            <h4 class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] mb-3 tracking-tight">{{ t('scene') }}</h4>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="category in categories"
                :key="category"
                @click="selectCategory(category)"
                class="px-4 py-2 text-sm font-medium rounded-full transition-all duration-200 tracking-tight"
                :class="selectedCategory === category
                  ? 'bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.25)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.3)]'
                  : 'bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:bg-white dark:hover:bg-[#3a3a3c] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7]'"
              >
                {{ translateCategory(category) }}
              </button>
            </div>
          </div>

          <!-- 版本筛选 -->
          <div>
            <h4 class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] mb-3 tracking-tight">{{ t('version') }}</h4>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="v in version"
                :key="v"
                @click="selectVersion(v)"
                class="px-4 py-2 text-sm font-medium rounded-full transition-all duration-200 tracking-tight"
                :class="selectedVersion === v
                  ? 'bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.25)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.3)]'
                  : 'bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:bg-white dark:hover:bg-[#3a3a3c] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7]'"
              >
                {{ translateVersion(v) }}
              </button>
            </div>
          </div>

          <!-- 语言筛选 -->
          <div>
            <h4 class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] mb-3 tracking-tight">{{ t('language') }}</h4>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="lang in languages"
                :key="lang"
                @click="selectLanguage(lang)"
                class="px-4 py-2 text-sm font-medium rounded-full transition-all duration-200 tracking-tight"
                :class="selectedLanguage === lang
                  ? 'bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.25)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.3)]'
                  : 'bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:bg-white dark:hover:bg-[#3a3a3c] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7]'"
              >
                {{ translateLanguage(lang) }}
              </button>
            </div>
          </div>

          <!-- 性别筛选 -->
          <div>
            <h4 class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] mb-3 tracking-tight">{{ t('gender') }}</h4>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="gender in genders"
                :key="gender"
                @click="selectGender(gender)"
                class="px-4 py-2 text-sm font-medium rounded-full transition-all duration-200 tracking-tight"
                :class="selectedGender === gender
                  ? 'bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.25)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.3)]'
                  : 'bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:bg-white dark:hover:bg-[#3a3a3c] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7]'"
              >
                {{ translateGender(gender) }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选操作按钮 - Apple 风格 -->
      <div class="flex gap-3 px-6 py-4 border-t border-black/8 dark:border-white/8 bg-white/50 dark:bg-[#1e1e1e]/50 backdrop-blur-[20px]">
        <button @click="resetFilters"
          class="flex-1 px-5 py-3 bg-white dark:bg-[#3a3a3c] border border-black/8 dark:border-white/8 text-[#1d1d1f] dark:text-[#f5f5f7] rounded-full transition-all duration-200 font-medium text-[15px] tracking-tight hover:bg-white/80 dark:hover:bg-[#3a3a3c]/80 hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.3)] active:scale-[0.98]">
          {{ t('reset') }}
        </button>
        <button @click="applyFilters"
          class="flex-1 px-5 py-3 bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white rounded-full transition-all duration-200 font-semibold text-[15px] tracking-tight hover:scale-[1.02] hover:shadow-[0_8px_24px_rgba(var(--brand-primary-rgb),0.35)] dark:hover:shadow-[0_8px_24px_rgba(var(--brand-primary-light-rgb),0.4)] active:scale-100">
          {{ t('done') }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import DropdownMenu from './DropdownMenu.vue'
import VoiceTtsHistoryPanel from './VoiceTtsHistoryPanel.vue'
import VoiceCloneModal from './VoiceCloneModal.vue'
import Confirm from './Confirm.vue'
import { ttsHistory, loadTtsHistory, addTtsHistoryEntry, removeTtsHistoryEntry, showConfirmDialog, showAlert } from '../utils/other'
import VoiceSelector from './VoiceSelector.vue'
import VoiceSelectorPanel from './VoiceSelectorPanel.vue'

export default {
  name: 'VoiceTTS',
  components: {
    DropdownMenu,
    VoiceTtsHistoryPanel,
    VoiceCloneModal,
    Confirm,
    VoiceSelector,
    VoiceSelectorPanel
  },
  emits: ['tts-complete', 'close-modal'],
  setup(props, { emit }) {
    const { t } = useI18n()
    const inputText = ref('')
    const contextText = ref('')
    const selectedVoice = ref('')
    const selectedVoiceResourceId = ref('')
    const searchQuery = ref('')
    const speechRate = ref(0)
    const loudnessRate = ref(0)
    const pitch = ref(0)
    const emotionScale = ref(3)
    const selectedEmotion = ref('neutral')
    const isGenerating = ref(false)
    const audioUrl = ref('')
    const currentAudio = ref(null) // 当前播放的音频对象
    const audioElement = ref(null) // 音频元素引用
    const isPlaying = ref(false) // 播放状态
    const audioDuration = ref(0) // 音频总时长
    const currentTime = ref(0) // 当前播放时间
    const shouldAutoPlay = ref(false) // 是否需要自动播放
    const isDragging = ref(false) // 是否正在拖拽进度条
    const voices = ref([])
    const emotions = ref([])
    const voiceListContainer = ref(null)
    const voiceSelectorRef = ref(null)
    const showControls = ref(false)
    const showFilterPanel = ref(false)
    const showHistoryPanel = ref(false)
    const showTextHistoryPanel = ref(false)
    const showInstructionHistoryPanel = ref(false)
    const showVoiceHistoryPanel = ref(false)
    const voiceTab = ref('ai') // 'ai' or 'clone'
    const clonedVoices = ref([])
    const showCloneModal = ref(false)
    const cloneVoiceListContainer = ref(null)
    const isCloneVoice = ref(false) // 标记当前选中的是否是克隆音色

    // 多段语音合成模式
    const isMultiSegmentMode = ref(false)
    const audioSegments = ref([]) // 音频段列表 [{ id, text, voice, voiceData, audioUrl, audioBlob, duration, isGenerating }]
    const mergedAudioUrl = ref('') // 合并后的音频URL(已废弃,保留用于兼容)
    const mergedAudioElement = ref(null) // 合并音频元素(已废弃,保留用于兼容)
    const isMerging = ref(false) // 是否正在合并(已废弃,保留用于兼容)
    const isPlayingMerged = ref(false) // 是否正在播放合并音频
    const mergedAudioDuration = ref(0) // 合并音频总时长(所有段的总时长)
    const mergedCurrentTime = ref(0) // 合并音频当前时间(累计时间)
    const segmentStartTimes = ref([]) // 每段的开始时间(累计),用于计算总进度
    const playingSegmentIndex = ref(-1) // 当前播放的段索引
    const segmentAudioElements = ref({}) // 分段音频元素引用
    const showInstructionInput = ref(-1) // 显示语音指令输入的段索引
    const selectedSegmentIndex = ref(-1) // 当前选择音色的段索引
    const showVoiceSelector = ref(false) // 是否显示音色选择器
    const showSegmentSettings = ref(-1) // 显示设置的段索引
    const segmentVoiceSelectors = ref({}) // 分段音色选择器容器引用
    const dropdownStyle = ref({}) // 下拉菜单样式(不包含 display,由 v-show 控制)
    const dropdownContainerRef = ref(null) // 下拉菜单容器 ref
    const segmentVoiceTab = ref('ai') // 段落音色选择标签页 'ai' or 'clone'
    const segmentSearchQuery = ref('') // 段落音色选择搜索查询
    const draggingSegmentIndex = ref(-1) // 正在拖拽的段落索引
    const dragOverSegmentIndex = ref(-1) // 拖拽悬停的段落索引

    // Category filtering - 存储原始中文值
    const selectedCategory = ref('全部场景')
    const categories = ref(['全部场景', '通用场景', '客服场景', '教育场景', '趣味口音', '角色扮演', '有声阅读', '多语种', '多情感', '视频配音'])
    const selectedVersion = ref('全部版本')
    const version = ref(['全部版本', '1.0', '2.0'])
    const selectedLanguage = ref('全部语言')
    const languages = ref(['全部语言'])
    const selectedGender = ref('全部性别')
    const genders = ref(['全部性别'])

    // 翻译映射函数
    const translateCategory = (category) => {
      const map = {
        '全部场景': t('allScenes'),
        '通用场景': t('generalScene'),
        '客服场景': t('customerServiceScene'),
        '教育场景': t('educationScene'),
        '趣味口音': t('funAccent'),
        '角色扮演': t('rolePlaying'),
        '有声阅读': t('audiobook'),
        '多语种': t('multilingual'),
        '多情感': t('multiEmotion'),
        '视频配音': t('videoDubbing')
      }
      return map[category] || category
    }

    const translateVersion = (ver) => {
      return ver === '全部版本' ? t('allVersions') : ver
    }

    const translateLanguage = (lang) => {
      if (lang === '全部语言') return t('allLanguages')

      // 语言名称映射 - 中文到翻译键(如果有的话直接显示)
      // 对于后端返回的中文语言名,直接显示即可,因为它们是通用的
      return lang
    }

    const translateGender = (gender) => {
      const map = {
        '全部性别': t('allGenders'),
        '女性': t('female'),
        '男性': t('male')
      }
      return map[gender] || gender
    }

    const openHistoryPanel = () => {
      loadTtsHistory()
      showHistoryPanel.value = true
    }

    const closeHistoryPanel = () => {
      showHistoryPanel.value = false
    }

    const openTextHistoryPanel = () => {
      loadTtsHistory()
      showTextHistoryPanel.value = true
    }

    const openInstructionHistoryPanel = () => {
      loadTtsHistory()
      showInstructionHistoryPanel.value = true
    }

    const openVoiceHistoryPanel = () => {
      loadTtsHistory()
      showVoiceHistoryPanel.value = true
    }

    const closeTextHistoryPanel = () => {
      showTextHistoryPanel.value = false
    }

    const closeInstructionHistoryPanel = () => {
      showInstructionHistoryPanel.value = false
    }

    const closeVoiceHistoryPanel = () => {
      showVoiceHistoryPanel.value = false
    }

    const handleDeleteHistoryEntry = (entry) => {
      if (!entry?.id) return
      removeTtsHistoryEntry(entry.id)
      loadTtsHistory()
    }


    // Load voices data
    onMounted(async () => {
      document.addEventListener('click', handleClickOutside)
      loadTtsHistory()
      loadClonedVoices()
      try {
        const response = await fetch('/api/v1/voices/list')
        const data = await response.json()
        console.log('音色数据', data)
        voices.value = data.voices || []
        emotions.value = data.emotions || []

        // Map languages data to language options
        if (data.languages && Array.isArray(data.languages)) {
          const languageOptions = ['全部语言']
          data.languages.forEach(lang => {
            languageOptions.push(lang.zh) // Use Chinese name
          })
          languages.value = languageOptions
        }

        // Extract gender options from voices data
        if (voices.value && voices.value.length > 0) {
          const genderSet = new Set()
          voices.value.forEach(voice => {
            if (voice.gender) {
              genderSet.add(voice.gender)
            }
          })

          const genderOptions = ['全部性别']
          // Convert English gender to localized display - 保留中文作为内部值
          genderSet.forEach(gender => {
            if (gender === 'female') {
              genderOptions.push('女性')
            } else if (gender === 'male') {
              genderOptions.push('男性')
            } else {
              // For any other gender values, use as is
              genderOptions.push(gender)
            }
          })
          genders.value = genderOptions
        }
      } catch (error) {
        console.error('Failed to load voices:', error)
      }
    })

    // 组件卸载时清理音频资源
    onUnmounted(() => {
      if (currentAudio.value) {
        currentAudio.value.pause()
        currentAudio.value = null
      }
      // 清理音频URL
      if (audioUrl.value) {
        URL.revokeObjectURL(audioUrl.value)
      }
    })

    // 监听参数变化,自动重新生成音频
    watch([speechRate, loudnessRate, pitch, emotionScale, selectedEmotion], () => {
      if (selectedVoice.value && inputText.value.trim() && !isGenerating.value) {
        generateTTS()
      }
    })

    // 监听文本输入变化,使用防抖避免频繁生成
    let textTimeout = null
    watch([inputText, contextText], () => {
      if (textTimeout) {
        clearTimeout(textTimeout)
      }
      textTimeout = setTimeout(() => {
        if (selectedVoice.value && inputText.value.trim() && !isGenerating.value) {
          generateTTS()
        }
      }, 800) // 延迟800ms执行,给用户足够时间输入
    })

    // 监听搜索查询变化,重置滚动位置(延迟执行以避免频繁重置)
    let searchTimeout = null
    watch(searchQuery, () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }
      searchTimeout = setTimeout(() => {
        resetScrollPosition()
      }, 300) // 延迟300ms执行
    })

    // 重置滚动位置
    const resetScrollPosition = () => {
      // 单段模式:直接使用 voiceListContainer
      if (voiceListContainer.value) {
        voiceListContainer.value.scrollTop = 0
      }
      // 多段模式:如果使用 VoiceSelector 组件,通过 ref 访问
      if (voiceSelectorRef.value && voiceSelectorRef.value.voiceListContainer) {
        voiceSelectorRef.value.voiceListContainer.scrollTop = 0
      }
    }

    // Filter voices based on search query, category, version, language, and gender
    const filteredVoices = computed(() => {
      let filtered = [...voices.value] // 创建副本,避免修改原始数据

      console.log('原始音色数据:', voices.value.length)
      console.log('筛选条件:', {
        category: selectedCategory.value,
        version: selectedVersion.value,
        language: selectedLanguage.value,
        gender: selectedGender.value,
        search: searchQuery.value
      })

      // Filter by category
      if (selectedCategory.value !== '全部场景') {
        filtered = filtered.filter(voice => voice.scene === selectedCategory.value)
        console.log('分类筛选后:', filtered.length)
      }

      // Filter by version
      if (selectedVersion.value !== '全部版本') {
        filtered = filtered.filter(voice => voice.version === selectedVersion.value)
        console.log('版本筛选后:', filtered.length)
      }

      // Filter by language
      if (selectedLanguage.value !== '全部语言') {
        // Convert Chinese language display back to language code for filtering
        let languageFilter = selectedLanguage.value
        // Create a mapping from Chinese names to language codes
        const languageMap = {
          '中文': 'chinese',
          '美式英语': 'en_us',
          '英式英语': 'en_gb',
          '澳洲英语': 'en_au',
          '西语': 'es',
          '日语': 'ja'
        }

        if (languageMap[selectedLanguage.value]) {
          languageFilter = languageMap[selectedLanguage.value]
        }

        filtered = filtered.filter(voice => {
          // Check if voice.language array contains the language code
          return voice.language && Array.isArray(voice.language) && voice.language.includes(languageFilter)
        })
        console.log('语言筛选后:', filtered.length)
      }

      // Filter by gender
      if (selectedGender.value !== '全部性别') {
        // Convert Chinese gender display back to English for filtering
        let genderFilter = selectedGender.value
        if (selectedGender.value === '女性') {
          genderFilter = 'female'
        } else if (selectedGender.value === '男性') {
          genderFilter = 'male'
        }

        filtered = filtered.filter(voice => voice.gender === genderFilter)
        console.log('性别筛选后:', filtered.length)
      }

      // Filter by search query
      if (searchQuery.value) {
        filtered = filtered.filter(voice =>
          voice.name.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
        console.log('搜索筛选后:', filtered.length)
      }

      console.log('最终筛选结果:', filtered.length)
      return filtered
    })

    // 段落音色选择的筛选音色列表
    const segmentFilteredVoices = computed(() => {
      let filtered = [...voices.value] // 创建副本,避免修改原始数据

      // Filter by category
      if (selectedCategory.value !== '全部场景') {
        filtered = filtered.filter(voice => voice.scene === selectedCategory.value)
      }

      // Filter by version
      if (selectedVersion.value !== '全部版本') {
        filtered = filtered.filter(voice => voice.version === selectedVersion.value)
      }

      // Filter by language
      if (selectedLanguage.value !== '全部语言') {
        let languageFilter = selectedLanguage.value
        const languageMap = {
          '中文': 'chinese',
          '美式英语': 'en_us',
          '英式英语': 'en_gb',
          '澳洲英语': 'en_au',
          '西语': 'es',
          '日语': 'ja'
        }

        if (languageMap[selectedLanguage.value]) {
          languageFilter = languageMap[selectedLanguage.value]
        }

        filtered = filtered.filter(voice => {
          return voice.language && Array.isArray(voice.language) && voice.language.includes(languageFilter)
        })
      }

      // Filter by gender
      if (selectedGender.value !== '全部性别') {
        let genderFilter = selectedGender.value
        if (selectedGender.value === '女性') {
          genderFilter = 'female'
        } else if (selectedGender.value === '男性') {
          genderFilter = 'male'
        }

        filtered = filtered.filter(voice => voice.gender === genderFilter)
      }

      // Filter by search query
      if (segmentSearchQuery.value) {
        filtered = filtered.filter(voice =>
          voice.name.toLowerCase().includes(segmentSearchQuery.value.toLowerCase())
        )
      }

      return filtered
    })

    // 反转段落数组,用于从下往上显示
    const reversedSegments = computed(() => {
      return audioSegments.value.map((segment, index) => ({
        segment,
        originalIndex: index
      })).reverse()
    })

    // Check if voice is female based on name
    const isFemaleVoice = (name) => {
      return name.toLowerCase().includes('female')
    }

    // Get selected voice data
    const selectedVoiceData = computed(() => {
      return voices.value.find(v => v.voice_type === selectedVoice.value)
    })

    // Emotion items for dropdown
    const emotionItems = computed(() => {
      const items = []
      if (selectedVoiceData.value && selectedVoiceData.value.emotions && emotions.value.length > 0) {
        selectedVoiceData.value.emotions.forEach(emotionName => {
          // Find the emotion data from emotions array
          const emotionData = emotions.value.find(emotion => emotion.name === emotionName)
          if (emotionData) {
            items.push({ value: emotionName, label: emotionData.zh })
          } else {
            // Fallback if emotion not found in emotions data
            items.push({ value: emotionName, label: emotionName })
          }
        })
      }

      // If no emotions found or no neutral emotion in the list, add neutral as default
      if (items.length === 0 || !items.find(item => item.value === 'neutral')) {
        items.unshift({ value: 'neutral', label: t('neutral') })
      }

      return items
    })

    // Get available emotions for selected voice
    const availableEmotions = computed(() => {
      return selectedVoiceData.value?.emotions || []
    })

    // Handle emotion selection
    const handleEmotionSelect = (item) => {
      selectedEmotion.value = item.value
    }

    // Handle voice selection and auto-generate TTS
    const onVoiceSelect = async (voice) => {
      selectedVoice.value = voice.voice_type
      selectedVoiceResourceId.value = voice.resource_id
      isCloneVoice.value = false
      // Reset emotion if not available for this voice
      if (voice.emotions && !voice.emotions.includes(selectedEmotion.value)) {
        selectedEmotion.value = ''
      }

      // Auto-generate TTS when voice is selected and text is available
      await generateTTS()
    }

    // Handle clone voice selection
    const onCloneVoiceSelect = async (voice) => {
      selectedVoice.value = `clone_${voice.speaker_id}`
      selectedVoiceResourceId.value = voice.speaker_id
      isCloneVoice.value = true
      // Auto-generate TTS when voice is selected and text is available
      await generateTTS()
    }

    // Load cloned voices
    const loadClonedVoices = async () => {
      try {
        const token = localStorage.getItem('accessToken')
        const response = await fetch('/api/v1/voice/clone/list', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        if (response.ok) {
          const data = await response.json()
          clonedVoices.value = data.voice_clones || []
        }
      } catch (error) {
        console.error('Failed to load cloned voices:', error)
      }
    }

    // Open clone modal
    const openCloneModal = () => {
      showCloneModal.value = true
    }

    // Close clone modal
    const closeCloneModal = () => {
      showCloneModal.value = false
    }

    // Handle voice clone saved
    const handleVoiceCloneSaved = async (voiceData) => {
      await loadClonedVoices()
      // Auto-select the newly created voice
      const newVoice = clonedVoices.value.find(v => v.speaker_id === voiceData.speaker_id)
      if (newVoice) {
        await onCloneVoiceSelect(newVoice)
      }
    }

    // Handle delete voice clone
    const handleDeleteVoiceClone = async (voice) => {
      try {
        const confirmed = await showConfirmDialog({
          title: t('deleteVoiceClone'),
          message: t('deleteVoiceCloneMessage', { name: voice.name || t('unnamedVoice') }),
          confirmText: t('confirmDelete')
        })

        if (!confirmed) {
          return
        }

        const token = localStorage.getItem('accessToken')
        const response = await fetch(`/api/v1/voice/clone/${voice.speaker_id}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (response.ok) {
          showAlert(t('voiceCloneDeleted'), 'success')
          // 如果删除的是当前选中的音色,清除选择
          if (selectedVoice.value === `clone_${voice.speaker_id}`) {
            selectedVoice.value = ''
            selectedVoiceResourceId.value = ''
            isCloneVoice.value = false
            audioUrl.value = ''
            if (audioElement.value) {
              audioElement.value.pause()
              audioElement.value.src = ''
            }
          }
          // 重新加载克隆音色列表
          await loadClonedVoices()
        } else {
          const error = await response.json()
          showAlert(error.error || t('deleteFailed'), 'danger')
        }
      } catch (error) {
        console.error('Delete voice clone error:', error)
        showAlert(t('deleteFailed'), 'danger')
      }
    }

    // Format date
    const formatDate = (timestamp) => {
      if (!timestamp) return ''
      const date = new Date(timestamp * 1000)
      return date.toLocaleDateString('zh-CN')
    }

    // Generate TTS and auto-play
    const generateTTS = async () => {
      if (!inputText.value.trim()) {
        inputText.value = t('ttsPlaceholder')
      }

      if (!selectedVoice.value) return

      // 停止当前播放的音频
      if (audioElement.value) {
        audioElement.value.pause()
        audioElement.value.currentTime = 0
      }
      if (currentAudio.value) {
        currentAudio.value.pause()
        currentAudio.value.currentTime = 0
        currentAudio.value = null
      }

      console.log('contextText', contextText.value)
      isGenerating.value = true
      try {
        let response
        const token = localStorage.getItem('accessToken')

        // 如果是克隆音色,使用克隆音色合成接口
        if (isCloneVoice.value) {
          response = await fetch('/api/v1/voice/clone/tts', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
              text: inputText.value,
              speaker_id: selectedVoiceResourceId.value,
              style: '正常',
              speed: getSpeechRateValue(speechRate.value),
              volume: getLoudnessValue(loudnessRate.value),
              pitch: getPitchValue(pitch.value),
              language: 'ZH_CN'
            })
          })
        } else {
          // 普通AI音色
          response = await fetch('/api/v1/tts/generate', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              text: inputText.value,
              voice_type: selectedVoice.value,
              context_texts: contextText.value,
              emotion: selectedEmotion.value,
              emotion_scale: emotionScale.value,
              speech_rate: speechRate.value,
              loudness_rate: loudnessRate.value,
              pitch: pitch.value,
              resource_id: selectedVoiceResourceId.value
            })
          })
        }

        if (response.ok) {
          const blob = await response.blob()
          audioUrl.value = URL.createObjectURL(blob)
          // 标记需要自动播放
          shouldAutoPlay.value = true
          addTtsHistoryEntry(
            inputText.value,
            contextText.value,
            {
              voiceType: selectedVoice.value,
              voiceName: selectedVoiceData.value?.name || ''
            }
          )
        } else {
          throw new Error('TTS generation failed')
        }
      } catch (error) {
        console.error('TTS generation error:', error)
        alert(t('ttsGenerationFailed'))
      } finally {
        isGenerating.value = false
      }
    }

    const applyCombinedHistoryEntry = async (entry) => {
      if (!entry) return
      inputText.value = entry.text || ''
      contextText.value = entry.instruction || ''

      if (entry.voiceType) {
        const voice = voices.value.find(v => v.voice_type === entry.voiceType)
        if (voice) {
          await onVoiceSelect(voice)
          return
        }

        selectedVoice.value = entry.voiceType
        selectedVoiceResourceId.value = ''
      }

      nextTick(() => {
        generateTTS()
      })
      showHistoryPanel.value = false
    }

    const applyTextHistoryEntry = (value) => {
      if (!value) return
      inputText.value = value
      showTextHistoryPanel.value = false
    }

    const applyInstructionHistoryEntry = (value) => {
      if (!value) return
      contextText.value = value
      showInstructionHistoryPanel.value = false
    }

    const applyVoiceHistoryEntry = async (voiceType) => {
      if (!voiceType) return
      const voice = voices.value.find(v => v.voice_type === voiceType)
      if (voice) {
        await onVoiceSelect(voice)
      } else {
        selectedVoice.value = voiceType
        selectedVoiceResourceId.value = ''
        nextTick(() => {
          generateTTS()
        })
      }
      showVoiceHistoryPanel.value = false
    }

    const getHistoryVoiceName = (entry) => {
      if (!entry) return ''
      if (entry.voiceName) return entry.voiceName
      if (entry.voiceType) {
        const voice = voices.value.find(v => v.voice_type === entry.voiceType)
        return voice?.name || ''
      }
      return ''
    }

    // 格式化音频时间
    const formatAudioTime = (seconds) => {
      if (!seconds || isNaN(seconds)) return '0:00'
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins}:${secs.toString().padStart(2, '0')}`
    }

    // 切换播放/暂停
    const toggleAudioPlayback = () => {
      if (!audioElement.value) return

      if (audioElement.value.paused) {
        audioElement.value.play().catch(error => {
          console.log('播放失败:', error)
        })
      } else {
        audioElement.value.pause()
      }
    }

    // 音频加载完成
    const onAudioLoaded = () => {
      if (audioElement.value) {
        audioDuration.value = audioElement.value.duration || 0
        // 如果需要自动播放,则播放
        if (shouldAutoPlay.value) {
          setTimeout(() => {
            if (audioElement.value && !audioElement.value.paused) {
              return // 如果已经在播放,不重复播放
            }
            audioElement.value.play().catch(error => {
              console.log('自动播放被阻止:', error)
            })
            shouldAutoPlay.value = false // 重置自动播放标志
          }, 100)
        }
      }
    }

    // 时间更新
    const onTimeUpdate = () => {
      if (audioElement.value && !isDragging.value) {
        currentTime.value = audioElement.value.currentTime || 0
      }
    }

    // 进度条变化处理(点击或拖拽)
    const onProgressChange = (event) => {
      if (audioDuration.value > 0 && audioElement.value && event.target) {
        const newTime = parseFloat(event.target.value)
        currentTime.value = newTime
        // 立即更新音频位置
        audioElement.value.currentTime = newTime
      }
    }

    // 进度条拖拽结束处理
    const onProgressEnd = (event) => {
      if (audioElement.value && audioDuration.value > 0 && event.target) {
        const newTime = parseFloat(event.target.value)
        audioElement.value.currentTime = newTime
        currentTime.value = newTime
      }
      isDragging.value = false
    }

    // 播放结束
    const onAudioEnded = () => {
      isPlaying.value = false
      currentTime.value = 0
    }

    // 监听音频 URL 变化,重置状态
    watch(audioUrl, (newUrl) => {
      if (newUrl) {
        isPlaying.value = false
        currentTime.value = 0
        audioDuration.value = 0
        // 等待 DOM 更新后加载音频
        nextTick(() => {
          if (audioElement.value) {
            audioElement.value.load()
          }
        })
      } else {
        // URL 清空时重置自动播放标志
        shouldAutoPlay.value = false
      }
    })


    // Apply selected voice (emit the generated audio)
    const applySelectedVoice = () => {
      if (audioUrl.value) {
        // Convert the audio URL back to blob and emit
        fetch(audioUrl.value)
          .then(response => response.blob())
          .then(blob => {
            emit('tts-complete', blob)
          })
          .catch(error => {
            console.error('Error converting audio to blob:', error)
            alert(t('applyAudioFailed'))
          })
      }
    }

    // Close modal function
    const closeModal = () => {
      emit('close-modal')
    }

    // Toggle controls panel
    const toggleControls = () => {
      showControls.value = !showControls.value
    }

    // Filter panel functions
    const toggleFilterPanel = () => {
      showFilterPanel.value = !showFilterPanel.value
    }

    const closeFilterPanel = () => {
      showFilterPanel.value = false
    }

    const selectCategory = (category) => {
      selectedCategory.value = category
    }

    const selectVersion = (version) => {
      selectedVersion.value = version
    }

    const selectLanguage = (language) => {
      selectedLanguage.value = language
    }

    const selectGender = (gender) => {
      selectedGender.value = gender
    }

    const resetFilters = () => {
      selectedCategory.value = '全部场景'
      selectedVersion.value = '全部版本'
      selectedLanguage.value = '全部语言'
      selectedGender.value = '全部性别'
    }

    const applyFilters = () => {
      showFilterPanel.value = false
      resetScrollPosition()
    }

    // Convert speech rate to display value (0.5x to 2.0x)
    const getSpeechRateDisplayValue = (value) => {
      // Map -50 to 100 range to 0.5x to 2.0x
      const ratio = (parseInt(value) + 50) / 150 // Convert to 0-1 range
      const speechRate = 0.5 + (ratio * 1.5) // Convert to 0.5-2.0 range
      return `${speechRate.toFixed(1)}x`
    }

    // Convert speech rate to API value for clone voice (0.5 to 2.0)
    const getSpeechRateValue = (value) => {
      const ratio = (parseInt(value) + 50) / 150
      return 0.5 + (ratio * 1.5)
    }

    // Convert loudness rate to display value (-100 to 100)
    const getLoudnessDisplayValue = (value) => {
      // Map -50 to 100 range to 50 to 200
      const apiValue = Math.round(parseInt(value)+100)
      return `${apiValue}%`
    }

    // Convert loudness rate to API value for clone voice (-12 to 12)
    const getLoudnessValue = (value) => {
      // Map -50 to 100 range to -12 to 12
      const ratio = (parseInt(value) + 50) / 150
      return -12 + (ratio * 24)
    }

    // Convert pitch to display value (-100 to 100)
    const getPitchDisplayValue = (value) => {
      // Map -12 to 12 range to -100 to 100 for API
      const apiValue = Math.round(parseInt(value) * 100 / 12)
      return `${apiValue}`
    }

    // Convert pitch to API value for clone voice (-24 to 24)
    const getPitchValue = (value) => {
      // Map -12 to 12 range to -24 to 24
      return parseInt(value) * 2
    }

    // Convert language code to Chinese display name
    const getLanguageDisplayName = (langCode) => {
      const languageMap = {
        'chinese': '中文',
        'en_us': '美式英语',
        'en_gb': '英式英语',
        'en_au': '澳洲英语',
        'es': '西语',
        'ja': '日语'
      }
      return languageMap[langCode] || langCode
    }

    // 多段模式相关函数
    const toggleMode = async () => {
      isMultiSegmentMode.value = !isMultiSegmentMode.value
      if (isMultiSegmentMode.value && audioSegments.value.length === 0) {
        // 添加默认示例
        await initDefaultSegments()
      }
    }

    // 初始化默认示例段落
    const initDefaultSegments = async () => {
      // 等待 voices 数据加载完成(最多等待 3 秒)
      let retryCount = 0
      while (voices.value.length === 0 && retryCount < 6) {
        await new Promise(resolve => setTimeout(resolve, 500))
        retryCount++
      }

      // 查找 Vivi 2.0 音色(尝试多种匹配方式)
      let viviVoice = voices.value.find(v =>
        v.name && v.name.toLowerCase().includes('vivi') && v.version === '2.0'
      )
      // 如果没找到,尝试只匹配 vivi(不限制版本)
      if (!viviVoice) {
        viviVoice = voices.value.find(v =>
          v.name && v.name.toLowerCase().includes('vivi')
        )
      }
      if (viviVoice) {
        console.log('找到 Vivi 音色:', viviVoice.name, viviVoice.voice_type)
      } else {
        console.warn('未找到 Vivi 音色,将创建段落但不会自动合成')
      }

      // 查找儒雅逸辰音色(尝试多种匹配方式)
      let ruyayiVoice = voices.value.find(v =>
        v.name && v.name.includes('儒雅逸辰')
      )
      // 如果没找到,尝试匹配逸辰
      if (!ruyayiVoice) {
        ruyayiVoice = voices.value.find(v =>
          v.name && v.name.includes('逸辰')
        )
      }
      // 如果还没找到,尝试匹配包含"儒雅"的
      if (!ruyayiVoice) {
        ruyayiVoice = voices.value.find(v =>
          v.name && v.name.includes('儒雅')
        )
      }
      if (ruyayiVoice) {
        console.log('找到儒雅逸辰音色:', ruyayiVoice.name, ruyayiVoice.voice_type)
      } else {
        console.warn('未找到儒雅逸辰音色,将创建段落但不会自动合成')
      }

      // 创建第一段:Vivi 2.0
      const segment1 = {
        id: Date.now() + Math.random(),
        text: '今天天气好好呀,要一起出去走走吗~',
        voice: viviVoice ? viviVoice.voice_type : '',
        voiceData: viviVoice || null,
        audioUrl: '',
        audioBlob: null,
        duration: 0,
        currentTime: 0,
        isGenerating: false,
        contextText: '用少女俏皮可爱的音色说',
        speechRate: 0,
        loudnessRate: 0,
        pitch: 0,
        isCloneVoice: false, // 默认不是克隆音色
        audioSnapshot: null
      }
      audioSegments.value.push(segment1)

      // 创建第二段:儒雅逸辰
      const segment2 = {
        id: Date.now() + Math.random() + 1,
        text: '好啊,小傻瓜,晚上想不想吃火锅啊?',
        voice: ruyayiVoice ? ruyayiVoice.voice_type : '',
        voiceData: ruyayiVoice || null,
        audioUrl: '',
        audioBlob: null,
        duration: 0,
        currentTime: 0,
        isGenerating: false,
        contextText: '磁性的低音炮,宠溺的语气',
        speechRate: 0,
        loudnessRate: 0,
        pitch: 0,
        isCloneVoice: false, // 默认不是克隆音色
        audioSnapshot: null
      }
      audioSegments.value.push(segment2)

      // 等待 DOM 更新后自动合成
      await nextTick()

      // 自动合成第一段(如果找到了音色)
      if (segment1.voice && segment1.text.trim()) {
        try {
          await generateSegmentTTS(0)
        } catch (error) {
          console.error('第一段合成失败:', error)
        }
      }

      // 等待第一段合成完成后再合成第二段(如果找到了音色)
      if (segment2.voice && segment2.text.trim()) {
        try {
          await generateSegmentTTS(1)
        } catch (error) {
          console.error('第二段合成失败:', error)
        }
      }
    }

    const addSegment = () => {
      audioSegments.value.push({
        id: Date.now() + Math.random(),
        text: '',
        voice: '',
        voiceData: null,
        audioUrl: '',
        audioBlob: null,
        duration: 0,
        currentTime: 0,
        isGenerating: false,
        contextText: '',
        speechRate: 0,
        loudnessRate: 0,
        pitch: 0,
        isCloneVoice: false, // 标记是否是克隆音色
        audioSnapshot: null // 记录生成音频时的参数快照
      })
    }

    const copySegment = (index, event) => {
      const segment = audioSegments.value[index]
      if (!segment) return

      // 创建段落的深拷贝,包括所有属性
      const copiedSegment = {
        id: Date.now() + Math.random(), // 新的唯一 ID
        text: segment.text || '',
        voice: segment.voice || '',
        voiceData: segment.voiceData ? { ...segment.voiceData } : null, // 浅拷贝 voiceData 对象
        audioUrl: '', // 新段落没有音频,需要重新生成
        audioBlob: null, // 不复制音频 blob,需要重新生成
        duration: 0, // 重置时长
        currentTime: 0, // 重置当前时间
        isGenerating: false, // 重置生成状态
        contextText: segment.contextText || '', // 复制语音指令
        speechRate: segment.speechRate || 0, // 复制语速设置
        loudnessRate: segment.loudnessRate || 0, // 复制音量设置
        pitch: segment.pitch || 0, // 复制音调设置
        isCloneVoice: segment.isCloneVoice || false, // 复制克隆音色标志
        audioSnapshot: null // 新段落没有快照,需要重新生成
      }

      // 将复制的段落添加到列表末尾
      audioSegments.value.push(copiedSegment)

      // 添加视觉反馈:图标临时变为对勾
      if (event && event.target) {
        const button = event.target.closest('button')
        if (button) {
          const originalIcon = button.querySelector('i')
          if (originalIcon) {
            originalIcon.className = 'fas fa-check text-xs'
            setTimeout(() => {
              originalIcon.className = 'fas fa-copy text-xs'
            }, 1000)
          }
        }
      }

      console.log(t('segmentCopied'))
    }

    const removeSegment = (index) => {
      if (audioSegments.value[index].audioUrl) {
        URL.revokeObjectURL(audioSegments.value[index].audioUrl)
      }
      audioSegments.value.splice(index, 1)
      // 重新合并音频
      if (audioSegments.value.length > 0) {
        mergeAllSegments()
      } else {
        mergedAudioUrl.value = ''
      }
    }

    // 设置段落音色选择器的 ref
    const setSegmentVoiceSelectorRef = (index, el) => {
      if (el) {
        if (!segmentVoiceSelectors.value) {
          segmentVoiceSelectors.value = {}
        }
        segmentVoiceSelectors.value[index] = el
      } else {
        // 元素被卸载时,清理 ref
        if (segmentVoiceSelectors.value && segmentVoiceSelectors.value[index]) {
          delete segmentVoiceSelectors.value[index]
        }
      }
    }

    const selectVoiceForSegment = (index) => {
      if (selectedSegmentIndex.value === index && showVoiceSelector.value) {
        // 如果点击的是已选中的,则关闭
        closeSegmentVoiceSelector()
      } else {
        // 先关闭其他可能打开的选择器
        if (showVoiceSelector.value) {
          closeSegmentVoiceSelector()
        }
        // 打开音色选择面板
        selectedSegmentIndex.value = index
        showVoiceSelector.value = true
        segmentVoiceTab.value = 'ai' // 默认显示 AI 音色标签页
        segmentSearchQuery.value = '' // 重置搜索查询
      }
    }

    // 获取当前段落选中的音色
    const getSegmentSelectedVoice = () => {
      if (selectedSegmentIndex.value >= 0 && audioSegments.value[selectedSegmentIndex.value]) {
        return audioSegments.value[selectedSegmentIndex.value].voice || ''
      }
      return ''
    }

    // 关闭段落音色选择面板
    const closeSegmentVoiceSelector = () => {
      selectedSegmentIndex.value = -1
      showVoiceSelector.value = false
      segmentSearchQuery.value = '' // 重置搜索查询
    }

    // 切换段落设置面板
    const toggleSegmentSettings = (index) => {
      if (showSegmentSettings.value === index) {
        showSegmentSettings.value = -1
      } else {
        showSegmentSettings.value = index
      }
    }

    const onVoiceSelectForSegment = (voice) => {
      if (selectedSegmentIndex.value >= 0) {
        const segment = audioSegments.value[selectedSegmentIndex.value]
        segment.voice = voice.voice_type
        segment.voiceData = voice
        segment.isCloneVoice = false // 标记为普通AI音色
        segment.contextText = '' // 重置语音指令
        showInstructionInput.value = -1
      }
      closeSegmentVoiceSelector()
    }

    // 处理段落克隆音色选择
    const onCloneVoiceSelectForSegment = (voice) => {
      if (selectedSegmentIndex.value >= 0) {
        const segment = audioSegments.value[selectedSegmentIndex.value]
        segment.voice = `clone_${voice.speaker_id}`
        segment.voiceData = {
          voice_type: `clone_${voice.speaker_id}`,
          name: voice.name || t('unnamedVoice'),
          speaker_id: voice.speaker_id,
          resource_id: voice.resource_id || voice.speaker_id // 确保有 resource_id
        }
        segment.isCloneVoice = true // 标记为克隆音色
        segment.contextText = '' // 重置语音指令
        showInstructionInput.value = -1
      }
      closeSegmentVoiceSelector()
    }

    // 下拉菜单相关代码已移除,现在使用面板模式

    // 监听合并音频 URL 变化,自动加载音频
    watch(mergedAudioUrl, async (newUrl, oldUrl) => {
      if (newUrl) {
        // 等待 DOM 更新
        await nextTick()

        if (mergedAudioElement.value) {
          console.log('检测到合并音频 URL 变化,准备加载音频:', newUrl)

          // 如果 URL 改变,先清理旧的
          if (oldUrl && oldUrl !== newUrl) {
            mergedAudioElement.value.src = ''
            mergedAudioElement.value.load()
            await new Promise(resolve => setTimeout(resolve, 50))
          }

          // 设置新的 src
          mergedAudioElement.value.src = newUrl
          console.log('音频 src 已设置:', mergedAudioElement.value.src)

          // 监听加载错误
          const handleError = (e) => {
            console.error('合并音频加载错误:', {
              error: e,
              errorCode: mergedAudioElement.value.error?.code,
              errorMessage: mergedAudioElement.value.error?.message,
              src: mergedAudioElement.value.src,
              readyState: mergedAudioElement.value.readyState,
              networkState: mergedAudioElement.value.networkState
            })
            alert(t('mergedAudioLoadFailed', { error: mergedAudioElement.value.error?.message || t('unknownError') }))
          }
          mergedAudioElement.value.addEventListener('error', handleError, { once: true })

          // 监听加载成功
          const handleLoadedMetadata = () => {
            console.log('合并音频元数据加载成功:', {
              duration: mergedAudioElement.value.duration,
              readyState: mergedAudioElement.value.readyState
            })
            if (mergedAudioElement.value) {
              mergedAudioDuration.value = mergedAudioElement.value.duration || 0
            }
          }
          mergedAudioElement.value.addEventListener('loadedmetadata', handleLoadedMetadata, { once: true })

          const handleLoadedData = () => {
            console.log('合并音频数据加载成功,可以播放')
          }
          mergedAudioElement.value.addEventListener('loadeddata', handleLoadedData, { once: true })

          // 加载音频
          mergedAudioElement.value.load()
          console.log('已调用 load(),readyState:', mergedAudioElement.value.readyState)
        } else {
          console.warn('音频元素不存在,URL:', newUrl)
          // 如果元素不存在,稍后重试
          setTimeout(() => {
            if (mergedAudioElement.value && mergedAudioUrl.value === newUrl) {
              mergedAudioElement.value.src = newUrl
              mergedAudioElement.value.load()
            }
          }, 200)
        }
      } else {
        // URL 清空时,清理音频元素
        if (mergedAudioElement.value) {
          mergedAudioElement.value.src = ''
          mergedAudioElement.value.load()
        }
      }
    })

    // 点击外部关闭音色选择器
    const handleClickOutside = (event) => {
      // 面板通过遮罩层点击关闭,这里保留作为备用
      // 面板的关闭逻辑由 closeSegmentVoiceSelector 处理
    }

    onUnmounted(() => {
      document.removeEventListener('click', handleClickOutside)
      if (currentAudio.value) {
        currentAudio.value.pause()
        currentAudio.value = null
      }
      // 清理音频URL
      if (audioUrl.value) {
        URL.revokeObjectURL(audioUrl.value)
      }
      // 清理多段模式的音频URL
      audioSegments.value.forEach(segment => {
        if (segment.audioUrl) {
          URL.revokeObjectURL(segment.audioUrl)
        }
      })
      if (mergedAudioUrl.value) {
        URL.revokeObjectURL(mergedAudioUrl.value)
      }
    })

    const generateSegmentTTS = async (index) => {
      const segment = audioSegments.value[index]
      if (!segment.text.trim() || !segment.voice) return

      segment.isGenerating = true
      try {
        let response
        const token = localStorage.getItem('accessToken')

        // 如果是克隆音色,使用克隆音色合成接口(与单段模式一致)
        if (segment.isCloneVoice && segment.voiceData?.speaker_id) {
          response = await fetch('/api/v1/voice/clone/tts', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
              text: segment.text,
              speaker_id: segment.voiceData.speaker_id,
              style: '正常',
              speed: getSpeechRateValue(segment.speechRate || 0),
              volume: getLoudnessValue(segment.loudnessRate || 0),
              pitch: getPitchValue(segment.pitch || 0),
              language: 'ZH_CN'
            })
          })
        } else {
          // 普通AI音色
          response = await fetch('/api/v1/tts/generate', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              text: segment.text,
              voice_type: segment.voice,
              context_texts: segment.contextText || '',
              emotion: 'neutral',
              emotion_scale: 3,
              speech_rate: parseInt(segment.speechRate || 0),
              loudness_rate: parseInt(segment.loudnessRate || 0),
              pitch: parseInt(segment.pitch || 0),
              resource_id: segment.voiceData?.resource_id || ''
            })
          })
        }

        if (response.ok) {
          const blob = await response.blob()
          segment.audioBlob = blob
          segment.audioUrl = URL.createObjectURL(blob)
          // 保存参数快照
          segment.audioSnapshot = {
            text: segment.text,
            voice: segment.voice,
            contextText: segment.contextText || '',
            speechRate: segment.speechRate || 0,
            loudnessRate: segment.loudnessRate || 0,
            pitch: segment.pitch || 0,
            resource_id: segment.voiceData?.resource_id || '',
            isCloneVoice: segment.isCloneVoice || false
          }
          // 等待音频加载后获取时长
          await nextTick()
          if (segmentAudioElements.value[index]) {
            segmentAudioElements.value[index].load()
            // 等待音频元数据加载完成
            await new Promise((resolve) => {
              const audioEl = segmentAudioElements.value[index]
              if (audioEl.readyState >= 2) {
                // 如果已经加载了元数据,直接解析
                resolve()
              } else {
                // 否则等待 loadedmetadata 事件
                audioEl.addEventListener('loadedmetadata', resolve, { once: true })
              }
            })
            // 自动播放生成的音频
            try {
              // 停止其他正在播放的段
              Object.values(segmentAudioElements.value).forEach((el, i) => {
                if (el && i !== index && !el.paused) {
                  el.pause()
                  if (audioSegments.value[i]) {
                    audioSegments.value[i].currentTime = el.currentTime
                  }
                }
              })
              await segmentAudioElements.value[index].play()
              playingSegmentIndex.value = index
            } catch (playError) {
              console.log('自动播放失败:', playError)
              // 自动播放失败不影响功能,用户可以手动播放
            }
          }
        } else {
          throw new Error('TTS generation failed')
        }
      } catch (error) {
        console.error('TTS generation error:', error)
        alert(t('ttsGenerationFailed'))
      } finally {
        segment.isGenerating = false
        // 自动合并所有段
        await mergeAllSegments()
      }
    }

    // 检查段的参数是否与音频快照匹配
    const isSegmentParamsChanged = (index) => {
      const segment = audioSegments.value[index]
      if (!segment || !segment.audioSnapshot) {
        // 如果没有快照,说明还没有生成过音频,需要生成
        return true
      }

      const snapshot = segment.audioSnapshot
      // 检查所有相关参数是否改变
      return (
        segment.text !== snapshot.text ||
        segment.voice !== snapshot.voice ||
        (segment.contextText || '') !== (snapshot.contextText || '') ||
        (segment.speechRate || 0) !== (snapshot.speechRate || 0) ||
        (segment.loudnessRate || 0) !== (snapshot.loudnessRate || 0) ||
        (segment.pitch || 0) !== (snapshot.pitch || 0) ||
        (segment.voiceData?.resource_id || '') !== (snapshot.resource_id || '') ||
        (segment.isCloneVoice || false) !== (snapshot.isCloneVoice || false)
      )
    }

    const handleSegmentGenerateOrPlay = (index) => {
      const segment = audioSegments.value[index]
      if (!segment) return

      // 检查参数是否改变
      if (segment.audioUrl && isSegmentParamsChanged(index)) {
        // 参数已改变,清除旧音频并重新生成
        if (segment.audioUrl) {
          URL.revokeObjectURL(segment.audioUrl)
        }
        segment.audioUrl = ''
        segment.audioBlob = null
        segment.duration = 0
        segment.currentTime = 0
        segment.audioSnapshot = null
        // 停止播放(如果正在播放)
        if (playingSegmentIndex.value === index && segmentAudioElements.value[index]) {
          segmentAudioElements.value[index].pause()
          playingSegmentIndex.value = -1
        }
        // 重新生成
        generateSegmentTTS(index)
      } else if (segment.audioUrl) {
        // 参数未改变,直接播放/暂停
        playSegment(index)
      } else {
        // 如果没有音频,则生成
        generateSegmentTTS(index)
      }
    }

    const onSegmentAudioLoaded = (index) => {
      const audioEl = segmentAudioElements.value[index]
      if (audioEl) {
        audioSegments.value[index].duration = audioEl.duration || 0
        if (!audioSegments.value[index].currentTime) {
          audioSegments.value[index].currentTime = 0
        }
        // 重新计算合并音频的总时长
        mergeAllSegments()
      }
    }

    const onSegmentTimeUpdate = (index) => {
      const audioEl = segmentAudioElements.value[index]
      if (audioEl && audioSegments.value[index]) {
        audioSegments.value[index].currentTime = audioEl.currentTime || 0

        // 如果是连续播放模式,更新累计时间
        if (isPlayingMerged.value && playingSegmentIndex.value === index) {
          let segmentIndexInSequence = 0
          for (let i = 0; i < index; i++) {
            if (audioSegments.value[i].audioUrl && audioSegments.value[i].duration > 0) {
              segmentIndexInSequence++
            }
          }

          if (segmentIndexInSequence < segmentStartTimes.value.length) {
            const segmentStartTime = segmentStartTimes.value[segmentIndexInSequence]
            mergedCurrentTime.value = segmentStartTime + (audioEl.currentTime || 0)
          }
        }
      }
    }

    const onSegmentAudioEnded = (index) => {
      // 如果是连续播放模式,自动播放下一段
      if (isPlayingMerged.value && playingSegmentIndex.value === index) {
        let segmentIndexInSequence = 0
        for (let i = 0; i < index; i++) {
          if (audioSegments.value[i].audioUrl && audioSegments.value[i].duration > 0) {
            segmentIndexInSequence++
          }
        }
        playNextSegment(segmentIndexInSequence)
      } else {
        // 单独播放模式
        playingSegmentIndex.value = -1
        if (audioSegments.value[index]) {
          audioSegments.value[index].currentTime = 0
        }
      }
    }

    // 处理进度条点击
    const handleSegmentProgressClick = (index, event) => {
      const segment = audioSegments.value[index]
      if (!segment.audioUrl || segment.isGenerating || !segment.duration) return

      const audioEl = segmentAudioElements.value[index]
      if (!audioEl) return

      const progressBar = event.currentTarget
      const rect = progressBar.getBoundingClientRect()
      const clickX = event.clientX - rect.left
      const percentage = clickX / rect.width
      const newTime = Math.max(0, Math.min(segment.duration, percentage * segment.duration))

      audioEl.currentTime = newTime
      segment.currentTime = newTime

      // 如果音频未播放,则开始播放
      if (audioEl.paused) {
        // 停止其他正在播放的段
        Object.values(segmentAudioElements.value).forEach((el, i) => {
          if (el && i !== index && !el.paused) {
            el.pause()
          }
        })
        audioEl.play().catch(error => {
          console.log('播放失败:', error)
        })
        playingSegmentIndex.value = index
      }
    }

    const playSegment = (index) => {
      const audioEl = segmentAudioElements.value[index]
      if (!audioEl) return

      // 停止其他正在播放的段
      Object.values(segmentAudioElements.value).forEach((el, i) => {
        if (el && i !== index && !el.paused) {
          el.pause()
          if (audioSegments.value[i]) {
            audioSegments.value[i].currentTime = el.currentTime
          }
        }
      })

      if (audioEl.paused) {
        audioEl.play().catch(error => {
          console.log('播放失败:', error)
        })
        playingSegmentIndex.value = index
      } else {
        audioEl.pause()
        playingSegmentIndex.value = -1
        if (audioSegments.value[index]) {
          audioSegments.value[index].currentTime = audioEl.currentTime
        }
      }
    }

    const mergeAllSegments = async () => {
      const segmentsWithAudio = audioSegments.value.filter(s => s.audioUrl && s.duration > 0)
      if (segmentsWithAudio.length === 0) {
        mergedAudioDuration.value = 0
        mergedCurrentTime.value = 0
        segmentStartTimes.value = []
        return
      }

      // 只计算总时长和每段的开始时间,不实际合并文件
      let totalDuration = 0
      const startTimes = [0] // 第一段从 0 开始

      for (let i = 0; i < segmentsWithAudio.length; i++) {
        const segment = segmentsWithAudio[i]
        if (i > 0) {
          startTimes.push(totalDuration)
        }
        totalDuration += segment.duration || 0
      }

      mergedAudioDuration.value = totalDuration
      segmentStartTimes.value = startTimes

      console.log('计算总时长:', totalDuration, '秒,共', segmentsWithAudio.length, '')
    }

    // 将 AudioBuffer 转换为 WAV
    const audioBufferToWav = (buffer) => {
      const length = buffer.length
      const numberOfChannels = buffer.numberOfChannels
      const sampleRate = buffer.sampleRate
      const bytesPerSample = 2 // 16-bit
      const blockAlign = numberOfChannels * bytesPerSample
      const byteRate = sampleRate * blockAlign
      const dataSize = length * blockAlign
      // RIFF chunk size = 文件总大小 - 8 (不包括 RIFF 和 size 字段本身)
      // 文件总大小 = 44 (文件头) + dataSize
      const riffChunkSize = 36 + dataSize // 36 = 44 - 8

      const arrayBuffer = new ArrayBuffer(44 + dataSize)
      const view = new DataView(arrayBuffer)

      // WAV 文件头写入函数
      const writeString = (offset, string) => {
        for (let i = 0; i < string.length; i++) {
          view.setUint8(offset + i, string.charCodeAt(i))
        }
      }

      // RIFF header (12 bytes: 4 + 4 + 4)
      writeString(0, 'RIFF')
      view.setUint32(4, riffChunkSize, true) // RIFF chunk size (little-endian)
      writeString(8, 'WAVE')

      // fmt chunk (24 bytes: 4 + 4 + 16)
      writeString(12, 'fmt ')
      view.setUint32(16, 16, true) // fmt chunk size (little-endian)
      view.setUint16(20, 1, true) // Audio format: 1 = PCM (little-endian)
      view.setUint16(22, numberOfChannels, true) // Number of channels (little-endian)
      view.setUint32(24, sampleRate, true) // Sample rate (little-endian)
      view.setUint32(28, byteRate, true) // Byte rate (little-endian)
      view.setUint16(32, blockAlign, true) // Block align (little-endian)
      view.setUint16(34, 16, true) // Bits per sample (little-endian)

      // data chunk header (8 bytes: 4 + 4)
      writeString(36, 'data')
      view.setUint32(40, dataSize, true) // Data size (little-endian)

      // 写入音频数据 (PCM 16-bit little-endian)
      let offset = 44
      for (let i = 0; i < length; i++) {
        for (let channel = 0; channel < numberOfChannels; channel++) {
          const sample = Math.max(-1, Math.min(1, buffer.getChannelData(channel)[i]))
          // 转换为 16-bit PCM (little-endian)
          // 范围: -32768 到 32767
          const int16Sample = sample < 0
            ? Math.max(-0x8000, Math.floor(sample * 0x8000))
            : Math.min(0x7FFF, Math.floor(sample * 0x7FFF))
          view.setInt16(offset, int16Sample, true) // little-endian
          offset += 2
        }
      }

      return arrayBuffer
    }

    // 播放下一段音频
    const playNextSegment = (currentIndex) => {
      const segmentsWithAudio = audioSegments.value.filter(s => s.audioUrl && s.duration > 0)
      const nextIndex = currentIndex + 1

      if (nextIndex >= segmentsWithAudio.length) {
        // 所有段播放完成
        isPlayingMerged.value = false
        playingSegmentIndex.value = -1
        mergedCurrentTime.value = 0
        return
      }

      // 找到下一段在 audioSegments 中的实际索引
      let actualIndex = -1
      let foundCount = 0
      for (let i = 0; i < audioSegments.value.length; i++) {
        if (audioSegments.value[i].audioUrl && audioSegments.value[i].duration > 0) {
          if (foundCount === nextIndex) {
            actualIndex = i
            break
          }
          foundCount++
        }
      }

      if (actualIndex >= 0) {
        playingSegmentIndex.value = actualIndex
        const audioEl = segmentAudioElements.value[actualIndex]
        if (audioEl) {
          audioEl.currentTime = 0
          audioEl.play().catch(error => {
            console.error('播放下一段失败:', error)
            isPlayingMerged.value = false
            playingSegmentIndex.value = -1
          })
        }
      }
    }

    const toggleMergedAudioPlayback = () => {
      const segmentsWithAudio = audioSegments.value.filter(s => s.audioUrl && s.duration > 0)
      if (segmentsWithAudio.length === 0) {
        console.warn('没有可播放的音频段')
        return
      }

      if (isPlayingMerged.value) {
        // 暂停播放:停止当前播放的段
        if (playingSegmentIndex.value >= 0) {
          const audioEl = segmentAudioElements.value[playingSegmentIndex.value]
          if (audioEl) {
            audioEl.pause()
          }
        }
        isPlayingMerged.value = false
        playingSegmentIndex.value = -1
      } else {
        // 开始播放:从第一段开始,或从上次暂停的位置继续
        let startIndex = 0
        let foundCount = 0

        // 如果之前有播放位置,找到对应的段
        if (mergedCurrentTime.value > 0 && segmentStartTimes.value.length > 0) {
          for (let i = segmentStartTimes.value.length - 1; i >= 0; i--) {
            if (mergedCurrentTime.value >= segmentStartTimes.value[i]) {
              startIndex = i
              break
            }
          }
        }

        // 找到实际索引
        let actualIndex = -1
        for (let i = 0; i < audioSegments.value.length; i++) {
          if (audioSegments.value[i].audioUrl && audioSegments.value[i].duration > 0) {
            if (foundCount === startIndex) {
              actualIndex = i
              break
            }
            foundCount++
          }
        }

        if (actualIndex >= 0) {
          playingSegmentIndex.value = actualIndex
          const audioEl = segmentAudioElements.value[actualIndex]
          if (audioEl) {
            // 如果从中间开始,计算当前段内的位置
            if (startIndex > 0 && segmentStartTimes.value[startIndex] > 0) {
              const segmentStartTime = segmentStartTimes.value[startIndex]
              const segmentOffset = mergedCurrentTime.value - segmentStartTime
              audioEl.currentTime = Math.max(0, Math.min(segmentOffset, audioSegments.value[actualIndex].duration))
            } else {
              audioEl.currentTime = 0
            }

            audioEl.play().catch(error => {
              console.error('播放失败:', error)
              alert(t('playbackFailed', { error: error.message || t('unknownError') }))
            })
            isPlayingMerged.value = true
          }
        }
      }
    }

    const onMergedAudioLoaded = () => {
      // 已废弃,保留用于兼容
    }

    const onMergedTimeUpdate = () => {
      // 已废弃,时间更新由 onSegmentTimeUpdate 处理
    }

    const onMergedProgressChange = (event) => {
      if (mergedAudioDuration.value > 0 && event.target) {
        const newTime = parseFloat(event.target.value)
        mergedCurrentTime.value = newTime

        // 找到对应的段和段内位置
        if (segmentStartTimes.value.length > 0) {
          let targetSegmentIndex = -1
          let segmentIndexInSequence = 0

          // 找到目标段
          for (let i = segmentStartTimes.value.length - 1; i >= 0; i--) {
            if (newTime >= segmentStartTimes.value[i]) {
              segmentIndexInSequence = i
              break
            }
          }

          // 找到实际索引
          let foundCount = 0
          for (let i = 0; i < audioSegments.value.length; i++) {
            if (audioSegments.value[i].audioUrl && audioSegments.value[i].duration > 0) {
              if (foundCount === segmentIndexInSequence) {
                targetSegmentIndex = i
                break
              }
              foundCount++
            }
          }

          if (targetSegmentIndex >= 0) {
            const segmentStartTime = segmentStartTimes.value[segmentIndexInSequence]
            const segmentOffset = newTime - segmentStartTime
            const audioEl = segmentAudioElements.value[targetSegmentIndex]

            if (audioEl) {
              audioEl.currentTime = Math.max(0, Math.min(segmentOffset, audioSegments.value[targetSegmentIndex].duration))

              // 如果正在播放,切换到目标段
              if (isPlayingMerged.value) {
                // 停止当前播放的段
                if (playingSegmentIndex.value >= 0 && playingSegmentIndex.value !== targetSegmentIndex) {
                  const currentAudioEl = segmentAudioElements.value[playingSegmentIndex.value]
                  if (currentAudioEl) {
                    currentAudioEl.pause()
                  }
                }

                playingSegmentIndex.value = targetSegmentIndex
                audioEl.play().catch(error => {
                  console.error('跳转播放失败:', error)
                })
              }
            }
          }
        }
      }
    }

    const onMergedAudioEnded = () => {
      // 已废弃,结束处理由 onSegmentAudioEnded 处理
      isPlayingMerged.value = false
      mergedCurrentTime.value = 0
    }

    const applyMergedAudio = async () => {
      const segmentsWithAudio = audioSegments.value.filter(s => s.audioBlob)
      if (segmentsWithAudio.length === 0) {
        alert(t('noSegmentsToApply'))
        return
      }

      try {
        // 临时合并所有段用于应用
        const audioContext = new (window.AudioContext || window.webkitAudioContext)()
        const audioBuffers = []

        // 加载并解码所有音频段
        for (const segment of segmentsWithAudio) {
          try {
            const arrayBuffer = await segment.audioBlob.arrayBuffer()
            const audioBuffer = await audioContext.decodeAudioData(arrayBuffer)
            audioBuffers.push(audioBuffer)
          } catch (error) {
            console.error('音频段解码失败:', error)
            throw new Error(t('audioDecodeFailed', { error: error.message || t('unknownError') }))
          }
        }

        if (audioBuffers.length === 0) {
          throw new Error('没有可用的音频段')
        }

        // 使用第一个音频的参数作为目标格式
        const targetSampleRate = audioBuffers[0].sampleRate
        const targetChannels = audioBuffers[0].numberOfChannels

        // 计算总长度
        let totalLength = 0
        for (const buffer of audioBuffers) {
          totalLength += buffer.length
        }

        // 创建合并后的音频缓冲区
        const mergedBuffer = audioContext.createBuffer(
          targetChannels,
          totalLength,
          targetSampleRate
        )

        // 合并所有音频数据
        let offset = 0
        for (const buffer of audioBuffers) {
          const bufferLength = buffer.length

          for (let channel = 0; channel < targetChannels; channel++) {
            const mergedChannelData = mergedBuffer.getChannelData(channel)

            if (channel < buffer.numberOfChannels) {
              const sourceChannelData = buffer.getChannelData(channel)
              mergedChannelData.set(sourceChannelData, offset)
            } else {
              const sourceChannelData = buffer.getChannelData(0)
              mergedChannelData.set(sourceChannelData, offset)
            }
          }

          offset += bufferLength
        }

        // 转换为 WAV
        const wav = audioBufferToWav(mergedBuffer)
        const blob = new Blob([wav], { type: 'audio/wav' })

        emit('tts-complete', blob)
      } catch (error) {
        console.error('合并音频失败:', error)
        alert(t('mergedAudioFailed', { error: error.message || t('unknownError') }))
      }
    }

    // 拖拽排序函数
    const handleDragStart = (index, event) => {
      draggingSegmentIndex.value = index
      event.dataTransfer.effectAllowed = 'move'
      event.dataTransfer.setData('text/plain', index.toString())
    }

    const handleDragEnd = () => {
      draggingSegmentIndex.value = -1
      dragOverSegmentIndex.value = -1
    }

    const handleDragOver = (index, event) => {
      event.preventDefault()
      event.dataTransfer.dropEffect = 'move'
      if (draggingSegmentIndex.value !== index && draggingSegmentIndex.value >= 0) {
        dragOverSegmentIndex.value = index
      }
    }

    const handleDragLeave = (index) => {
      // 只有当离开整个拖拽区域时才清除 dragOverSegmentIndex
      // 这里简化处理,在 drop 时再清除
    }

    const handleDrop = (targetIndex, event) => {
      event.preventDefault()
      event.stopPropagation()

      const draggedIndex = draggingSegmentIndex.value
      if (draggedIndex === -1 || draggedIndex === targetIndex) {
        draggingSegmentIndex.value = -1
        dragOverSegmentIndex.value = -1
        return
      }

      // 重新排序段落
      const segments = [...audioSegments.value]
      const draggedSegment = segments[draggedIndex]
      segments.splice(draggedIndex, 1)
      segments.splice(targetIndex, 0, draggedSegment)

      // 更新 audioSegments
      audioSegments.value = segments

      // 重新计算合并音频的总时长
      mergeAllSegments()

      draggingSegmentIndex.value = -1
      dragOverSegmentIndex.value = -1
    }

    return {
      t,
      inputText,
      contextText,
      selectedVoice,
      searchQuery,
      speechRate,
      loudnessRate,
      pitch,
      emotionScale,
      selectedEmotion,
      isGenerating,
      audioUrl,
      audioElement,
      isPlaying,
      audioDuration,
      currentTime,
      isDragging,
      onProgressChange,
      onProgressEnd,
      voices,
      voiceListContainer,
      voiceSelectorRef,
      showControls,
      showFilterPanel,
      filteredVoices,
      isFemaleVoice,
      selectedVoiceData,
      formatAudioTime,
      toggleAudioPlayback,
      onAudioLoaded,
      onTimeUpdate,
      onAudioEnded,
      availableEmotions,
      onVoiceSelect,
      generateTTS,
      applySelectedVoice,
      closeModal,
      toggleControls,
      toggleFilterPanel,
      closeFilterPanel,
      selectCategory,
      selectVersion,
      selectLanguage,
      selectGender,
      resetFilters,
      applyFilters,
      getSpeechRateDisplayValue,
      getLoudnessDisplayValue,
      getPitchDisplayValue,
      getLanguageDisplayName,
      emotionItems,
      handleEmotionSelect,
      selectedCategory,
      categories,
      selectedVoiceResourceId,
      version,
      selectedVersion,
      selectedLanguage,
      languages,
      selectedGender,
      genders,
      resetScrollPosition,
      translateCategory,
      translateVersion,
      translateLanguage,
      translateGender,
      ttsHistory,
      showHistoryPanel,
      openHistoryPanel,
      closeHistoryPanel,
      applyCombinedHistoryEntry,
      applyTextHistoryEntry,
      applyInstructionHistoryEntry,
      applyVoiceHistoryEntry,
      getHistoryVoiceName,
      handleDeleteHistoryEntry,
      showTextHistoryPanel,
      showInstructionHistoryPanel,
      showVoiceHistoryPanel,
      openTextHistoryPanel,
      openInstructionHistoryPanel,
      openVoiceHistoryPanel,
      closeTextHistoryPanel,
      closeInstructionHistoryPanel,
      closeVoiceHistoryPanel,
      voiceTab,
      clonedVoices,
      showCloneModal,
      cloneVoiceListContainer,
      isCloneVoice,
      onCloneVoiceSelect,
      loadClonedVoices,
      openCloneModal,
      closeCloneModal,
      handleVoiceCloneSaved,
      handleDeleteVoiceClone,
      formatDate,
      getSpeechRateValue,
      getLoudnessValue,
      getPitchValue,
      // 多段模式相关
      isMultiSegmentMode,
      audioSegments,
      reversedSegments,
      mergedAudioUrl,
      isMerging,
      isPlayingMerged,
      mergedAudioDuration,
      mergedCurrentTime,
      playingSegmentIndex,
      segmentAudioElements,
      showInstructionInput,
      showSegmentSettings,
      toggleSegmentSettings,
      toggleMode,
      addSegment,
      copySegment,
      removeSegment,
      setSegmentVoiceSelectorRef,
      selectVoiceForSegment,
      onVoiceSelectForSegment,
      onCloneVoiceSelectForSegment,
      getSegmentSelectedVoice,
      closeSegmentVoiceSelector,
      segmentVoiceTab,
      segmentSearchQuery,
      segmentFilteredVoices,
      dropdownStyle,
      generateSegmentTTS,
      handleSegmentGenerateOrPlay,
      onSegmentAudioLoaded,
      onSegmentTimeUpdate,
      onSegmentAudioEnded,
      handleSegmentProgressClick,
      playSegment,
      toggleMergedAudioPlayback,
      onMergedAudioLoaded,
      onMergedTimeUpdate,
      onMergedProgressChange,
      onMergedAudioEnded,
      applyMergedAudio,
      dropdownContainerRef,
      showVoiceSelector,
      selectedSegmentIndex,
      // 拖拽相关
      draggingSegmentIndex,
      dragOverSegmentIndex,
      handleDragStart,
      handleDragEnd,
      handleDragOver,
      handleDragLeave,
      handleDrop
    }
  }
}
</script>

<style scoped>
/* Apple 风格极简设计 - 大部分样式已通过 Tailwind CSS 在 template 中定义 */

/* 隐藏 radio input */
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border-width: 0;
}

/* 深色模式下增强滑动条可见性 */
.dark input[type="range"]::-webkit-slider-thumb {
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.15);
}

.dark input[type="range"]::-moz-range-thumb {
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.15);
}
</style>