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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IzuVidPlayer</title>
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c&display=swap" rel="stylesheet">
    <!-- M3U8ダウンロードスクリプト -->
    <script>
        function M3U8() {
            var _this = this;

            this.ie =
                navigator.appVersion.toString().indexOf(".NET") > 0;
            this.ios =
                navigator.platform &&
                /iPad|iPhone|iPod/.test(navigator.platform);

            this.start = function (m3u8, options) {
                if (!options) options = {};

                var callbacks = {
                    progress: null,
                    finished: null,
                    error: null,
                    aborted: null,
                };

                let recur;

                function handleCb(key, payload) {
                    if (key && callbacks[key]) {
                        callbacks[key](payload);
                    }
                }

                if (_this.ios) {
                    return handleCb(
                        "error",
                        "Downloading on IOS is not supported."
                    );
                }

                var startObj = {
                    on: function (str, cb) {
                        switch (str) {
                            case "progress":
                                callbacks.progress = cb;
                                break;
                            case "finished":
                                callbacks.finished = cb;
                                break;
                            case "error":
                                callbacks.error = cb;
                                break;
                            case "aborted":
                                callbacks.aborted = cb;
                                break;
                        }
                        return startObj;
                    },

                    abort: function () {
                        if (recur) {
                            recur.aborted = function () {
                                handleCb("aborted");
                            };
                        }
                    },
                };

                var download = new Promise(function (resolve, reject) {
                    var url = new URL(m3u8);

                    fetch(m3u8)
                        .then(function (d) {
                            return d.text();
                        })
                        .then(function (d) {
                            const segmentReg = /^(?!#)(.+)\.(.+)$/gm;
                            const segments = d.match(segmentReg);

                            var mapped = map(segments, function (v) {
                                let tempUrl = new URL(v, url);
                                return tempUrl.href;
                            });

                            if (!mapped.length) {
                                reject("Invalid m3u8 playlist");
                                return handleCb(
                                    "error",
                                    "Invalid m3u8 playlist"
                                );
                            }

                            recur = new RecurseDownload(
                                mapped,
                                function (data) {
                                    var blob = new Blob(data, {
                                        type: "octet/stream",
                                    });

                                    handleCb("progress", {
                                        status: "Processing...",
                                    });

                                    if (!options.returnBlob) {
                                        if (_this.ie) {
                                            handleCb("progress", {
                                                status:
                                                    "Sending video to Internet Explorer...",
                                            });

                                            window.navigator.msSaveBlob(
                                                blob,
                                                options.filename || "video.mp4"
                                            );
                                        } else {
                                            handleCb("progress", {
                                                status: "Sending video to browser...",
                                            });

                                            var a =
                                                document.createElementNS(
                                                    "http://www.w3.org/1999/xhtml",
                                                    "a"
                                                );

                                            a.href = URL.createObjectURL(blob);
                                            a.download =
                                                options.filename || "video.mp4";
                                            a.style.display = "none";

                                            document.body.appendChild(a);
                                            a.click();
                                        }

                                        handleCb("finished", {
                                            status:
                                                "Successfully downloaded video",
                                            data: blob,
                                        });

                                        resolve(blob);
                                    } else {
                                        handleCb("finished", {
                                            status:
                                                "Successfully downloaded video",
                                            data: blob,
                                        });

                                        resolve(blob);
                                    }
                                },
                                0,
                                []
                            );

                            recur.onprogress = function (obj) {
                                handleCb("progress", obj);
                            };
                        })
                        .catch(function (err) {
                            handleCb(
                                "error",
                                "Something went wrong when downloading m3u8 playlist: " +
                                err
                            );
                        });
                });

                return startObj;
            };

            function RecurseDownload(arr, cb, i, data) {
                var _this = this;
                this.aborted = false;

                recurseDownload(arr, cb, i, data);

                function recurseDownload(arr, cb, i, data) {
                    Promise.all([
                        fetch(arr[i]),
                        arr[i + 1] ? fetch(arr[i + 1]) : Promise.resolve(),
                    ])
                        .then(function (d) {
                            return map(
                                filter(d, function (v) {
                                    return v && v.blob;
                                }),
                                function (v) {
                                    return v.blob();
                                }
                            );
                        })
                        .then(function (d) {
                            return Promise.all(d);
                        })
                        .then(function (d) {
                            var blobs = map(d, function (v, j) {
                                return new Promise(function (resolve) {
                                    var reader = new FileReader();
                                    reader.readAsArrayBuffer(
                                        new Blob([v], {
                                            type: "octet/stream",
                                        })
                                    );

                                    reader.addEventListener(
                                        "loadend",
                                        function () {
                                            resolve(reader.result);

                                            if (_this.onprogress) {
                                                _this.onprogress({
                                                    segment: i + j + 1,
                                                    total: arr.length,
                                                    percentage: Math.floor(
                                                        ((i + j + 1) /
                                                            arr.length) *
                                                        100
                                                    ),
                                                    downloaded: formatNumber(
                                                        reduce(
                                                            map(data, function (v) {
                                                                return v.byteLength;
                                                            }),
                                                            function (t, c) {
                                                                return t + c;
                                                            },
                                                            0
                                                        )
                                                    ),
                                                    status: "Downloading...",
                                                });
                                            }
                                        }
                                    );
                                });
                            });

                            Promise.all(blobs).then(function (d) {
                                d.forEach(function (buf) {
                                    data.push(buf);
                                });

                                var increment = arr[i + 2] ? 2 : 1;

                                if (_this.aborted) {
                                    data = null;
                                    _this.aborted();
                                    return;
                                }

                                if (arr[i + increment]) {
                                    setTimeout(
                                        function () {
                                            recurseDownload(
                                                arr,
                                                cb,
                                                i + increment,
                                                data
                                            );
                                        },
                                        _this.ie ? 500 : 0
                                    );
                                } else {
                                    cb(data);
                                }
                            });
                        })
                        .catch(function (err) {
                            _this.onerror &&
                                _this.onerror(
                                    "Something went wrong when downloading ts file, nr. " +
                                    i +
                                    ": " +
                                    err
                                );
                        });
                }
            }
        }

        function filter(arr, condition) {
            var result = [];
            for (var i = 0; i < arr.length; i++) {
                if (condition(arr[i], i)) {
                    result.push(arr[i]);
                }
            }
            return result;
        }

        function map(arr, condition) {
            var result = arr.slice(0);
            for (var i = 0; i < arr.length; i++) {
                result[i] = condition(arr[i], i);
            }
            return result;
        }

        function reduce(arr, condition, start) {
            var result = start;
            arr.forEach(function (v, i) {
                result = condition(result, v, i);
            });
            return result;
        }

        function formatNumber(n) {
            var ranges = [
                { divider: 1e18, suffix: "EB" },
                { divider: 1e15, suffix: "PB" },
                { divider: 1e12, suffix: "TB" },
                { divider: 1e9, suffix: "GB" },
                { divider: 1e6, suffix: "MB" },
                { divider: 1e3, suffix: "kB" },
            ];

            for (var i = 0; i < ranges.length; i++) {
                if (n >= ranges[i].divider) {
                    return (
                        Math.floor(n / ranges[i].divider) +
                        ranges[i].suffix
                    );
                }
            }

            return n.toString();
        }

    </script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'M PLUS Rounded 1c', 'Segoe UI', Arial, sans-serif;
        }

        body {
            background-color: #0f0f0f;
            color: #f1f1f1;
            line-height: 1.6;
            display: flex;
        }

        /* サイドバー */
        .sidebar {
            width: 250px;
            background-color: #1a1a1a;
            min-height: 100vh;
            padding: 20px;
            position: sticky;
            top: 0;
            display: flex;
            flex-direction: column;
        }

        .sidebar-title {
            font-size: 24px;
            font-weight: bold;
            color: #ff4757;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #3d3d3d;
            text-align: center;
        }

        .sidebar-nav {
            display: flex;
            flex-direction: column;
            gap: 10px;
            flex: 1;
        }

        .nav-item {
            padding: 12px 20px;
            background-color: #2d2d2d;
            border: none;
            border-radius: 8px;
            color: white;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
            text-align: left;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .nav-item:hover {
            background-color: #3d3d3d;
        }

        .nav-item.active {
            background-color: #ff4757;
        }

        .nav-icon {
            width: 20px;
            height: 20px;
        }

        /* メインコンテンツ */
        .main-content {
            flex: 1;
            padding: 20px;
            max-width: calc(100vw - 250px);
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        /* ヘッダーと検索フォーム */
        header {
            background-color: #1a1a1a;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }

        .search-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: flex-end;
        }

        .search-box {
            flex: 1;
            min-width: 300px;
        }

        .search-box input {
            width: 100%;
            padding: 14px 20px;
            background-color: #2d2d2d;
            border: 2px solid #3d3d3d;
            border-radius: 8px;
            color: white;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .search-box input:focus {
            outline: none;
            border-color: #ff4757;
        }

        .search-options {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #3d3d3d;
        }

        .option-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .option-group label {
            font-size: 14px;
            color: #aaa;
        }

        .option-group select {
            padding: 10px 15px;
            background-color: #2d2d2d;
            border: 1px solid #3d3d3d;
            border-radius: 6px;
            color: white;
            font-size: 14px;
        }

        .buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        button {
            padding: 12px 24px;
            background-color: #ff4757;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #ff3742;
        }

        button.secondary {
            background-color: #3d3d3d;
        }

        button.secondary:hover {
            background-color: #4d4d4d;
        }

        .favorite-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .favorite-btn svg {
            fill: #e3e3e3;
            transition: fill 0.3s;
        }

        .favorite-btn.active svg {
            fill: #ffd700;
        }

        /* 動画グリッド */
        .videos-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 25px;
            margin-top: 30px;
        }

        .video-card {
            background-color: #1a1a1a;
            border-radius: 12px;
            overflow: hidden;
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
            position: relative;
        }

        .video-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.5);
        }

        .thumbnail-container {
            position: relative;
            width: 100%;
            aspect-ratio: 16/9;
            overflow: hidden;
        }

        .thumbnail {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: opacity 0.3s;
        }

        .hover-video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .video-card:hover .thumbnail {
            opacity: 0;
        }

        .video-card:hover .hover-video {
            opacity: 1;
        }

        .quality-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }

        .duration {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
        }

        .video-info {
            padding: 15px;
        }

        .video-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .video-metadata {
            font-size: 14px;
            color: #aaa;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* 動画プレーヤー画面 */
        .video-player-container {
            display: none;
            margin-top: 30px;
        }

        .video-wrapper {
            position: relative;
            width: 100%;
            background-color: #000;
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 30px;
        }

        #main-video {
            width: 100%;
            display: block;
            max-height: 600px;
        }

        /* カスタムコントロールバー */
        .custom-controls {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
            padding: 10px 15px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            opacity: 0;
            transition: opacity 0.3s;
            z-index: 10;
        }

        .video-wrapper:hover .custom-controls {
            opacity: 1;
        }

        .progress-container {
            position: relative;
            width: 100%;
            height: 5px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 2px;
            cursor: pointer;
            margin-bottom: 5px;
        }

        .progress-bar {
            position: absolute;
            height: 100%;
            background: #ff4757;
            border-radius: 2px;
            width: 0%;
        }

        .progress-buffer {
            position: absolute;
            height: 100%;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 2px;
            width: 0%;
        }

        .progress-time-tooltip {
            position: absolute;
            top: -30px;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            display: none;
            z-index: 100;
        }

        .controls-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .left-controls,
        .right-controls {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .control-btn {
            background: none;
            border: none;
            color: #e3e3e3;
            cursor: pointer;
            padding: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: color 0.3s;
        }

        .control-btn:hover {
            color: #fff;
        }

        .control-btn svg {
            width: 24px;
            height: 24px;
        }

        .volume-controls {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 120px;
        }

        .volume-slider {
            flex: 1;
            height: 4px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 2px;
            cursor: pointer;
            position: relative;
        }

        .volume-level {
            position: absolute;
            height: 100%;
            background: #ff4757;
            border-radius: 2px;
            width: 100%;
        }

        .speed-controls {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 100px;
        }

        .speed-slider {
            flex: 1;
            height: 4px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 2px;
            cursor: pointer;
            position: relative;
            min-width: 50px
        }

        .speed-level {
            position: absolute;
            height: 100%;
            background: #4CAF50;
            border-radius: 2px;
            width: 50%;
        }

        .speed-value {
            font-size: 12px;
            color: #e3e3e3;
            min-width: 40px;
            text-align: center;
        }

        .time-display {
            font-size: 14px;
            color: #e3e3e3;
            min-width: 110px;
            text-align: center;
        }

        /* 動画読み込み中のアニメーション */
        .video-loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 5;
            display: none;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid rgba(255, 255, 255, 0.1);
            border-left-color: #ff4757;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .video-details {
            background-color: #1a1a1a;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 30px;
            position: relative;
        }

        .video-details h2 {
            font-size: 24px;
            margin-bottom: 15px;
            color: #fff;
            padding-right: 40px;
        }

        .video-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid #3d3d3d;
        }

        .meta-item {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .meta-label {
            font-size: 12px;
            color: #aaa;
            text-transform: uppercase;
        }

        .meta-value {
            font-size: 16px;
            color: #fff;
        }

        .video-description {
            color: #ccc;
            line-height: 1.6;
            margin-top: 20px;
        }

        .quality-selector {
            margin-top: 20px;
            padding: 15px;
            background-color: #2d2d2d;
            border-radius: 8px;
        }

        .quality-selector h3 {
            margin-bottom: 10px;
            font-size: 18px;
        }

        .quality-options {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 15px;
        }

        .quality-option {
            padding: 8px 16px;
            background-color: #3d3d3d;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .quality-option:hover {
            background-color: #4d4d4d;
        }

        .quality-option.active {
            background-color: #ff4757;
        }

        .download-btn {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .download-btn:hover {
            background-color: #45a049;
        }

        /* ローディング表示 */
        .loading {
            display: none;
            text-align: center;
            padding: 40px;
            font-size: 18px;
            color: #aaa;
        }

        .loading::after {
            content: '';
            display: inline-block;
            width: 30px;
            height: 30px;
            border: 3px solid #3d3d3d;
            border-top-color: #ff4757;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 15px;
            vertical-align: middle;
        }

        /* エラーメッセージ */
        .error-message {
            display: none;
            background-color: rgba(255, 71, 87, 0.1);
            border: 1px solid #ff4757;
            color: #ff4757;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
            text-align: center;
        }

        /* 関連動画 */
        .related-videos {
            margin-top: 40px;
        }

        .related-videos h2 {
            font-size: 22px;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #3d3d3d;
        }

        .back-button {
            margin-bottom: 20px;
        }

        /* 履歴とお気に入り画面 */
        .history-favorites-container {
            display: none;
            margin-top: 30px;
        }

        .section-title {
            font-size: 24px;
            margin-bottom: 20px;
            color: #fff;
        }

        .search-history {
            margin-bottom: 30px;
        }

        .search-history-input {
            width: 100%;
            padding: 12px 20px;
            background-color: #2d2d2d;
            border: 2px solid #3d3d3d;
            border-radius: 8px;
            color: white;
            font-size: 16px;
            margin-bottom: 20px;
        }

        .history-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .history-item {
            padding: 15px;
            background-color: #2d2d2d;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
            transition: background-color 0.3s;
            position: relative;
            margin-bottom: 10px;
        }

        .history-info {
            flex: 1;
        }

        .history-title {
            font-size: 16px;
            margin-bottom: 5px;
        }

        .history-date {
            font-size: 12px;
            color: #aaa;
        }

        /* レスポンシブデザイン */
        @media (max-width: 1024px) {
            body {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                min-height: auto;
                position: relative;
                padding: 15px;
            }

            .sidebar-nav {
                flex-direction: row;
                flex-wrap: wrap;
            }

            .nav-item {
                flex: 1;
                min-width: 150px;
            }

            .main-content {
                max-width: 100%;
                padding: 15px;
            }

            .volume-controls,
            .speed-controls {
                min-width: 80px;
            }
        }

        @media (max-width: 768px) {
            .videos-grid {
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: 20px;
            }

            .search-container {
                flex-direction: column;
                align-items: stretch;
            }

            .search-box {
                min-width: 100%;
            }

            .search-options {
                grid-template-columns: 1fr;
            }

            .video-meta {
                flex-direction: column;
                gap: 15px;
            }

            .sidebar-nav {
                flex-direction: column;
            }

            .controls-row {
                flex-wrap: wrap;
            }

            .volume-controls,
            .speed-controls {
                display: none;
            }
        }

        @media (max-width: 480px) {
            .videos-grid {
                grid-template-columns: 1fr;
            }

            .container {
                padding: 10px;
            }

            header {
                padding: 15px;
            }

            .time-display {
                font-size: 12px;
                min-width: 90px;
            }
        }

        /* 履歴画面のグリッド表示用スタイル */
        #history-list.videos-grid {
            display: grid !important;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 25px;
            margin-top: 20px;
        }

        /* 履歴アイテムのカードスタイル */
        .history-card {
            background-color: #1a1a1a;
            border-radius: 12px;
            overflow: hidden;
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
            position: relative;
        }

        .history-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.5);
        }

        /* 履歴サムネイル */
        .history-thumbnail {
            width: 100%;
            aspect-ratio: 16/9;
            background-color: #2d2d2d;
            position: relative;
            overflow: hidden;
        }

        .history-thumbnail img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* 履歴情報 */
        .history-content {
            padding: 15px;
        }

        .history-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            line-height: 1.4;
            height: 44px;
        }

        .history-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: #aaa;
            margin-top: 10px;
        }

        /* 履歴削除ボタン */
        .history-delete-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #ff4757;
        }

        .history-delete-btn:hover {
            color: #ff3742;
        }

        /* 履歴日時 */
        .history-date {
            font-size: 11px;
            color: #888;
        }

        /* 空の履歴メッセージ */
        .history-empty {
            grid-column: 1 / -1;
            text-align: center;
            padding: 60px 20px;
            color: #aaa;
            font-size: 16px;
        }
    </style>
</head>

<body>
    <!-- サイドバー -->
    <div class="sidebar">
        <div class="sidebar-title">IzuVidPlayer</div>
        <div class="sidebar-nav">
            <button class="nav-item active" id="home-nav">
                <svg class="nav-icon" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
                </svg>
                ホーム
            </button>
            <button class="nav-item" id="history-nav">
                <svg class="nav-icon" viewBox="0 0 24 24" fill="currentColor">
                    <path
                        d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z" />
                </svg>
                履歴
            </button>
            <button class="nav-item" id="favorites-nav">
                <svg class="nav-icon" viewBox="0 0 24 24" fill="currentColor">
                    <path
                        d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                </svg>
                お気に入り
            </button>
            <button class="nav-item" id="about-nav">
                <svg class="nav-icon" viewBox="0 0 24 24" fill="currentColor">
                    <path
                        d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z" />
                </svg>
                このページについて
            </button>
        </div>
    </div>

    <!-- メインコンテンツ -->
    <div class="main-content">
        <div class="container">
            <!-- ホーム/検索画面 -->
            <div id="home-container">
                <!-- ヘッダーと検索フォーム -->
                <header>
                    <div class="search-container">
                        <div class="search-box">
                            <input type="text" id="search-input" placeholder="動画を検索...">
                        </div>
                        <div class="buttons">
                            <button id="search-button">検索</button>
                            <button id="home-button" class="secondary">ホーム</button>
                        </div>
                    </div>

                    <div class="search-options">
                        <div class="option-group">
                            <label for="sort-option">並べ替え</label>
                            <select id="sort-option">
                                <option value="relevance">関連性</option>
                                <option value="uploaddate">最新</option>
                                <option value="rating">評価</option>
                                <option value="views">視聴回数</option>
                                <option value="random">ランダム</option>
                            </select>
                        </div>

                        <div class="option-group">
                            <label for="date-option">作成日時</label>
                            <select id="date-option">
                                <option value="all">すべて</option>
                                <option value="today">ここ3日間</option>
                                <option value="week">今週</option>
                                <option value="month">今月</option>
                                <option value="3month">ここ3ヶ月</option>
                                <option value="6month">ここ6ヶ月</option>
                            </select>
                        </div>

                        <div class="option-group">
                            <label for="duration-option">動画の長さ</label>
                            <select id="duration-option">
                                <option value="allduration">全て</option>
                                <option value="1-3min">短い動画 (1-3分)</option>
                                <option value="3-10min">中程度 (3-10分)</option>
                                <option value="10min_more">長い動画 (+10分)</option>
                                <option value="10-20min">長編動画 (10-20分)</option>
                                <option value="20min_more">長編動画 (20分以上)</option>
                            </select>
                        </div>

                        <div class="option-group">
                            <label for="quality-option">画質</label>
                            <select id="quality-option">
                                <option value="all">全て</option>
                                <option value="hd">720P以上</option>
                                <option value="1080P">1080P+</option>
                            </select>
                        </div>

                        <div class="option-group">
                            <label for="page-option">ページ番号</label>
                            <input type="number" id="page-option" min="1" value="1" placeholder="1">
                        </div>
                    </div>
                </header>

                <!-- ローディング表示 -->
                <div id="loading" class="loading">
                    読み込み中...
                </div>

                <!-- エラーメッセージ -->
                <div id="error-message" class="error-message">
                    エラーが発生しました。もう一度お試しください。
                </div>

                <!-- 動画グリッド(初期画面・検索結果) -->
                <div id="videos-grid-container">
                    <div class="videos-grid" id="videos-grid">
                        <!-- 動画カードはJavaScriptで生成 -->
                    </div>
                </div>
            </div>

            <!-- 履歴画面部分(約300行目付近)の変更 -->
            <div id="history-container" class="history-favorites-container">
                <h2 class="section-title">視聴履歴</h2>

                <!-- 履歴設定コントロール -->
                <div class="history-controls">
                    <button id="clear-history-btn" class="secondary">履歴を全て削除</button>
                    <label class="history-toggle">
                        <input type="checkbox" id="history-toggle-checkbox" checked>
                        <span>履歴を記録する</span>
                    </label>
                    <button id="delete-selected-btn" class="secondary" style="display:none;">選択項目を削除</button>
                </div>

                <div class="search-history">
                    <input type="text" class="search-history-input" id="search-history-input" placeholder="履歴を検索...">
                    <div class="history-list" id="history-list">
                        <!-- 履歴項目はJavaScriptで生成 -->
                    </div>
                </div>
            </div>
            <!-- 履歴画面の下(約310行目付近)に追加 -->
            <div id="about-container" class="history-favorites-container">
                <h2 class="section-title">このページについて</h2>
                <div class="about-content" id="about-content">
                    <!-- コンテンツはJavaScriptで設定 -->
                </div>
            </div>
            <style>
                /* 履歴コントロールの調整 */
                .history-controls {
                    display: flex;
                    gap: 15px;
                    margin-bottom: 20px;
                    padding: 15px;
                    background-color: #2d2d2d;
                    border-radius: 8px;
                    flex-wrap: wrap;
                    align-items: center;
                }

                .history-toggle {
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    cursor: pointer;
                    color: #f1f1f1;
                }

                .history-toggle input[type="checkbox"] {
                    width: 18px;
                    height: 18px;
                    cursor: pointer;
                }

                .history-item {
                    padding: 15px;
                    background-color: #2d2d2d;
                    border-radius: 8px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    cursor: pointer;
                    transition: background-color 0.3s;
                    position: relative;
                }

                .history-item:hover {
                    background-color: #3d3d3d;
                }

                .history-item.selected {
                    background-color: rgba(255, 71, 87, 0.2);
                    border-left: 4px solid #ff4757;
                }

                .history-checkbox {
                    margin-right: 15px;
                    width: 18px;
                    height: 18px;
                    cursor: pointer;
                }

                #history-container .videos-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                    gap: 25px;
                    margin-top: 20px;
                }

                #search-history-input {
                    width: 100%;
                    padding: 12px 20px;
                    background-color: #2d2d2d;
                    border: 2px solid #3d3d3d;
                    border-radius: 8px;
                    color: white;
                    font-size: 16px;
                    margin-bottom: 20px;
                }

                /* 履歴リストのグリッドレイアウト設定 */
                #history-list.videos-grid {

                    display: grid !important;
                    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                    gap: 25px;
                    margin-top: 20px;
                    width: 100%;
                }

                /* 履歴サムネイル */
                .history-thumbnail {
                    width: 120px;
                    height: 68px;
                    border-radius: 4px;
                    overflow: hidden;
                    flex-shrink: 0;
                    margin-right: 15px;
                    background-color: #1a1a1a;
                    position: relative;
                }

                .history-thumbnail img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                /* 履歴情報 */
                .history-info {
                    flex: 1;
                    min-width: 0;
                    overflow: hidden;
                }

                .history-title {
                    font-size: 16px;
                    font-weight: 600;
                    margin-bottom: 5px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .history-meta {
                    display: flex;
                    gap: 15px;
                    flex-wrap: wrap;
                    font-size: 13px;
                    color: #aaa;
                }

                /* 履歴アクションボタン */
                .history-actions {
                    display: flex;
                    gap: 10px;
                    flex-shrink: 0;
                }

                /* レスポンシブ対応 */
                @media (max-width: 768px) {
                    .history-item {
                        flex-direction: column;
                        align-items: flex-start;
                    }

                    .history-thumbnail {
                        width: 100%;
                        height: 180px;
                        margin-right: 0;
                        margin-bottom: 10px;
                    }

                    .history-actions {
                        width: 100%;
                        justify-content: flex-end;
                        margin-top: 10px;
                    }

                    .history-info {
                        width: 100%;
                    }
                }

                @media (max-width: 480px) {
                    .history-thumbnail {
                        height: 150px;
                    }

                    .history-actions {
                        flex-direction: column;
                    }

                    .history-actions button {
                        width: 100%;
                    }
                }

                /* このページについてスタイル */
                .about-content {
                    padding: 20px;
                    background-color: #2d2d2d;
                    border-radius: 8px;
                    line-height: 1.6;
                    color: #e3e3e3;
                }

                .about-content h3 {
                    margin: 20px 0 10px 0;
                    color: #ff4757;
                }

                .about-content h3:first-child {
                    margin-top: 0;
                }

                .about-content p {
                    margin-bottom: 15px;
                }

                .about-content ul {
                    padding-left: 20px;
                    margin-bottom: 15px;
                }

                .about-content li {
                    margin-bottom: 8px;
                }
            </style>

            <!-- お気に入り画面 -->
            <div id="favorites-container" class="history-favorites-container">
                <h2 class="section-title">お気に入り動画</h2>
                <div class="search-history">
                    <input type="text" class="search-history-input" id="search-favorites-input"
                        placeholder="お気に入りを検索...">
                    <div class="videos-grid" id="favorites-grid">
                        <!-- お気に入り動画はJavaScriptで生成 -->
                    </div>
                </div>
            </div>

            <!-- 動画プレーヤー画面 -->
            <div id="video-player-container" class="video-player-container">
                <div class="back-button">
                    <button id="back-button" class="secondary">← 戻る</button>
                </div>

                <div class="video-wrapper">
                    <video id="main-video" playsinline></video>

                    <!-- 動画読み込み中のアニメーション -->
                    <div class="video-loading" id="video-loading">
                        <div class="spinner"></div>
                    </div>

                    <!-- カスタムコントロールバー -->
                    <div class="custom-controls">
                        <div class="progress-container" id="progress-container">
                            <div class="progress-buffer" id="progress-buffer"></div>
                            <div class="progress-bar" id="progress-bar"></div>
                            <div class="progress-time-tooltip" id="progress-time-tooltip">00:00</div>
                        </div>

                        <div class="controls-row">
                            <div class="left-controls">
                                <button class="control-btn" id="play-pause-btn">
                                    <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960"
                                        width="24px" fill="#e3e3e3">
                                        <path d="M320-200v-560l440 280-440 280Zm80-280Zm0 134 210-134-210-134v268Z" />
                                    </svg>
                                </button>

                                <div class="volume-controls">
                                    <button class="control-btn" id="volume-btn">
                                        <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960"
                                            width="24px" fill="#e3e3e3">
                                            <path
                                                d="M560-131v-82q90-26 145-100t55-168q0-94-55-168T560-749v-82q124 28 202 125.5T840-481q0 127-78 224.5T560-131ZM120-360v-240h160l200-200v640L280-360H120Zm440 40v-322q47 22 73.5 66t26.5 96q0 51-26.5 94.5T560-320ZM400-606l-86 86H200v80h114l86 86v-252ZM300-480Z" />
                                        </svg>
                                    </button>
                                    <div class="volume-slider" id="volume-slider">
                                        <div class="volume-level" id="volume-level"></div>
                                    </div>
                                </div>

                                <div class="time-display" id="time-display">00:00 / 00:00</div>
                            </div>

                            <div class="right-controls">
                                <div class="speed-controls">
                                    <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960"
                                        width="24px" fill="#e3e3e3">
                                        <path
                                            d="M480-316.5q38-.5 56-27.5l224-336-336 224q-27 18-28.5 55t22.5 61q24 24 62 23.5Zm0-483.5q59 0 113.5 16.5T696-734l-76 48q-33-17-68.5-25.5T480-720q-133 0-226.5 93.5T160-400q0 42 11.5 83t32.5 77h552q23-38 33.5-79t10.5-85q0-36-8.5-70T766-540l48-76q30 47 47.5 100T880-406q1 57-13 109t-41 99q-11 18-30 28t-40 10H204q-21 0-40-10t-30-28q-26-45-40-95.5T80-400q0-83 31.5-155.5t86-127Q252-737 325-768.5T480-800Zm7 313Z" />
                                    </svg>
                                    <div class="speed-slider" id="speed-slider">
                                        <div class="speed-level" id="speed-level"></div>
                                    </div>
                                    <div class="speed-value" id="speed-value">1.0x</div>
                                </div>

                                <button class="control-btn" id="pip-btn">
                                    <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960"
                                        width="24px" fill="#e3e3e3">
                                        <path
                                            d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z" />
                                    </svg>
                                </button>

                                <button class="control-btn" id="fullscreen-btn">
                                    <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960"
                                        width="24px" fill="#e3e3e3">
                                        <path
                                            d="M120-120v-200h80v120h120v80H120Zm520 0v-80h120v-120h80v200H640ZM120-640v-200h200v80H200v120h-80Zm640 0v-120H640v-80h200v200h-80Z" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div id="video-details" class="video-details">
                    <!-- 動画詳細はJavaScriptで生成 -->
                </div>

                <div id="quality-selector" class="quality-selector">
                    <!-- 画質選択はJavaScriptで生成 -->
                </div>

                <div id="related-videos-container" class="related-videos">
                    <h2>関連動画</h2>
                    <div class="videos-grid" id="related-videos-grid">
                        <!-- 関連動画はJavaScriptで生成 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- HLS.js スクリプト -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/hls.js/1.4.10/hls.min.js"></script>

    <script>
        // CORS Proxy URL(キャッシュ防止用ランダムパラメータ追加)
        const getCorsProxyUrl = (url) => {
            const randomNum = Math.floor(10000 + Math.random() * 90000);
            return `https://izuemon-any-env-code.hf.space/cors-proxy?url=${encodeURIComponent(url)}&uvrqu=${randomNum}`;
        };

        const BASE_URL = 'https://www.xvideos.com/';

        // 状態管理
        let currentView = 'home'; // 'home', 'history', 'favorites', 'player'
        let currentVideoData = null;
        let currentHLSPlaylist = null;
        let hlsPlayer = null;
        let currentQualityUrl = '';

        // ストレージ管理
        const storage = {
            // 履歴の取得
            getHistory: () => {
                const history = localStorage.getItem('videoHistory');
                return history ? JSON.parse(history) : [];
            },

            // 履歴の保存
            saveHistory: (history) => {
                localStorage.setItem('videoHistory', JSON.stringify(history));
            },

            addToHistory: (video) => {
                // 履歴が無効なら追加しない
                if (!storage.getHistoryEnabled()) {
                    return;
                }

                const history = storage.getHistory();
                const existingIndex = history.findIndex(item => item.url === video.url);

                // 完全な動画データで上書き
                if (existingIndex > -1) {
                    history.splice(existingIndex, 1);
                }

                history.unshift({
                    url: video.url,
                    pageUrl: video.pageUrl || video.url,
                    title: video.title || '不明なタイトル',
                    thumbnail: video.thumbnail || '',  // サムネイルURLを確実に保存
                    hoverVideo: video.hoverVideo || '',
                    duration: video.duration || '',
                    quality: video.quality || '',
                    watchedAt: new Date().toISOString(),
                    description: video.description || '',
                    views: video.views || '',
                    uploadDate: video.uploadDate || '',
                    hlsUrl: video.hlsUrl || '',
                    videoUrl: video.videoUrl || video.url
                });

                if (history.length > 50) {
                    history.pop();
                }

                storage.saveHistory(history);
            },
            updateHistoryItem: (url, updates) => {
                const history = storage.getHistory();
                const index = history.findIndex(item => item.url === url || item.pageUrl === url);

                if (index > -1) {
                    history[index] = {
                        ...history[index],
                        ...updates,
                        // 更新時間も更新
                        updatedAt: new Date().toISOString()
                    };
                    storage.saveHistory(history);
                }
            },
            // お気に入りの取得
            getFavorites: () => {
                const favorites = localStorage.getItem('videoFavorites');
                return favorites ? JSON.parse(favorites) : [];
            },

            // お気に入りの保存
            saveFavorites: (favorites) => {
                localStorage.setItem('videoFavorites', JSON.stringify(favorites));
            },

            // お気に入りの追加
            addToFavorites: (video) => {
                const favorites = storage.getFavorites();
                const existingIndex = favorites.findIndex(item => item.url === video.url);

                if (existingIndex === -1) {
                    favorites.push({
                        ...video,
                        favoritedAt: new Date().toISOString()
                    });
                    storage.saveFavorites(favorites);
                    return true;
                }
                return false;
            },

            // お気に入りの削除
            removeFromFavorites: (videoUrl) => {
                const favorites = storage.getFavorites();
                const filtered = favorites.filter(item => item.url !== videoUrl);
                storage.saveFavorites(filtered);
                return filtered;
            },

            // お気に入りかどうかの確認
            isFavorite: (videoUrl) => {
                const favorites = storage.getFavorites();
                return favorites.some(item => item.url === videoUrl);
            },
            // 履歴設定の取得
            getHistoryEnabled: () => {
                const enabled = localStorage.getItem('historyEnabled');
                return enabled === null ? true : JSON.parse(enabled);
            },

            // 履歴設定の保存
            setHistoryEnabled: (enabled) => {
                localStorage.setItem('historyEnabled', JSON.stringify(enabled));
            }
        };

        // DOM要素
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        const homeButton = document.getElementById('home-button');
        const backButton = document.getElementById('back-button');
        const videosGrid = document.getElementById('videos-grid');
        const videosGridContainer = document.getElementById('videos-grid-container');
        const videoPlayerContainer = document.getElementById('video-player-container');
        const mainVideo = document.getElementById('main-video');
        const videoDetails = document.getElementById('video-details');
        const qualitySelector = document.getElementById('quality-selector');
        const relatedVideosGrid = document.getElementById('related-videos-grid');
        const relatedVideosContainer = document.getElementById('related-videos-container');
        const loadingElement = document.getElementById('loading');
        const errorElement = document.getElementById('error-message');
        const videoLoadingElement = document.getElementById('video-loading');

        // カスタムコントロール要素
        const playPauseBtn = document.getElementById('play-pause-btn');
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const progressBuffer = document.getElementById('progress-buffer');
        const progressTimeTooltip = document.getElementById('progress-time-tooltip');
        const volumeBtn = document.getElementById('volume-btn');
        const volumeSlider = document.getElementById('volume-slider');
        const volumeLevel = document.getElementById('volume-level');
        const speedSlider = document.getElementById('speed-slider');
        const speedLevel = document.getElementById('speed-level');
        const speedValue = document.getElementById('speed-value');
        const timeDisplay = document.getElementById('time-display');
        const pipBtn = document.getElementById('pip-btn');
        const fullscreenBtn = document.getElementById('fullscreen-btn');

        // ナビゲーション要素
        const homeNav = document.getElementById('home-nav');
        const historyNav = document.getElementById('history-nav');
        const favoritesNav = document.getElementById('favorites-nav');

        // 画面コンテナ
        const homeContainer = document.getElementById('home-container');
        const historyContainer = document.getElementById('history-container');
        const favoritesContainer = document.getElementById('favorites-container');

        // 履歴・お気に入り要素
        const historyList = document.getElementById('history-list');
        const favoritesGrid = document.getElementById('favorites-grid');
        const searchHistoryInput = document.getElementById('search-history-input');
        const searchFavoritesInput = document.getElementById('search-favorites-input');

        // 検索オプション
        const sortOption = document.getElementById('sort-option');
        const dateOption = document.getElementById('date-option');
        const durationOption = document.getElementById('duration-option');
        const qualityOption = document.getElementById('quality-option');
        const pageOption = document.getElementById('page-option');

        // コントロール状態
        let isDraggingProgress = false;
        let isDraggingVolume = false;
        let isDraggingSpeed = false;
        let lastVolume = 1.0;
        const aboutNav = document.getElementById('about-nav');
        const aboutContainer = document.getElementById('about-container');
        const aboutContent = document.getElementById('about-content');
        const clearHistoryBtn = document.getElementById('clear-history-btn');
        const historyToggleCheckbox = document.getElementById('history-toggle-checkbox');
        const deleteSelectedBtn = document.getElementById('delete-selected-btn');

        // 3. ナビゲーションイベントに「このページについて」を追加
        aboutNav.addEventListener('click', () => {
            showView('about');
            loadAboutContent();
        });

        // 4. 履歴コントロールのイベントリスナー
        clearHistoryBtn.addEventListener('click', clearAllHistory);
        historyToggleCheckbox.addEventListener('change', toggleHistoryRecording);
        deleteSelectedBtn.addEventListener('click', deleteSelectedHistoryItems);

        // 5. 「このページについて」コンテンツの読み込み
        function loadAboutContent() {
            const aboutHTML = `<p>このページはテストページです</p>
    <h3>機能説明</h3>
    <ul>
        <li>動画の検索と再生</li>
        <li>視聴履歴の記録</li>
        <li>お気に入り動画の保存</li>
        <li>複数の画質で再生・ダウンロード</li>
    </ul>
    <h3>履歴設定</h3>
    <p>履歴の記録は設定から無効化できます。</p>`;

            aboutContent.innerHTML = aboutHTML;
        }

        // 6. 履歴設定の読み込み
        function loadHistorySettings() {
            const isEnabled = storage.getHistoryEnabled();
            historyToggleCheckbox.checked = isEnabled;
        }

        // 7. 履歴機能の有効/無効切り替え
        function toggleHistoryRecording() {
            const isEnabled = historyToggleCheckbox.checked;
            storage.setHistoryEnabled(isEnabled);

            if (!isEnabled) {
                // 履歴を無効にする場合は確認
                if (confirm('履歴の記録を無効にすると、新しい視聴履歴が記録されなくなります。よろしいですか?')) {
                    // 必要に応じて既存の履歴をクリア
                    // clearAllHistory(); // コメントアウトを外すと履歴もクリアされます
                } else {
                    historyToggleCheckbox.checked = true;
                    storage.setHistoryEnabled(true);
                }
            }
        }

        // 8. 履歴の全削除
        function clearAllHistory() {
            if (confirm('すべての視聴履歴を削除しますか?この操作は元に戻せません。')) {
                storage.saveHistory([]);
                loadHistory();
                alert('履歴を全て削除しました。');
            }
        }

        // 9. 履歴の選択削除機能の強化
        let selectedHistoryItems = [];
        // 履歴の表示(タイル形式 - 新しいバージョン)
        function displayHistory(history) {
            historyList.innerHTML = '';

            if (history.length === 0) {
                historyList.innerHTML = '<div class="history-empty">視聴履歴はありません</div>';
                return;
            }

            // 履歴リストをグリッドレイアウトに設定
            historyList.className = 'videos-grid';

            // 履歴を新しい順に表示
            history.forEach((item, index) => {
                const card = document.createElement('div');
                card.className = 'video-card';
                card.dataset.url = item.pageUrl || item.url;

                // サムネイルコンテナ
                const thumbnailContainer = document.createElement('div');
                thumbnailContainer.className = 'thumbnail-container';

                // サムネイル画像(保存されたサムネイルを使用)
                const thumbnail = document.createElement('img');
                thumbnail.className = 'thumbnail';
                thumbnail.loading = 'lazy';

                // サムネイルURLの設定(保存されたものがあれば使用)
                if (item.thumbnail && item.thumbnail.trim() !== '') {
                    thumbnail.src = item.thumbnail;
                } else {
                    // デフォルトのプレースホルダー画像
                    thumbnail.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQwIiBoZWlnaHQ9IjEzNSIgdmlld0JveD0iMCAwIDI0MCAxMzUiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHJlY3Qgd2lkdGg9IjI0MCIgaGVpZ2h0PSIxMzUiIGZpbGw9IiMxYTFhMWEiLz48cGF0aCBkPSJNOTYgNjcuNUw3MiA3NVY2MEw5NiA2Ny41WiIgZmlsbD0iIzMzMyIvPjxwYXRoIGQ9Ik05NiA2Ny41TDcyIDc1VjYwTDk2IDY3LjVaIiBmaWxsPSIjZmY0NzU3Ii8+PC9zdmc+';
                }
                thumbnail.alt = item.title || '履歴動画';

                // 動画長バッジ
                if (item.duration) {
                    const durationBadge = document.createElement('div');
                    durationBadge.className = 'duration';
                    durationBadge.textContent = item.duration;
                    thumbnailContainer.appendChild(durationBadge);
                }

                // 視聴日時バッジ
                const dateBadge = document.createElement('div');
                dateBadge.style.cssText = `
            position: absolute;
            top: 10px;
            left: 10px;
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: normal;
            z-index: 2;
        `;
                const watchedDate = new Date(item.watchedAt);
                dateBadge.textContent = `${watchedDate.getMonth() + 1}/${watchedDate.getDate()} ${watchedDate.getHours().toString().padStart(2, '0')}:${watchedDate.getMinutes().toString().padStart(2, '0')}`;
                thumbnailContainer.appendChild(dateBadge);

                thumbnailContainer.appendChild(thumbnail);

                // 動画情報
                const videoInfo = document.createElement('div');
                videoInfo.className = 'video-info';

                const videoTitle = document.createElement('div');
                videoTitle.className = 'video-title';
                videoTitle.textContent = item.title || `動画 ${index + 1}`;

                const videoMetadata = document.createElement('div');
                videoMetadata.className = 'video-metadata';
                videoMetadata.style.cssText = `
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
        `;

                // 視聴回数(あれば)
                const viewsContainer = document.createElement('span');
                if (item.views) {
                    try {
                        const views = parseInt(item.views);
                        if (!isNaN(views)) {
                            viewsContainer.textContent = `${views.toLocaleString()} 回視聴`;
                        }
                    } catch (e) {
                        console.log('視聴回数のパースエラー:', e);
                    }
                }

                // 削除ボタン(ダウンロードボタンはなし)
                const deleteBtn = document.createElement('button');
                deleteBtn.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" height="18px" viewBox="0 -960 960 960" width="18px" fill="#ff4757">
                <path d="M280-120q-33 0-56.5-23.5T200-200v-520h-40v-80h200v-40h240v40h200v80h-40v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM360-280h80v-360h-80v360Zm160 0h80v-360h-80v360ZM280-720v520-520Z"/>
            </svg>
        `;
                deleteBtn.style.cssText = `
            background: none;
            border: none;
            cursor: pointer;
            padding: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
        `;
                deleteBtn.title = '履歴から削除';
                deleteBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    deleteSingleHistoryItem(index);
                });

                videoMetadata.appendChild(viewsContainer);
                videoMetadata.appendChild(deleteBtn);

                videoInfo.appendChild(videoTitle);
                videoInfo.appendChild(videoMetadata);

                card.appendChild(thumbnailContainer);
                card.appendChild(videoInfo);

                // クリックイベント - 動画を再生
                card.addEventListener('click', (e) => {
                    // 削除ボタン以外をクリックした場合
                    if (!e.target.closest('button')) {
                        loadVideo(item.pageUrl || item.url);
                    }
                });

                // ホバー効果
                card.addEventListener('mouseenter', () => {
                    card.style.transform = 'translateY(-5px)';
                    card.style.boxShadow = '0 10px 20px rgba(0, 0, 0, 0.5)';
                });

                card.addEventListener('mouseleave', () => {
                    card.style.transform = '';
                    card.style.boxShadow = '';
                });

                historyList.appendChild(card);
            });
        }
        // 10. 履歴選択の切り替え
        function toggleHistorySelection(index, isSelected) {
            if (isSelected) {
                selectedHistoryItems.push(index);
                const item = document.querySelector(`.history-item[data-index="${index}"]`);
                item.classList.add('selected');
            } else {
                selectedHistoryItems = selectedHistoryItems.filter(i => i !== index);
                const item = document.querySelector(`.history-item[data-index="${index}"]`);
                item.classList.remove('selected');
            }

            deleteSelectedBtn.style.display = selectedHistoryItems.length > 0 ? 'block' : 'none';
        }

        // 11. 選択した履歴項目の削除
        function deleteSelectedHistoryItems() {
            if (selectedHistoryItems.length === 0) return;

            if (confirm(`選択した${selectedHistoryItems.length}件の履歴を削除しますか?`)) {
                const history = storage.getHistory();
                // 選択されたインデックスを降順で削除(インデックスがずれないように)
                selectedHistoryItems.sort((a, b) => b - a).forEach(index => {
                    history.splice(index, 1);
                });

                storage.saveHistory(history);
                loadHistory();
                selectedHistoryItems = [];
                deleteSelectedBtn.style.display = 'none';
            }
        }

        // 12. 単一履歴項目の削除
        function deleteSingleHistoryItem(index) {
            if (confirm('この履歴を削除しますか?')) {
                const history = storage.getHistory();
                history.splice(index, 1);
                storage.saveHistory(history);
                loadHistory();
            }
        }

        // イベントリスナーの設定
        document.addEventListener('DOMContentLoaded', () => {
            loadHomeVideos();
            setupVideoControls();
            loadHistorySettings();
        });

        searchButton.addEventListener('click', () => {
            performSearch();
        });

        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                performSearch();
            }
        });

        homeButton.addEventListener('click', () => {
            loadHomeVideos();
        });

        backButton.addEventListener('click', () => {
            showVideoGrid();
        });

        // ナビゲーションイベント
        homeNav.addEventListener('click', () => {
            showView('home');
            loadHomeVideos();
        });

        historyNav.addEventListener('click', () => {
            showView('history');
            loadHistory();
        });

        favoritesNav.addEventListener('click', () => {
            showView('favorites');
            loadFavorites();
        });

        // 履歴検索
        searchHistoryInput.addEventListener('input', (e) => {
            filterHistory(e.target.value);
        });

        // お気に入り検索
        searchFavoritesInput.addEventListener('input', (e) => {
            filterFavorites(e.target.value);
        });

        // ビデオコントロールの設定
        function setupVideoControls() {
            // 再生/一時停止
            playPauseBtn.addEventListener('click', togglePlayPause);

            // プログレスバー
            progressContainer.addEventListener('mousedown', startProgressDrag);
            progressContainer.addEventListener('touchstart', startProgressDrag);
            document.addEventListener('mousemove', handleProgressDrag);
            document.addEventListener('touchmove', handleProgressDrag);
            document.addEventListener('mouseup', stopProgressDrag);
            document.addEventListener('touchend', stopProgressDrag);

            // プログレスバーホバー時の時間表示
            progressContainer.addEventListener('mousemove', updateProgressTooltip);
            progressContainer.addEventListener('mouseleave', () => {
                progressTimeTooltip.style.display = 'none';
            });

            // ボリュームコントロール
            volumeBtn.addEventListener('click', toggleMute);
            volumeSlider.addEventListener('mousedown', startVolumeDrag);
            volumeSlider.addEventListener('touchstart', startVolumeDrag);

            // 再生速度コントロール
            speedSlider.addEventListener('mousedown', startSpeedDrag);
            speedSlider.addEventListener('touchstart', startSpeedDrag);

            // PIPボタン
            pipBtn.addEventListener('click', togglePIP);

            // フルスクリーンボタン
            fullscreenBtn.addEventListener('click', toggleFullscreen);

            // 動画イベント
            mainVideo.addEventListener('play', updatePlayPauseIcon);
            mainVideo.addEventListener('pause', updatePlayPauseIcon);
            mainVideo.addEventListener('timeupdate', updateProgress);
            mainVideo.addEventListener('loadedmetadata', updateTimeDisplay);
            mainVideo.addEventListener('durationchange', updateTimeDisplay);
            mainVideo.addEventListener('volumechange', updateVolumeUI);
            mainVideo.addEventListener('waiting', () => {
                videoLoadingElement.style.display = 'block';
            });
            mainVideo.addEventListener('playing', () => {
                videoLoadingElement.style.display = 'none';
            });
            mainVideo.addEventListener('canplay', () => {
                videoLoadingElement.style.display = 'none';
            });

            // フルスクリーン変更検知
            document.addEventListener('fullscreenchange', updateFullscreenIcon);
            document.addEventListener('webkitfullscreenchange', updateFullscreenIcon);
            document.addEventListener('mozfullscreenchange', updateFullscreenIcon);
            document.addEventListener('MSFullscreenChange', updateFullscreenIcon);

            // PIP変更検知
            mainVideo.addEventListener('enterpictureinpicture', updatePIPIcon);
            mainVideo.addEventListener('leavepictureinpicture', updatePIPIcon);

            // 初期設定
            updatePlayPauseIcon();
            updateVolumeUI();
            updateSpeedUI();
        }

        // 再生/一時停止の切り替え
        function togglePlayPause() {
            if (mainVideo.paused) {
                mainVideo.play();
            } else {
                mainVideo.pause();
            }
        }

        // 再生/一時停止アイコンの更新
        function updatePlayPauseIcon() {
            const icon = playPauseBtn.querySelector('svg');
            if (mainVideo.paused) {
                icon.innerHTML = '<path d="M320-200v-560l440 280-440 280Zm80-280Zm0 134 210-134-210-134v268Z"/>';
            } else {
                icon.innerHTML = '<path d="M520-200v-560h240v560H520Zm-320 0v-560h240v560H200Zm400-80h80v-400h-80v400Zm-320 0h80v-400h-80v400Zm0-400v400-400Zm320 0v400-400Z"/>';
            }
        }

        // プログレスバー操作
        function startProgressDrag(e) {
            e.preventDefault();
            isDraggingProgress = true;
            updateProgressFromEvent(e);
        }

        function handleProgressDrag(e) {
            if (isDraggingProgress) {
                updateProgressFromEvent(e);
            }
        }

        function stopProgressDrag() {
            isDraggingProgress = false;
        }

        function updateProgressFromEvent(e) {
            if (!isDraggingProgress && e.type !== 'mousemove') return;

            const rect = progressContainer.getBoundingClientRect();
            const clientX = e.touches ? e.touches[0].clientX : e.clientX;
            let percent = (clientX - rect.left) / rect.width;
            percent = Math.max(0, Math.min(1, percent));

            const time = percent * mainVideo.duration;

            if (!isNaN(time)) {
                mainVideo.currentTime = time;
                updateProgress();
            }
        }

        // プログレスバーの更新
        function updateProgress() {
            if (mainVideo.duration) {
                const percent = (mainVideo.currentTime / mainVideo.duration) * 100;
                progressBar.style.width = percent + '%';

                // バッファリングの表示
                if (mainVideo.buffered.length > 0) {
                    const bufferedEnd = mainVideo.buffered.end(mainVideo.buffered.length - 1);
                    const bufferedPercent = (bufferedEnd / mainVideo.duration) * 100;
                    progressBuffer.style.width = bufferedPercent + '%';
                }

                updateTimeDisplay();
            }
        }

        // プログレスバーツールチップの更新
        function updateProgressTooltip(e) {
            const rect = progressContainer.getBoundingClientRect();
            const clientX = e.clientX;
            let percent = (clientX - rect.left) / rect.width;
            percent = Math.max(0, Math.min(1, percent));

            const time = percent * mainVideo.duration;
            const timeStr = formatTime(time);

            progressTimeTooltip.textContent = timeStr;
            progressTimeTooltip.style.left = (percent * 100) + '%';
            progressTimeTooltip.style.display = 'block';
        }

        // 時間表示の更新
        function updateTimeDisplay() {
            if (mainVideo.duration) {
                const currentTime = formatTime(mainVideo.currentTime);
                const duration = formatTime(mainVideo.duration);
                timeDisplay.textContent = `${currentTime} / ${duration}`;
            }
        }

        // 時間のフォーマット
        function formatTime(seconds) {
            if (isNaN(seconds)) return '00:00';

            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = Math.floor(seconds % 60);

            if (hours > 0) {
                return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            } else {
                return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            }
        }

        // ミュート切り替え
        function toggleMute() {
            if (mainVideo.volume > 0) {
                lastVolume = mainVideo.volume;
                mainVideo.volume = 0;
            } else {
                mainVideo.volume = lastVolume;
            }
            updateVolumeUI();
        }

        // ボリュームUIの更新
        function updateVolumeUI() {
            const volume = mainVideo.volume;
            const isMuted = mainVideo.muted || volume === 0;

            volumeLevel.style.width = (volume * 100) + '%';

            const icon = volumeBtn.querySelector('svg');
            if (isMuted || volume === 0) {
                icon.innerHTML = '<path d="M792-56 671-177q-25 16-53 27.5T560-131v-82q14-5 27.5-10t25.5-12L480-368v208L280-360H120v-240h128L56-792l56-56 736 736-56 56Zm-8-232-58-58q17-31 25.5-65t8.5-70q0-94-55-168T560-749v-82q124 28 202 125.5T840-481q0 53-14.5 102T784-288ZM650-422l-90-90v-130q47 22 73.5 66t26.5 96q0 15-2.5 29.5T650-422ZM480-592 376-696l104-104v208Zm-80 238v-94l-72-72H200v80h114l86 86Zm-36-130Z"/>';
            } else if (volume < 0.33) {
                icon.innerHTML = '<path d="M280-360v-240h160l200-200v640L440-360H280Zm80-80h114l86 86v-252l-86 86H360v80Zm100-40Z"/>';
            } else if (volume < 0.66) {
                icon.innerHTML = '<path d="M200-360v-240h160l200-200v640L360-360H200Zm440 40v-322q45 21 72.5 65t27.5 97q0 53-27.5 96T640-320ZM480-606l-86 86H280v80h114l86 86v-252ZM380-480Z"/>';
            } else {
                icon.innerHTML = '<path d="M560-131v-82q90-26 145-100t55-168q0-94-55-168T560-749v-82q124 28 202 125.5T840-481q0 127-78 224.5T560-131ZM120-360v-240h160l200-200v640L280-360H120Zm440 40v-322q47 22 73.5 66t26.5 96q0 51-26.5 94.5T560-320ZM400-606l-86 86H200v80h114l86 86v-252ZM300-480Z"/>';
            }
        }

        // ボリュームドラッグ
        function startVolumeDrag(e) {
            e.preventDefault();
            isDraggingVolume = true;
            updateVolumeFromEvent(e);

            document.addEventListener('mousemove', handleVolumeDrag);
            document.addEventListener('touchmove', handleVolumeDrag);
            document.addEventListener('mouseup', stopVolumeDrag);
            document.addEventListener('touchend', stopVolumeDrag);
        }

        function handleVolumeDrag(e) {
            if (isDraggingVolume) {
                updateVolumeFromEvent(e);
            }
        }

        function stopVolumeDrag() {
            isDraggingVolume = false;
            document.removeEventListener('mousemove', handleVolumeDrag);
            document.removeEventListener('touchmove', handleVolumeDrag);
            document.removeEventListener('mouseup', stopVolumeDrag);
            document.removeEventListener('touchend', stopVolumeDrag);
        }

        function updateVolumeFromEvent(e) {
            const rect = volumeSlider.getBoundingClientRect();
            const clientX = e.touches ? e.touches[0].clientX : e.clientX;
            let percent = (clientX - rect.left) / rect.width;
            percent = Math.max(0, Math.min(1, percent));

            mainVideo.volume = percent;
            updateVolumeUI();
        }

        // 再生速度ドラッグ
        function startSpeedDrag(e) {
            e.preventDefault();
            isDraggingSpeed = true;
            updateSpeedFromEvent(e);

            document.addEventListener('mousemove', handleSpeedDrag);
            document.addEventListener('touchmove', handleSpeedDrag);
            document.addEventListener('mouseup', stopSpeedDrag);
            document.addEventListener('touchend', stopSpeedDrag);
        }

        function handleSpeedDrag(e) {
            if (isDraggingSpeed) {
                updateSpeedFromEvent(e);
            }
        }

        function stopSpeedDrag() {
            isDraggingSpeed = false;
            document.removeEventListener('mousemove', handleSpeedDrag);
            document.removeEventListener('touchmove', handleSpeedDrag);
            document.removeEventListener('mouseup', stopSpeedDrag);
            document.removeEventListener('touchend', stopSpeedDrag);
        }

        function updateSpeedFromEvent(e) {
            const rect = speedSlider.getBoundingClientRect();
            const clientX = e.touches ? e.touches[0].clientX : e.clientX;
            let percent = (clientX - rect.left) / rect.width;
            percent = Math.max(0, Math.min(1, percent));

            // 0.25x から 3.0x までの範囲
            const speed = 0.25 + percent * 2.75;
            mainVideo.playbackRate = speed;
            updateSpeedUI();
        }

        // 再生速度UIの更新
        function updateSpeedUI() {
            const speed = mainVideo.playbackRate;
            const percent = (speed - 0.25) / 2.75 * 100;
            speedLevel.style.width = percent + '%';
            speedValue.textContent = speed.toFixed(1) + 'x';
        }

        // PIP切り替え
        function togglePIP() {
            if (document.pictureInPictureElement) {
                document.exitPictureInPicture();
            } else if (document.pictureInPictureEnabled) {
                mainVideo.requestPictureInPicture();
            }
        }

        // PIPアイコンの更新
        function updatePIPIcon() {
            const icon = pipBtn.querySelector('svg');
            if (document.pictureInPictureElement) {
                icon.innerHTML = '<path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v280h-80v-280H200v560h280v80H200Zm360 0v-80h144L332-572l56-56 372 371v-143h80v280H560Z"/>';
            } else {
                icon.innerHTML = '<path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z"/>';
            }
        }

        // フルスクリーン切り替え
        function toggleFullscreen() {
            const videoWrapper = document.querySelector('.video-wrapper');

            if (!document.fullscreenElement && !document.webkitFullscreenElement &&
                !document.mozFullScreenElement && !document.msFullscreenElement) {
                if (videoWrapper.requestFullscreen) {
                    videoWrapper.requestFullscreen();
                } else if (videoWrapper.webkitRequestFullscreen) {
                    videoWrapper.webkitRequestFullscreen();
                } else if (videoWrapper.mozRequestFullScreen) {
                    videoWrapper.mozRequestFullScreen();
                } else if (videoWrapper.msRequestFullscreen) {
                    videoWrapper.msRequestFullscreen();
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            }
        }

        // フルスクリーンアイコンの更新
        function updateFullscreenIcon() {
            const icon = fullscreenBtn.querySelector('svg');
            if (document.fullscreenElement || document.webkitFullscreenElement ||
                document.mozFullScreenElement || document.msFullscreenElement) {
                icon.innerHTML = '<path d="M240-120v-120H120v-80h200v200h-80Zm400 0v-200h200v80H720v120h-80ZM120-640v-80h120v-120h80v200H120Zm520 0v-200h80v120h120v80H640Z"/>';
            } else {
                icon.innerHTML = '<path d="M120-120v-200h80v120h120v80H120Zm520 0v-80h120v-120h80v200H640ZM120-640v-200h200v80H200v120h-80Zm640 0v-120H640v-80h200v200h-80Z"/>';
            }
        }

        function showView(view) {
            // すべてのビューを非表示
            homeContainer.style.display = 'none';
            historyContainer.style.display = 'none';
            favoritesContainer.style.display = 'none';
            videoPlayerContainer.style.display = 'none';
            aboutContainer.style.display = 'none';

            // アクティブなナビを更新
            homeNav.classList.remove('active');
            historyNav.classList.remove('active');
            favoritesNav.classList.remove('active');
            aboutNav.classList.remove('active');

            // 選択したビューを表示
            switch (view) {
                case 'home':
                    homeContainer.style.display = 'block';
                    homeNav.classList.add('active');
                    break;
                case 'history':
                    historyContainer.style.display = 'block';
                    historyNav.classList.add('active');
                    break;
                case 'favorites':
                    favoritesContainer.style.display = 'block';
                    favoritesNav.classList.add('active');
                    break;
                case 'player':
                    videoPlayerContainer.style.display = 'block';
                    break;
                case 'about':
                    aboutContainer.style.display = 'block';
                    aboutNav.classList.add('active');
                    break;
            }

            currentView = view;
        }
        function addToHistoryWithCheck(video) {
            if (!storage.getHistoryEnabled()) {
                return; // 履歴が無効なら追加しない
            }

            const history = storage.getHistory();
            const existingIndex = history.findIndex(item => item.url === video.url);

            if (existingIndex > -1) {
                history.splice(existingIndex, 1);
            }

            history.unshift({
                ...video,
                watchedAt: new Date().toISOString()
            });

            if (history.length > 50) {
                history.pop();
            }

            storage.saveHistory(history);
        }
        function loadHistory() {
            const history = storage.getHistory();
            loadHistorySettings(); // 設定を読み込む
            displayHistory(history);
        }
        // 履歴の表示
        function displayHistory(history) {
            historyList.innerHTML = '';

            if (history.length === 0) {
                historyList.innerHTML = '<div style="text-align:center;padding:40px;color:#aaa;">視聴履歴はありません</div>';
                return;
            }

            history.forEach((item, index) => {
                const historyItem = document.createElement('div');
                historyItem.className = 'history-item';

                const historyInfo = document.createElement('div');
                historyInfo.className = 'history-info';

                const historyTitle = document.createElement('div');
                historyTitle.className = 'history-title';
                historyTitle.textContent = item.title || `動画 ${index + 1}`;

                const historyDate = document.createElement('div');
                historyDate.className = 'history-date';
                historyDate.textContent = new Date(item.watchedAt).toLocaleString('ja-JP');

                historyInfo.appendChild(historyTitle);
                historyInfo.appendChild(historyDate);

                const downloadBtn = document.createElement('button');
                downloadBtn.className = 'download-btn';
                downloadBtn.textContent = 'ダウンロード';
                downloadBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    downloadVideo(item);
                });

                historyItem.appendChild(historyInfo);
                historyItem.appendChild(downloadBtn);

                historyItem.addEventListener('click', () => {
                    loadVideo(item.url);
                });

                historyList.appendChild(historyItem);
            });
        }

        // 履歴のフィルタリング
        function filterHistory(query) {
            const history = storage.getHistory();
            const filtered = history.filter(item =>
                item.title.toLowerCase().includes(query.toLowerCase())
            );
            displayHistory(filtered);
        }

        // お気に入りの読み込み
        function loadFavorites() {
            const favorites = storage.getFavorites();
            displayFavorites(favorites);
        }

        // お気に入りの表示
        function displayFavorites(favorites) {
            favoritesGrid.innerHTML = '';

            if (favorites.length === 0) {
                favoritesGrid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:40px;color:#aaa;">お気に入りの動画はありません</div>';
                return;
            }

            favorites.forEach((favorite) => {
                createFavoriteCard(favorite);
            });
        }

        // お気に入りカードの作成
        function createFavoriteCard(video) {
            const card = document.createElement('div');
            card.className = 'video-card';
            card.dataset.url = video.url;

            // サムネイルコンテナ
            const thumbnailContainer = document.createElement('div');
            thumbnailContainer.className = 'thumbnail-container';

            // サムネイル画像
            const thumbnail = document.createElement('img');
            thumbnail.className = 'thumbnail';
            thumbnail.src = video.thumbnail;
            thumbnail.alt = video.title;
            thumbnail.loading = 'lazy';

            // ホバー動画
            const hoverVideo = document.createElement('video');
            hoverVideo.className = 'hover-video';
            hoverVideo.muted = true;
            hoverVideo.loop = true;
            hoverVideo.preload = 'none';

            if (video.hoverVideo) {
                const source = document.createElement('source');
                source.src = video.hoverVideo;
                source.type = 'video/mp4';
                hoverVideo.appendChild(source);
            }

            // 画質バッジ
            if (video.quality) {
                const qualityBadge = document.createElement('div');
                qualityBadge.className = 'quality-badge';
                qualityBadge.textContent = video.quality;
                thumbnailContainer.appendChild(qualityBadge);
            }

            // 動画長
            if (video.duration) {
                const durationBadge = document.createElement('div');
                durationBadge.className = 'duration';
                durationBadge.textContent = video.duration;
                thumbnailContainer.appendChild(durationBadge);
            }

            thumbnailContainer.appendChild(thumbnail);
            thumbnailContainer.appendChild(hoverVideo);

            // 動画情報
            const videoInfo = document.createElement('div');
            videoInfo.className = 'video-info';

            const videoTitle = document.createElement('div');
            videoTitle.className = 'video-title';
            videoTitle.textContent = video.title;

            const videoMetadata = document.createElement('div');
            videoMetadata.className = 'video-metadata';

            const videoMeta = document.createElement('span');
            videoMeta.textContent = video.duration || '時間不明';

            const removeBtn = document.createElement('button');
            removeBtn.className = 'favorite-btn active';
            removeBtn.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 -960 960 960" width="20px">
                    <path d="m354-287 126-76 126 77-33-144 111-96-146-13-58-136-58 135-146 13 111 97-33 143ZM233-120l65-281L80-590l288-25 112-265 112 265 288 25-218 189 65 281-247-149-247 149Zm247-350Z"/>
                </svg>
            `;

            removeBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                storage.removeFromFavorites(video.url);
                card.remove();
                if (favoritesGrid.children.length === 0) {
                    favoritesGrid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:40px;color:#aaa;">お気に入りの動画はありません</div>';
                }
            });

            videoMetadata.appendChild(removeBtn);

            videoInfo.appendChild(videoTitle);
            videoInfo.appendChild(videoMetadata);

            card.appendChild(thumbnailContainer);
            card.appendChild(videoInfo);

            card.addEventListener('click', () => {
                // クリック時に動画データを保存してから読み込む
                const videoData = {
                    url: video.url,
                    pageUrl: video.url,
                    title: video.title,
                    thumbnail: video.thumbnail,
                    hoverVideo: video.hoverVideo,
                    duration: video.duration,
                    quality: video.quality
                };

                // 履歴に追加
                storage.addToHistory(videoData);

                // 動画を読み込み
                loadVideo(video.url);
            });

            // ホバーイベント
            card.addEventListener('mouseenter', () => {
                if (video.hoverVideo && hoverVideo.paused) {
                    hoverVideo.play().catch(e => console.log('ホバー動画の再生に失敗:', e));
                }
            });

            card.addEventListener('mouseleave', () => {
                if (!hoverVideo.paused) {
                    hoverVideo.pause();
                    hoverVideo.currentTime = 0;
                }
            });

            favoritesGrid.appendChild(card);
        }

        // お気に入りのフィルタリング
        function filterFavorites(query) {
            const favorites = storage.getFavorites();
            const filtered = favorites.filter(item =>
                item.title.toLowerCase().includes(query.toLowerCase())
            );

            favoritesGrid.innerHTML = '';
            if (filtered.length === 0) {
                favoritesGrid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:40px;color:#aaa;">一致する動画が見つかりませんでした</div>';
                return;
            }

            filtered.forEach(favorite => {
                createFavoriteCard(favorite);
            });
        }

        // ホーム動画の読み込み
        async function loadHomeVideos() {
            showLoading();
            hideError();
            currentView = 'home';
            showView('home');

            try {
                const url = BASE_URL;
                const proxyUrl = getCorsProxyUrl(url);

                const response = await fetch(proxyUrl);
                const html = await response.text();

                displayVideosFromHTML(html);
            } catch (error) {
                console.error('ホーム動画の読み込みエラー:', error);
                showError('動画の読み込みに失敗しました');
            } finally {
                hideLoading();
            }
        }

        // 検索の実行(修正:検索画面に移動しないバグを修正)
        function performSearch() {
            const query = searchInput.value.trim();
            if (!query) {
                loadHomeVideos();
                return;
            }

            showLoading();
            hideError();
            currentView = 'home'; // 検索結果もホーム画面で表示
            showView('home');

            // 検索パラメータの構築
            let searchUrl = `${BASE_URL}?k=${encodeURIComponent(query)}`;

            // ソートオプション
            const sortValue = sortOption.value;
            if (sortValue && sortValue !== 'relevance') {
                searchUrl += `&sort=${sortValue}`;
            }

            // 日付フィルター
            const dateValue = dateOption.value;
            if (dateValue && dateValue !== 'all') {
                searchUrl += `&datef=${dateValue}`;
            }

            // 動画長フィルター
            const durationValue = durationOption.value;
            if (durationValue && durationValue !== 'allduration') {
                searchUrl += `&durf=${durationValue}`;
            }

            // 画質フィルター
            const qualityValue = qualityOption.value;
            if (qualityValue && qualityValue !== 'all') {
                searchUrl += `&quality=${qualityValue}`;
            }

            // ページ番号
            const pageValue = pageOption.value;
            if (pageValue && pageValue > 1) {
                searchUrl += `&p=${pageValue}`;
            }

            // 検索実行
            fetchSearchResults(searchUrl);
        }

        // 検索結果の取得と表示
        async function fetchSearchResults(url) {
            try {
                const proxyUrl = getCorsProxyUrl(url);
                const response = await fetch(proxyUrl);
                const html = await response.text();

                displayVideosFromHTML(html);
            } catch (error) {
                console.error('検索エラー:', error);
                showError('検索に失敗しました');
            } finally {
                hideLoading();
            }
        }

        // HTMLから動画情報を抽出して表示
        function displayVideosFromHTML(html) {
            // 動画グリッドをクリア
            videosGrid.innerHTML = '';

            // HTMLをパースするための一時要素
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');

            // mozaiqueクラスを持つdivを探す
            const mozaiqueDivs = doc.querySelectorAll('div[class*="mozaique"]');

            if (mozaiqueDivs.length === 0) {
                videosGrid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:40px;color:#aaa;">動画が見つかりませんでした</div>';
                return;
            }

            // 各mozaique divを処理
            mozaiqueDivs.forEach((mozaiqueDiv) => {
                // mozaique内のdiv要素を取得
                const videoDivs = mozaiqueDiv.querySelectorAll('div');

                videoDivs.forEach((videoDiv, index) => {
                    // thumb-insideを探す
                    const thumbInside = videoDiv.querySelector('div.thumb-inside');
                    if (!thumbInside) return;

                    // thumbを探す
                    const thumb = thumbInside.querySelector('div.thumb');
                    if (!thumb) return;

                    // リンクと画像を取得
                    const link = thumb.querySelector('a');
                    if (!link) return;

                    const img = link.querySelector('img');
                    if (!img) return;

                    // 動画情報を抽出
                    const videoUrl = link.getAttribute('href') || '#';
                    const thumbnailUrl = img.getAttribute('data-src') || img.src;
                    const hoverVideoUrl = img.getAttribute('data-pvv') || '';

                    // 画質情報を取得
                    const qualitySpan = thumbInside.querySelector('div.top-right-tags span.video-hd-mark');
                    const quality = qualitySpan ? qualitySpan.textContent.trim() : '';

                    // サムネイル下の情報を取得
                    const thumbUnder = videoDiv.querySelector('div.thumb-under');
                    let title = '';
                    let duration = '';

                    if (thumbUnder) {
                        const titleElement = thumbUnder.querySelector('p.title a');
                        if (titleElement) {
                            title = titleElement.textContent.replace(/\s*<span class="duration">.*?<\/span>/, '').trim();

                            const durationElement = titleElement.querySelector('span.duration');
                            if (durationElement) {
                                duration = durationElement.textContent.trim();
                            }
                        }

                        // タイトルが空の場合、代替手段を試す
                        if (!title) {
                            const metadataDuration = thumbUnder.querySelector('p.metadata span.duration');
                            if (metadataDuration) {
                                duration = metadataDuration.textContent.trim();
                            }
                        }
                    }

                    // タイトルがまだ空の場合、imgのalt属性を試す
                    if (!title && img.alt) {
                        title = img.alt;
                    }

                    // タイトルがまだ空の場合、デフォルトタイトルを使用
                    if (!title) {
                        title = `動画 ${index + 1}`;
                    }

                    // 動画カードを作成
                    createVideoCard({
                        url: videoUrl,
                        thumbnail: thumbnailUrl,
                        hoverVideo: hoverVideoUrl,
                        title: title,
                        duration: duration,
                        quality: quality,
                        index: index
                    });
                });
            });

            // 動画が見つからなかった場合
            if (videosGrid.children.length === 0) {
                videosGrid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:40px;color:#aaa;">動画が見つかりませんでした</div>';
            }
        }

        // 動画カードの作成
        function createVideoCard(video) {
            const card = document.createElement('div');
            card.className = 'video-card';
            card.dataset.url = video.url;

            // サムネイルコンテナ
            const thumbnailContainer = document.createElement('div');
            thumbnailContainer.className = 'thumbnail-container';

            // サムネイル画像
            const thumbnail = document.createElement('img');
            thumbnail.className = 'thumbnail';
            thumbnail.src = video.thumbnail;
            thumbnail.alt = video.title;
            thumbnail.loading = 'lazy';

            // ホバー動画
            const hoverVideo = document.createElement('video');
            hoverVideo.className = 'hover-video';
            hoverVideo.muted = true;
            hoverVideo.loop = true;
            hoverVideo.preload = 'none';

            if (video.hoverVideo) {
                const source = document.createElement('source');
                source.src = video.hoverVideo;
                source.type = 'video/mp4';
                hoverVideo.appendChild(source);
            }

            // 画質バッジ
            if (video.quality) {
                const qualityBadge = document.createElement('div');
                qualityBadge.className = 'quality-badge';
                qualityBadge.textContent = video.quality;
                thumbnailContainer.appendChild(qualityBadge);
            }

            // 動画長
            if (video.duration) {
                const durationBadge = document.createElement('div');
                durationBadge.className = 'duration';
                durationBadge.textContent = video.duration;
                thumbnailContainer.appendChild(durationBadge);
            }

            thumbnailContainer.appendChild(thumbnail);
            thumbnailContainer.appendChild(hoverVideo);

            // 動画情報
            const videoInfo = document.createElement('div');
            videoInfo.className = 'video-info';

            const videoTitle = document.createElement('div');
            videoTitle.className = 'video-title';
            videoTitle.textContent = video.title;

            const videoMetadata = document.createElement('div');
            videoMetadata.className = 'video-metadata';
            videoMetadata.textContent = video.duration || '時間不明';

            videoInfo.appendChild(videoTitle);
            videoInfo.appendChild(videoMetadata);

            card.appendChild(thumbnailContainer);
            card.appendChild(videoInfo);

            // クリックイベント
            card.addEventListener('click', () => {
                loadVideo(video.url);
            });

            // ホバーイベント
            card.addEventListener('mouseenter', () => {
                if (video.hoverVideo && hoverVideo.paused) {
                    hoverVideo.play().catch(e => console.log('ホバー動画の再生に失敗:', e));
                }
            });

            card.addEventListener('mouseleave', () => {
                if (!hoverVideo.paused) {
                    hoverVideo.pause();
                    hoverVideo.currentTime = 0;
                }
            });

            videosGrid.appendChild(card);
        }

        async function loadVideo(url) {
            showLoading();
            hideError();
            videoLoadingElement.style.display = 'block';
            currentView = 'player';
            showView('player');

            // 相対URLを絶対URLに変換
            let videoUrl = url;
            if (!url.startsWith('http')) {
                videoUrl = BASE_URL + (url.startsWith('/') ? url.substring(1) : url);
            }

            try {
                const proxyUrl = getCorsProxyUrl(videoUrl);
                const response = await fetch(proxyUrl);
                const html = await response.text();

                // 動画データを抽出
                extractVideoData(html, videoUrl);

            } catch (error) {
                console.error('動画読み込みエラー:', error);
                showError('動画の読み込みに失敗しました');
                hideLoading();
                videoLoadingElement.style.display = 'none';
            }
        }

        // extractVideoData関数内で履歴保存を追加(約1300行目付近)
        function extractVideoData(html, videoUrl) {
            // 動画情報を抽出する正規表現
            const videoHLSRegex = /html5player\.setVideoHLS\('([^']+)'\)/;
            const videoHighRegex = /html5player\.setVideoUrlHigh\('([^']+)'\)/;
            const videoLowRegex = /html5player\.setVideoUrlLow\('([^']+)'\)/;
            const videoTitleRegex = /html5player\.setVideoTitle\('([^']+)'\)/;

            const videoHLSMatch = html.match(videoHLSRegex);
            const videoHighMatch = html.match(videoHighRegex);
            const videoLowMatch = html.match(videoLowRegex);
            const videoTitleMatch = html.match(videoTitleRegex);

            // サムネイル画像を抽出
            const thumbnailRegex = /meta\s+property="og:image"\s+content="([^"]+)"/;
            const thumbnailMatch = html.match(thumbnailRegex);

            // JSON-LDデータを抽出
            const jsonLdRegex = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/;
            const jsonLdMatch = html.match(jsonLdRegex);

            let jsonLdData = null;
            if (jsonLdMatch) {
                try {
                    jsonLdData = JSON.parse(jsonLdMatch[1]);
                } catch (e) {
                    console.error('JSON-LDの解析エラー:', e);
                }
            }

            // 関連動画を抽出
            const relatedRegex = /var video_related\s*=\s*(\[.*?\]);/s;
            const relatedMatch = html.match(relatedRegex);

            let relatedVideos = [];
            if (relatedMatch) {
                try {
                    relatedVideos = JSON.parse(relatedMatch[1]);
                } catch (e) {
                    console.error('関連動画データの解析エラー:', e);
                }
            }

            // サムネイルURLを取得(優先順位: og:image > その他)
            let thumbnailUrl = '';
            if (thumbnailMatch && thumbnailMatch[1]) {
                thumbnailUrl = thumbnailMatch[1];
            } else if (jsonLdData && jsonLdData.thumbnailUrl) {
                thumbnailUrl = jsonLdData.thumbnailUrl;
            }

            // タイトルを取得
            let title = videoTitleMatch ? videoTitleMatch[1] :
                (jsonLdData ? jsonLdData.name : '不明なタイトル');

            // 動画データを保存
            currentVideoData = {
                hlsUrl: videoHLSMatch ? videoHLSMatch[1] : null,
                highQualityUrl: videoHighMatch ? videoHighMatch[1] : null,
                lowQualityUrl: videoLowMatch ? videoLowMatch[1] : null,
                title: title,
                thumbnail: thumbnailUrl,
                jsonLd: jsonLdData,
                relatedVideos: relatedVideos,
                pageUrl: videoUrl
            };

            // 履歴に動画データを保存
            const videoDataForHistory = {
                url: videoUrl,
                pageUrl: videoUrl,
                title: title,
                thumbnail: thumbnailUrl,
                duration: jsonLdData ? jsonLdData.duration?.replace('PT', '').toLowerCase() : '',
                description: jsonLdData ? jsonLdData.description : '',
                views: jsonLdData?.interactionStatistic?.userInteractionCount || '',
                uploadDate: jsonLdData?.uploadDate || '',
                hlsUrl: videoHLSMatch ? videoHLSMatch[1] : null,
                // 実際の再生URL(最初に利用可能なもの)
                videoUrl: videoHLSMatch ? videoHLSMatch[1] :
                    (videoHighMatch ? videoHighMatch[1] :
                        (videoLowMatch ? videoLowMatch[1] : videoUrl))
            };

            storage.addToHistory(videoDataForHistory);

            // HLSプレイリストを取得
            if (currentVideoData.hlsUrl) {
                fetchHLSPlaylist(currentVideoData.hlsUrl);
            } else {
                displayVideoPlayer();
            }
        }

        // HLSプレイリストの取得
        async function fetchHLSPlaylist(hlsUrl) {
            try {
                const proxyUrl = getCorsProxyUrl(hlsUrl);
                const response = await fetch(proxyUrl);
                const playlistText = await response.text();

                currentHLSPlaylist = parseM3U8Playlist(playlistText, hlsUrl);
                displayVideoPlayer();
            } catch (error) {
                console.error('HLSプレイリストの取得エラー:', error);
                currentHLSPlaylist = null;
                displayVideoPlayer();
            }
        }

        // M3U8プレイリストの解析
        function parseM3U8Playlist(playlistText, baseUrl) {
            const lines = playlistText.split('\n');
            const variants = [];

            let currentVariant = null;

            for (let i = 0; i < lines.length; i++) {
                const line = lines[i].trim();

                if (line.startsWith('#EXT-X-STREAM-INF:')) {
                    currentVariant = {};

                    // 属性を解析
                    const bandwidthMatch = line.match(/BANDWIDTH=(\d+)/);
                    const resolutionMatch = line.match(/RESOLUTION=(\d+x\d+)/);
                    const nameMatch = line.match(/NAME="([^"]+)"/);

                    if (bandwidthMatch) currentVariant.bandwidth = parseInt(bandwidthMatch[1]);
                    if (resolutionMatch) currentVariant.resolution = resolutionMatch[1];
                    if (nameMatch) currentVariant.name = nameMatch[1];
                } else if (line && !line.startsWith('#') && currentVariant) {
                    // 相対URLを絶対URLに変換
                    let variantUrl = line;
                    if (!variantUrl.startsWith('http')) {
                        const basePath = baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1);
                        variantUrl = basePath + variantUrl;
                    }

                    currentVariant.url = variantUrl;
                    variants.push(currentVariant);
                    currentVariant = null;
                }
            }

            return variants;
        }

        // 動画プレーヤーの表示
        function displayVideoPlayer() {
            // 動画詳細情報の表示
            displayVideoDetails();

            // 画質選択オプションの表示
            displayQualityOptions();

            // 関連動画の表示
            displayRelatedVideos();

            // デフォルトの動画ソースを設定
            if (currentVideoData.hlsUrl && currentHLSPlaylist && currentHLSPlaylist.length > 0) {
                // 最初のHLSバリアントを再生
                playHLSVideo(currentHLSPlaylist[0].url);
            } else if (currentVideoData.highQualityUrl) {
                // 高画質動画を再生
                playRegularVideo(currentVideoData.highQualityUrl);
            } else if (currentVideoData.lowQualityUrl) {
                // 低画質動画を再生
                playRegularVideo(currentVideoData.lowQualityUrl);
            } else {
                showError('再生可能な動画が見つかりませんでした');
            }

            hideLoading();
            videoLoadingElement.style.display = 'none';
        }

        // 動画詳細情報の表示
        function displayVideoDetails() {
            const data = currentVideoData;
            const jsonLd = data.jsonLd;

            let html = '';

            if (data.title) {
                html += `<h2>${data.title}</h2>`;
            }

            // お気に入りボタン
            const isFavorite = storage.isFavorite(data.pageUrl);
            html += `
                <button class="favorite-btn ${isFavorite ? 'active' : ''}" id="video-favorite-btn" style="position:absolute;top:25px;right:25px;">
                    <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px">
                        <path d="m354-287 126-76 126 77-33-144 111-96-146-13-58-136-58 135-146 13 111 97-33 143ZM233-120l65-281L80-590l288-25 112-265 112 265 288 25-218 189 65 281-247-149-247 149Zm247-350Z"/>
                    </svg>
                </button>
            `;

            html += '<div class="video-meta">';

            if (jsonLd) {
                if (jsonLd.uploadDate) {
                    const date = new Date(jsonLd.uploadDate);
                    const formattedDate = date.toLocaleDateString('ja-JP', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric'
                    });

                    html += `
                        <div class="meta-item">
                            <span class="meta-label">投稿日</span>
                            <span class="meta-value">${formattedDate}</span>
                        </div>
                    `;
                }

                if (jsonLd.duration) {
                    const duration = jsonLd.duration.replace('PT', '').toLowerCase();
                    html += `
                        <div class="meta-item">
                            <span class="meta-label">長さ</span>
                            <span class="meta-value">${duration}</span>
                        </div>
                    `;
                }

                if (jsonLd.interactionStatistic && jsonLd.interactionStatistic.userInteractionCount) {
                    const views = parseInt(jsonLd.interactionStatistic.userInteractionCount).toLocaleString();
                    html += `
                        <div class="meta-item">
                            <span class="meta-label">視聴回数</span>
                            <span class="meta-value">${views} 回</span>
                        </div>
                    `;
                }
            }

            html += '</div>';

            if (jsonLd && jsonLd.description) {
                html += `<div class="video-description">${jsonLd.description}</div>`;
            }

            videoDetails.innerHTML = html;

            // お気に入りボタンのイベント
            const favoriteBtn = document.getElementById('video-favorite-btn');
            favoriteBtn.addEventListener('click', () => {
                const isFavorite = storage.isFavorite(data.pageUrl);

                if (isFavorite) {
                    storage.removeFromFavorites(data.pageUrl);
                    favoriteBtn.classList.remove('active');
                } else {
                    const videoData = {
                        url: data.pageUrl,
                        thumbnail: '',
                        title: data.title,
                        duration: jsonLd ? jsonLd.duration.replace('PT', '').toLowerCase() : '',
                        quality: '',
                        hoverVideo: ''
                    };
                    storage.addToFavorites(videoData);
                    favoriteBtn.classList.add('active');
                }
            });
        }

        // 画質選択オプションの表示
        function displayQualityOptions() {
            let html = '<h3>画質選択</h3><div class="quality-options">';

            // HLSオプション
            if (currentHLSPlaylist && currentHLSPlaylist.length > 0) {
                currentHLSPlaylist.forEach((variant, index) => {
                    html += `
                        <div class="quality-option" data-type="hls" data-url="${variant.url}" data-index="${index}">
                            HLS ${variant.name} (${variant.resolution})
                        </div>
                    `;
                });
            }

            // 通常動画オプション
            if (currentVideoData.highQualityUrl) {
                html += `
                    <div class="quality-option" data-type="regular" data-url="${currentVideoData.highQualityUrl}">
                        高画質 (MP4)
                    </div>
                `;
            }

            if (currentVideoData.lowQualityUrl) {
                html += `
                    <div class="quality-option" data-type="regular" data-url="${currentVideoData.lowQualityUrl}">
                        低画質 (MP4)
                    </div>
                `;
            }

            html += '</div>';

            // ダウンロードボタン
            html += '<button class="download-btn" id="download-quality-btn">この画質でダウンロード</button>';

            qualitySelector.innerHTML = html;

            // 画質選択イベント
            const qualityOptions = qualitySelector.querySelectorAll('.quality-option');
            qualityOptions.forEach(option => {
                option.addEventListener('click', () => {
                    // アクティブクラスの切り替え
                    qualityOptions.forEach(opt => opt.classList.remove('active'));
                    option.classList.add('active');

                    const type = option.dataset.type;
                    const url = option.dataset.url;
                    currentQualityUrl = url;

                    if (type === 'hls') {
                        playHLSVideo(url);
                    } else {
                        playRegularVideo(url);
                    }
                });
            });

            // ダウンロードボタンのイベント
            const downloadBtn = document.getElementById('download-quality-btn');
            downloadBtn.addEventListener('click', () => {
                if (currentQualityUrl) {
                    downloadVideoFromUrl(currentQualityUrl);
                }
            });

            // 最初のオプションをアクティブにする
            if (qualityOptions.length > 0) {
                qualityOptions[0].click();
            }
        }

        // 関連動画の表示
        function displayRelatedVideos() {
            relatedVideosGrid.innerHTML = '';

            if (!currentVideoData.relatedVideos || currentVideoData.relatedVideos.length === 0) {
                relatedVideosContainer.style.display = 'none';
                return;
            }

            relatedVideosContainer.style.display = 'block';

            currentVideoData.relatedVideos.forEach((video, index) => {
                // サムネイルURLの取得(優先順位: i > il > if > ip > st1)
                let thumbnailUrl = '';
                if (video.i) thumbnailUrl = video.i;
                else if (video.il) thumbnailUrl = video.il;
                else if (video.if) thumbnailUrl = video.if;
                else if (video.ip) thumbnailUrl = video.ip;
                else if (video.st1) thumbnailUrl = video.st1;

                // タイトル
                const title = video.t || `関連動画 ${index + 1}`;

                // 動画長
                const duration = video.d || '';

                // 視聴回数
                const views = video.n || '';

                // ホバー動画
                const hoverVideo = video.ipu || '';

                // 動画URL(仮 - 実際の構造に合わせて調整が必要)
                const videoUrl = `/${video.u || index}`;

                // カードを作成
                const card = document.createElement('div');
                card.className = 'video-card';
                card.dataset.url = videoUrl;

                const thumbnailContainer = document.createElement('div');
                thumbnailContainer.className = 'thumbnail-container';

                const thumbnail = document.createElement('img');
                thumbnail.className = 'thumbnail';
                thumbnail.src = thumbnailUrl;
                thumbnail.alt = title;
                thumbnail.loading = 'lazy';

                const hoverVideoElement = document.createElement('video');
                hoverVideoElement.className = 'hover-video';
                hoverVideoElement.muted = true;
                hoverVideoElement.loop = true;
                hoverVideoElement.preload = 'none';

                if (hoverVideo) {
                    const source = document.createElement('source');
                    source.src = hoverVideo;
                    source.type = 'video/mp4';
                    hoverVideoElement.appendChild(source);
                }

                if (duration) {
                    const durationBadge = document.createElement('div');
                    durationBadge.className = 'duration';
                    durationBadge.textContent = duration;
                    thumbnailContainer.appendChild(durationBadge);
                }

                thumbnailContainer.appendChild(thumbnail);
                thumbnailContainer.appendChild(hoverVideoElement);

                const videoInfo = document.createElement('div');
                videoInfo.className = 'video-info';

                const videoTitle = document.createElement('div');
                videoTitle.className = 'video-title';
                videoTitle.textContent = title;

                const videoMetadata = document.createElement('div');
                videoMetadata.className = 'video-metadata';

                let metadataText = duration;
                if (views && duration) metadataText += ` • ${views}`;
                else if (views) metadataText = views;

                videoMetadata.textContent = metadataText || '情報なし';

                videoInfo.appendChild(videoTitle);
                videoInfo.appendChild(videoMetadata);

                card.appendChild(thumbnailContainer);
                card.appendChild(videoInfo);

                // クリックイベント
                card.addEventListener('click', () => {
                    loadVideo(videoUrl);
                });

                // ホバーイベント
                card.addEventListener('mouseenter', () => {
                    if (hoverVideo && hoverVideoElement.paused) {
                        hoverVideoElement.play().catch(e => console.log('ホバー動画の再生に失敗:', e));
                    }
                });

                card.addEventListener('mouseleave', () => {
                    if (!hoverVideoElement.paused) {
                        hoverVideoElement.pause();
                        hoverVideoElement.currentTime = 0;
                    }
                });

                relatedVideosGrid.appendChild(card);
            });
        }

        let hlsBasePath = '';

        function extractHlsBasePath(m3u8Url) {
            // https://example.com/path/to/playlist.m3u8
            // → https://example.com/path/to/
            const match = m3u8Url.match(/^(https?:\/\/[^\/]+\/.*\/)/);
            return match ? match[1] : '';
        }

        // HLSビデオの再生
        function playHLSVideo(url) {
            hlsBasePath = extractHlsBasePath(url);
            // 既存のHLSプレーヤーを破棄
            if (hlsPlayer) {
                hlsPlayer.destroy();
                hlsPlayer = null;
            }

            // ビデオ要素をリセット
            mainVideo.src = '';
            mainVideo.load();

            // HLSプレーヤーの設定
            if (Hls.isSupported()) {
                hlsPlayer = new Hls({
                    debug: false,
                    enableWorker: true,
                    xhrSetup: function (xhr) {
                        const params = 'baseurl23896=' + encodeURIComponent(hlsBasePath);
                        const originalOpen = xhr.open;
                        xhr.open = function (method, url, async) {
                            const newUrl = url.includes('?')
                                ? `${url}&${params}`
                                : `${url}?${params}`;
                            return originalOpen.call(xhr, method, newUrl, async);
                        };
                    }
                });

                hlsPlayer.loadSource(getCorsProxyUrl(url));
                hlsPlayer.attachMedia(mainVideo);

                hlsPlayer.on(Hls.Events.MANIFEST_PARSED, () => {
                    mainVideo.play().catch(e => console.log('自動再生に失敗:', e));
                });

                hlsPlayer.on(Hls.Events.ERROR, (event, data) => {
                    console.error('HLSエラー:', data);
                    if (data.fatal) {
                        switch (data.type) {
                            case Hls.ErrorTypes.NETWORK_ERROR:
                                console.error('ネットワークエラー、再試行します');
                                hlsPlayer.startLoad();
                                break;
                            case Hls.ErrorTypes.MEDIA_ERROR:
                                console.error('メディアエラー');
                                hlsPlayer.recoverMediaError();
                                break;
                            default:
                                console.error('回復不能なエラー');
                                playFallbackVideo();
                                break;
                        }
                    }
                });
            } else if (mainVideo.canPlayType('application/vnd.apple.mpegurl')) {
                // ネイティブHLSサポート(Safariなど)
                mainVideo.src = url;
                mainVideo.play().catch(e => console.log('自動再生に失敗:', e));
            } else {
                console.error('HLSがサポートされていません');
                playFallbackVideo();
            }
        }

        // 通常動画の再生
        function playRegularVideo(url) {
            // HLSプレーヤーを破棄
            if (hlsPlayer) {
                hlsPlayer.destroy();
                hlsPlayer = null;
            }

            mainVideo.src = getCorsProxyUrl(url);
            mainVideo.load();
            mainVideo.play().catch(e => console.log('自動再生に失敗:', e));
        }

        // フォールバック動画の再生
        function playFallbackVideo() {
            if (currentVideoData.highQualityUrl) {
                playRegularVideo(currentVideoData.highQualityUrl);
            } else if (currentVideoData.lowQualityUrl) {
                playRegularVideo(currentVideoData.lowQualityUrl);
            } else {
                showError('動画を再生できませんでした');
            }
        }

        // ダウンロード機能
        function downloadVideoFromUrl(url) {
            // HLSの場合
            if (url.includes('.m3u8')) {
                const m3u8 = new M3U8();
                const download = m3u8.start(url);

                download
                    .on("progress", progress => {
                        console.log(progress);
                        showError(`ダウンロード中... ${progress.percentage}%`);
                    })
                    .on("finished", finished => {
                        console.log("完了", finished);
                        hideError();
                    })
                    .on("error", message => {
                        console.error(message);
                        showError('ダウンロードに失敗しました: ' + message);
                    })
                    .on("aborted", () => {
                        console.log("Download aborted");
                        hideError();
                    });
            } else {
                // 通常動画の場合
                const a = document.createElement('a');
                a.href = getCorsProxyUrl(url);
                a.download = currentVideoData.title ? `${currentVideoData.title}.mp4` : 'video.mp4';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
        }

        // 履歴からのダウンロード
        function downloadVideo(video) {
            // 履歴に保存された情報から動画をダウンロード
            // 注意: 履歴には動画URLのみが保存されているため、実際のダウンロードは最新の動画URLが必要
            // ここでは簡易的に履歴のURLからダウンロードを試みる
            downloadVideoFromUrl(video.url);
        }

        // ビデオグリッドの表示
        function showVideoGrid() {
            showView('home');
            currentView = 'home';
        }

        // ローディング表示
        function showLoading() {
            loadingElement.style.display = 'block';
        }

        function hideLoading() {
            loadingElement.style.display = 'none';
        }

        // エラー表示
        function showError(message) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }

        function hideError() {
            errorElement.style.display = 'none';
        }
    </script>
</body>

</html>