bckplayer 0.1.0

A cross-platform CLI media player interface for VLC
Documentation
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
use anyhow::Result;
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{
        Block, Borders, Clear, Gauge, Paragraph, Wrap,
    },
    Frame, Terminal,
};
use std::io;
use std::io::{BufRead, BufReader};
use std::process::{Command as OsCommand, Stdio};
use std::thread;
use std::path::PathBuf;
use std::sync::mpsc;

use crate::commands::{get_command_suggestions, Command};
use crate::playlists::PlaylistsManager;
use crate::types::{LogEntry, PlayerState, TuiMode};
use crate::utils;

pub struct TuiApp {
    mode: TuiMode,
    input: String,
    command_input: String,
    command_suggestion_index: usize, // Track selected suggestion
    help_visible: bool,
    help_scroll: u16,
    config_visible: bool,
    config_section_index: usize, // Track selected config section
    config_item_index: usize,   // Track selected config item
    config_sections: Vec<String>, // Available config sections
    config_editing: bool,        // Whether we're currently editing a config value
    config_edit_input: String,   // Input buffer for editing config values
    command_sender: mpsc::Sender<Command>,
    state_receiver: Option<mpsc::Receiver<PlayerState>>,
    log_receiver: Option<mpsc::Receiver<Command>>,
    logs: Vec<LogEntry>,
    status_message: String,
    loading: bool,
    loading_start: Option<std::time::Instant>,
    // YouTube search state
    yt_search_query: String,
    yt_search_input_active: bool,
    yt_search_results: Vec<YouTubeSearchResult>,
    yt_selected_index: usize,
    yt_is_searching: bool,
    yt_result_rx: Option<mpsc::Receiver<YouTubeSearchResult>>, // streamed results from worker
    // Playlists state
    playlists_visible: bool,
    playlists_manager: PlaylistsManager,
    pl_selected_playlist_idx: usize,
    pl_selected_item_idx: usize,
    // Focus: 0=player header (top sections), 1=playlist list (left), 2=items (right)
    pl_focus: u8,
    // Now playing markers
    now_playing_playlist_id: Option<String>,
    now_playing_item_id: Option<String>,
    pl_show_ids: bool,
}

#[derive(Debug, Clone)]
struct YouTubeSearchResult {
    title: String,
    duration: Option<String>,
    id: String,
}

impl TuiApp {
    pub fn new(
        command_sender: mpsc::Sender<Command>,
        state_receiver: mpsc::Receiver<PlayerState>,
        log_receiver: mpsc::Receiver<Command>,
    ) -> Self {
    let mut playlists_manager = PlaylistsManager::new_or_default();
    playlists_manager.ensure_default();
    let _ = playlists_manager.save();
    Self {
            mode: TuiMode::Normal, // Start in normal mode since password is auto-set
            input: String::new(),
            command_input: String::new(),
            command_suggestion_index: 0,
            help_visible: false,
            help_scroll: 0,
            config_visible: false,
            config_section_index: 0,
            config_item_index: 0,
            config_sections: vec![
                "Player".to_string(),
                "Network".to_string(),
                "Appearance".to_string(),
                "Media".to_string(),
                "Advanced".to_string(),
                "YouTube".to_string(),
            ],
            config_editing: false,
            config_edit_input: String::new(),
            command_sender,
            state_receiver: Some(state_receiver),
            log_receiver: Some(log_receiver),
            logs: Vec::new(),
            status_message: "VLC started automatically - ready to use!".to_string(),
            loading: false,
            loading_start: None,
            yt_search_query: String::new(),
            yt_search_input_active: true,
            yt_search_results: Vec::new(),
            yt_selected_index: 0,
            yt_is_searching: false,
            yt_result_rx: None,
            playlists_visible: false,
            playlists_manager,
            pl_selected_playlist_idx: 0,
            pl_selected_item_idx: 0,
            pl_focus: 0,
            pl_show_ids: false,
            now_playing_playlist_id: None,
            now_playing_item_id: None,
        }
    }

    pub fn run(&mut self, mut terminal: Terminal<CrosstermBackend<io::Stdout>>) -> Result<()> {
        let mut current_state = PlayerState::default();
        self.add_log("INFO", "TUI thread started");

        loop {
            // Check for loading timeout (10 seconds)
            if let Some(start_time) = self.loading_start {
                if start_time.elapsed() > std::time::Duration::from_secs(300) {
                    self.loading = false;
                    self.loading_start = None;
                    self.add_log("ERROR", "Loading timed out after 300 seconds");
                }
            }
            
            // Check for state updates
            if let Some(ref receiver) = self.state_receiver {
                if let Ok(new_state) = receiver.try_recv() {
                    //self.add_log("DEBUG", &format!("Received state update: {:?}", new_state.state));

                    current_state = new_state;
                    
                    // Reset loading state when we receive a state update
                    // This indicates that the loading operation has completed (success or failure)
                    if self.loading {
                        self.loading = false;
                        self.loading_start = None;
                        
                        // Log the result
                        if current_state.media_info.title.as_deref().unwrap_or("").contains("Error") {
                            self.add_log("ERROR", "Failed to load media");
                        } else if !current_state.media_info.filename.is_empty() {
                            self.add_log("INFO", &format!("Successfully loaded: {}", current_state.media_info.filename));
                        }
                    }
                }
            }

            // Check for log events
            let mut pending_commands = Vec::new();
            if let Some(ref receiver) = self.log_receiver {
                while let Ok(command) = receiver.try_recv() {
                    pending_commands.push(command);
                }
            }
            
            // Process pending commands
            for command in pending_commands {
                match command {
                    Command::Log(log_entry) => {
                        self.logs.push(log_entry);
                        // Keep only the last 100 logs for performance
                        if self.logs.len() > 100 {
                            self.logs.remove(0);
                        }
                    }
                    Command::PlaylistReload => {
                        // Force reload playlists from disk
                        let _ = self.playlists_manager.reload();
                    }
                    Command::PlaylistNowPlaying { playlist_id, item_id } => {
                        self.now_playing_playlist_id = Some(playlist_id);
                        self.now_playing_item_id = Some(item_id);
                    }
                    Command::PlaylistClearNowPlaying => {
                        self.now_playing_playlist_id = None;
                        self.now_playing_item_id = None;
                    }
                    Command::Quit => {
                        self.add_log("INFO", "Received quit command, exiting TUI");
                        return Ok(());
                    }
                    Command::ShowConfig => {
                        self.add_log("DEBUG", "Received ShowConfig command, switching to config mode");
                        self.mode = TuiMode::Config;
                        self.config_visible = true;
                    }
                    Command::HideConfig => {
                        self.add_log("DEBUG", "Received HideConfig command, switching to normal mode");
                        self.mode = TuiMode::Normal;
                        self.config_visible = false;
                    }
                    _ => {
                        // Ignore other commands
                    }
                }
            }

            // Pump YouTube search streamed results even without keypresses
            if let Some(rx) = self.yt_result_rx.as_ref() {
                loop {
                    match rx.try_recv() {
                        Ok(item) => {
                            self.yt_search_results.push(item);
                        }
                        Err(mpsc::TryRecvError::Empty) => { break; }
                        Err(mpsc::TryRecvError::Disconnected) => {
                            self.yt_is_searching = false;
                            self.yt_result_rx = None;
                            break;
                        }
                    }
                }
            }

            // Render the UI
            terminal.draw(|f| self.draw(f, &current_state))?;

            // Handle input
            if event::poll(std::time::Duration::from_millis(16))? {
                if let Event::Key(key) = event::read()? {
                    if key.kind == KeyEventKind::Press {
                        self.add_log("DEBUG", &format!("Key pressed: {:?} in mode {:?}", key.code, self.mode));
                        
                        let should_quit = match self.mode {
                            TuiMode::Normal => self.handle_normal_key(key.code)?,
                            TuiMode::Input => self.handle_input_key(key.code)?,
                            TuiMode::Command => self.handle_command_key(key.code)?,
                            TuiMode::Help => self.handle_help_key(key.code)?,
                            TuiMode::Config => self.handle_config_key(key.code)?,
                            TuiMode::YoutubeSearch => self.handle_youtube_search_key(key.code)?,
                        };

                        if should_quit {
                            self.add_log("INFO", "Quit requested from key handler, exiting TUI");
                            break;
                        }
                    }
                }
            }
        }

        self.add_log("INFO", "TUI thread ending normally");
        Ok(())
    }

    fn handle_normal_key(&mut self, key: KeyCode) -> Result<bool> {
        match key {
            KeyCode::Char('p') | KeyCode::Char('P') => {
                self.playlists_visible = !self.playlists_visible;
                self.add_log("INFO", if self.playlists_visible { "Playlists panel opened" } else { "Playlists panel closed" });
            }
            KeyCode::Char('I') => {
                if self.playlists_visible {
                    self.pl_show_ids = !self.pl_show_ids;
                    self.add_log("INFO", if self.pl_show_ids { "Playlist IDs shown" } else { "Playlist IDs hidden" });
                }
            }
            KeyCode::Tab => {
                if self.playlists_visible {
                    // Cycle focus: 0 -> 1 -> 2 -> 0
                    self.pl_focus = (self.pl_focus + 1) % 3;
                } else {
                    // Cycle between player/logs (no-op here)
                }
            }
            KeyCode::Delete => {
                if self.playlists_visible {
                    self.delete_selected_playlist_or_item()?;
                }
            }
            KeyCode::Char('q') => {
                self.add_log("INFO", "Quit key pressed, sending quit event");
                let _ = self.command_sender.send(Command::Quit);
                return Ok(true);
            }
            KeyCode::Char('h') => {
                self.add_log("DEBUG", "Help key pressed, showing help");
                let _ = self.command_sender.send(Command::ShowHelp);
                self.mode = TuiMode::Help;
                self.help_visible = true;
            }
            KeyCode::Char('C') => {
                self.add_log("DEBUG", "Config key pressed, showing config");
                let _ = self.command_sender.send(Command::ShowConfig);
                // Mode will be set when the command comes back through log_receiver
            }
            KeyCode::Char('i') => {
                self.add_log("DEBUG", "Input key pressed, entering input mode");
                self.mode = TuiMode::Input;
                self.input.clear();
            }
            KeyCode::Char(' ') => {
                self.add_log("DEBUG", "Space key pressed, sending play/pause event");
                let _ = self.command_sender.send(Command::Toggle);
            }
            KeyCode::Char('s') => {
                self.add_log("DEBUG", "Stop key pressed, sending stop event");
                let _ = self.command_sender.send(Command::Stop);
            }
            KeyCode::Char('m') => {
                self.add_log("DEBUG", "Mute key pressed, sending mute event");
                let _ = self.command_sender.send(Command::Mute);
            }
            KeyCode::Up => {
                if self.playlists_visible && (self.pl_focus == 1 || self.pl_focus == 2) {
                    if self.pl_focus == 1 {
                        if self.pl_selected_playlist_idx > 0 { self.pl_selected_playlist_idx -= 1; self.pl_selected_item_idx = 0; }
                    } else if self.pl_selected_item_idx > 0 {
                        self.pl_selected_item_idx -= 1;
                    }
                } else {
                    self.add_log("DEBUG", "Up arrow pressed, sending volume up event");
                    let _ = self.command_sender.send(Command::VolumeUp);
                }
            }
            KeyCode::Down => {
                if self.playlists_visible && (self.pl_focus == 1 || self.pl_focus == 2) {
                    if self.pl_focus == 1 {
                        let len = self.playlists_manager.list().len();
                        if len > 0 { self.pl_selected_playlist_idx = (self.pl_selected_playlist_idx + 1).min(len.saturating_sub(1)); self.pl_selected_item_idx = 0; }
                    } else if let Some(pl) = self.playlists_manager.list().get(self.pl_selected_playlist_idx) {
                        let len = pl.items.len();
                        if len > 0 { self.pl_selected_item_idx = (self.pl_selected_item_idx + 1).min(len.saturating_sub(1)); }
                    }
                } else {
                    self.add_log("DEBUG", "Down arrow pressed, sending volume down event");
                    let _ = self.command_sender.send(Command::VolumeDown);
                }
            }
            KeyCode::Left => {
                self.add_log("DEBUG", "Left arrow pressed, sending seek backward event");
                let _ = self.command_sender.send(Command::SeekBackward);
            }
            KeyCode::Right => {
                self.add_log("DEBUG", "Right arrow pressed, sending seek forward event");
                let _ = self.command_sender.send(Command::SeekForward);
            }
            KeyCode::Enter => {
                if self.playlists_visible && self.pl_focus == 2 {
                    if let Some(pl) = self.playlists_manager.list().get(self.pl_selected_playlist_idx) {
                        let _ = self.command_sender.send(Command::PlaylistPlay { playlist_id: pl.id.clone(), index: self.pl_selected_item_idx });
                    }
                }
            }
            KeyCode::Char('=') | KeyCode::Char('+') => {
                self.add_log("DEBUG", "Speed up key pressed, sending speed up event");
                let _ = self.command_sender.send(Command::SpeedUp);
            }
            KeyCode::Char('-') => {
                self.add_log("DEBUG", "Speed down key pressed, sending speed down event");
                let _ = self.command_sender.send(Command::SpeedDown);
            }
            KeyCode::Char('r') => {
                self.add_log("DEBUG", "Reset speed key pressed, sending reset speed event");
                let _ = self.command_sender.send(Command::SpeedReset);
            }
            KeyCode::Char('f') => {
                self.add_log("DEBUG", "Fullscreen key pressed, sending toggle fullscreen event");
                let _ = self.command_sender.send(Command::ToggleFullscreen);
            }
            KeyCode::Char('l') => {
                self.add_log("DEBUG", "Loop key pressed, sending loop toggle event");
                let _ = self.command_sender.send(Command::ToggleLoop);
            }
            KeyCode::Char('c') => {
                self.add_log("DEBUG", "Connection test key pressed, testing VLC connection");
                let _ = self.command_sender.send(Command::TestConnection);
            }
            KeyCode::Char('y') => {
                self.add_log("DEBUG", "YouTube search key pressed, opening search window");
                self.mode = TuiMode::YoutubeSearch;
                // keep previous query if any
                self.yt_search_input_active = true;
            }
            KeyCode::Char(':') => {
                self.add_log("DEBUG", "Colon pressed, entering command mode");
                self.mode = TuiMode::Command;
                self.command_input.clear();
                self.command_suggestion_index = 0;
            }
            _ => {
                self.add_log("DEBUG", &format!("Unhandled key: {:?}", key));
            }
        }
        Ok(false)
    }

    fn handle_input_key(&mut self, key: KeyCode) -> Result<bool> {
        match key {
            KeyCode::Enter => {
                if !self.input.is_empty() {
                    let input = self.input.clone();
                    self.add_log("INFO", &format!("Input entered: {}", input));
                    
                    self.loading = true;
                    self.loading_start = Some(std::time::Instant::now());
                    self.add_log("INFO", &format!("Loading: {}", input));
                    let _ = self.command_sender.send(Command::Open(input));
                    
                    self.input.clear();
                    self.mode = TuiMode::Normal;
                    self.add_log("DEBUG", "Switched back to normal mode");
                } else {
                    self.add_log("WARN", "Empty input entered, ignoring");
                }
            }
            KeyCode::Esc => {
                self.add_log("DEBUG", "Escape pressed in input mode, canceling input");
                self.input.clear();
                self.mode = TuiMode::Normal;
            }
            KeyCode::Char(c) => {
                self.input.push(c);
                self.add_log("DEBUG", &format!("Character added to input: '{}', current input: '{}'", c, self.input));
            }
            KeyCode::Backspace => {
                if !self.input.is_empty() {
                    let removed = self.input.pop();
                    self.add_log("DEBUG", &format!("Backspace pressed, removed: '{:?}', current input: '{}'", removed, self.input));
                } else {
                    self.add_log("DEBUG", "Backspace pressed but input is empty");
                }
            }
            _ => {
                self.add_log("DEBUG", &format!("Unhandled key in input mode: {:?}", key));
            }
        }
        Ok(false)
    }

    fn handle_command_key(&mut self, key: KeyCode) -> Result<bool> {
        match key {
            KeyCode::Esc => {
                self.add_log("DEBUG", "Escape pressed, exiting command mode");
                self.mode = TuiMode::Normal;
                self.command_input.clear();
                self.command_suggestion_index = 0;
            }
            KeyCode::Enter => {
                if !self.command_input.is_empty() {
                    self.add_log("DEBUG", &format!("Executing command: {}", self.command_input));
                    let _ = self.command_sender.send(Command::ExecuteCommand(self.command_input.clone()));
                    self.command_input.clear();
                    self.command_suggestion_index = 0;
                    self.mode = TuiMode::Normal;
                }
            }
            KeyCode::Tab => {
                let suggestions = get_command_suggestions(&self.command_input);
                if !suggestions.is_empty() {
                    // Auto-complete with currently selected suggestion
                    if let Some(suggestion) = suggestions.get(self.command_suggestion_index) {
                        self.command_input = suggestion.command.clone();
                        self.command_suggestion_index = 0; // Reset after completion
                    }
                }
            }
            KeyCode::Up => {
                let suggestions = get_command_suggestions(&self.command_input);
                if !suggestions.is_empty() {
                    // Move up in suggestions list
                    if self.command_suggestion_index == 0 {
                        self.command_suggestion_index = suggestions.len() - 1;
                    } else {
                        self.command_suggestion_index -= 1;
                    }
                }
            }
            KeyCode::Down => {
                let suggestions = get_command_suggestions(&self.command_input);
                if !suggestions.is_empty() {
                    // Move down in suggestions list
                    self.command_suggestion_index = (self.command_suggestion_index + 1) % suggestions.len();
                }
            }
            KeyCode::BackTab => {
                // Keep BackTab for backwards compatibility
                let suggestions = get_command_suggestions(&self.command_input);
                if !suggestions.is_empty() {
                    // Cycle backwards through suggestions
                    if self.command_suggestion_index == 0 {
                        self.command_suggestion_index = suggestions.len() - 1;
                    } else {
                        self.command_suggestion_index -= 1;
                    }
                }
            }
            KeyCode::Backspace => {
                self.command_input.pop();
                self.command_suggestion_index = 0; // Reset selection when typing
            }
            KeyCode::Char(c) => {
                self.command_input.push(c);
                self.command_suggestion_index = 0; // Reset selection when typing
            }
            _ => {
                self.add_log("DEBUG", &format!("Unhandled key in command mode: {:?}", key));
            }
        }
        Ok(false)
    }

    fn handle_help_key(&mut self, key: KeyCode) -> Result<bool> {
        match key {
            KeyCode::Esc | KeyCode::Char('h') | KeyCode::Char('q') => {
                self.add_log("DEBUG", "Closing help screen");
                let _ = self.command_sender.send(Command::HideHelp);
                self.mode = TuiMode::Normal;
                self.help_visible = false;
                self.help_scroll = 0;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.help_scroll = self.help_scroll.saturating_sub(1);
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.help_scroll = self.help_scroll.saturating_add(1);
            }
            KeyCode::PageUp => {
                self.help_scroll = self.help_scroll.saturating_sub(5);
            }
            KeyCode::PageDown => {
                self.help_scroll = self.help_scroll.saturating_add(5);
            }
            KeyCode::Home => {
                self.help_scroll = 0;
            }
            KeyCode::End => {
                self.help_scroll = 50; // Set to a high value, will be clamped in draw
            }
            _ => {
                self.add_log("DEBUG", &format!("Unhandled key in help mode: {:?}", key));
            }
        }
        Ok(false)
    }

    fn handle_config_key(&mut self, key: KeyCode) -> Result<bool> {
        if self.config_editing {
            // Handle input for config editing
            match key {
                KeyCode::Enter => {
                    // Save the edited value
                    match self.save_config_edit() {
                        Ok(()) => {
                            self.add_log("DEBUG", "Config value saved successfully");
                        }
                        Err(e) => {
                            self.add_log("ERROR", &format!("Failed to save config: {}", e));
                        }
                    }
                    self.config_editing = false;
                    self.config_edit_input.clear();
                }
                KeyCode::Esc => {
                    // Cancel editing
                    self.config_editing = false;
                    self.config_edit_input.clear();
                    self.add_log("DEBUG", "Config editing cancelled");
                }
                KeyCode::Backspace => {
                    self.config_edit_input.pop();
                }
                KeyCode::Char(c) => {
                    self.config_edit_input.push(c);
                }
                _ => {}
            }
        } else {
            // Handle navigation and commands
            match key {
                KeyCode::Char('q') | KeyCode::Esc => {
                    self.mode = TuiMode::Normal;
                    self.config_visible = false;
                    self.add_log("DEBUG", "Exited config mode");
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    if self.config_item_index > 0 {
                        self.config_item_index -= 1;
                    } else {
                        // Wrap to bottom
                        self.config_item_index = self.get_config_item_count() - 1;
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    self.config_item_index = (self.config_item_index + 1) % self.get_config_item_count();
                }
                KeyCode::Left | KeyCode::Char('h') => {
                    if self.config_section_index > 0 {
                        self.config_section_index -= 1;
                    } else {
                        self.config_section_index = self.config_sections.len() - 1;
                    }
                    self.config_item_index = 0; // Reset item index when changing sections
                }
                KeyCode::Right | KeyCode::Char('l') => {
                    self.config_section_index = (self.config_section_index + 1) % self.config_sections.len();
                    self.config_item_index = 0; // Reset item index when changing sections
                }
                KeyCode::Enter => {
                    self.start_config_edit()?;
                }
                KeyCode::Char('r') => {
                    self.reset_config_section()?;
                }
                KeyCode::Char('s') => {
                    self.add_log("INFO", "Saving configuration");
                    if let Err(e) = self.command_sender.send(Command::Save) {
                        self.add_log("ERROR", &format!("Failed to send save command: {}", e));
                    }
                }
                _ => {
                    self.add_log("DEBUG", &format!("Unhandled key in config mode: {:?}", key));
                }
            }
        }
        Ok(false)
    }

    pub fn add_log(&mut self, level: &str, message: &str) {
        self.logs.push(LogEntry {
            level: level.to_string(),
            message: message.to_string(),
        });

        // Keep only the last 100 logs
        if self.logs.len() > 100 {
            self.logs.remove(0);
        }
    }

    fn draw(&self, f: &mut Frame, state: &PlayerState) {
        let size = f.size();

        if let TuiMode::Help = self.mode {
            self.draw_help(f, size);
            return;
        }

        // Main layout
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3), // Title
                Constraint::Length(4), // Media info
                Constraint::Length(3), // Controls
                Constraint::Length(3), // Volume
                Constraint::Length(3), // Progress
                Constraint::Min(5),    // Logs
                Constraint::Length(3), // Status/Input
            ].as_ref())
            .split(size);

        // Title
        let title = Paragraph::new("BCK Player - VLC HTTP Interface")
            .style(Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD))
            .alignment(Alignment::Center)
            .block(Block::default().borders(Borders::ALL));
        f.render_widget(title, chunks[0]);

        // Media info
        self.draw_media_info(f, chunks[1], state);

        // Controls
        self.draw_controls(f, chunks[2], state);

        // Volume
        self.draw_volume(f, chunks[3], state);

        // Progress
        self.draw_progress(f, chunks[4], state);

        // Logs or Playlists
        if self.playlists_visible {
            self.draw_playlists(f, chunks[5]);
        } else {
            self.draw_logs(f, chunks[5]);
        }

        // Status and input
        self.draw_status(f, chunks[6], state);
        
        // Command popup (drawn on top)
        if let TuiMode::Command = self.mode {
            self.draw_command_popup(f, size);
        }
        
        // Config window (drawn on top)
        if let TuiMode::Config = self.mode {
            self.draw_config_window(f, size);
        }

        // YouTube search window (drawn on top)
        if let TuiMode::YoutubeSearch = self.mode {
            self.draw_youtube_search(f, size);
        }
    }

    fn draw_playlists(&self, f: &mut Frame, area: Rect) {
        // Try to reload from disk to reflect external changes
        let mut mgr = self.playlists_manager.clone();
        let _ = mgr.reload();
    let mut title_text = "Playlists (P: close | Tab: focus | Enter: play | Del: delete".to_string();
    if self.pl_show_ids { title_text.push_str(" | I: hide IDs"); } else { title_text.push_str(" | I: show IDs"); }
    title_text.push(')');
    let outer = Block::default().title(title_text).borders(Borders::ALL);
        let inner = outer.inner(area);
        f.render_widget(outer, area);

        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(20), Constraint::Percentage(80)])
            .split(inner);

        // Left: playlists list
        let mut pls_lines: Vec<Line> = Vec::new();
        for (i, p) in mgr.list().iter().enumerate() {
            let selected = self.pl_focus == 1 && i == self.pl_selected_playlist_idx;
            let style = if selected { Style::default().bg(Color::DarkGray).fg(Color::White) } else { Style::default() };
            let marker = if i == self.pl_selected_playlist_idx { ">" } else { " " };
            if self.pl_show_ids {
                pls_lines.push(Line::from(vec![
                    Span::styled(format!("{} {}", marker, p.name), style),
                ]));
                pls_lines.push(Line::from(vec![Span::styled(format!("    id: {}", p.id), Style::default().fg(Color::Gray))]));
            } else {
                pls_lines.push(Line::from(vec![
                    Span::styled(format!("{} {}", marker, p.name), style),
                ]));
            }
        }
        if pls_lines.is_empty() {
            pls_lines.push(Line::from(Span::styled("No playlists. Use :pladd <name> to create.", Style::default().fg(Color::Gray))));
        }
        let pls = Paragraph::new(pls_lines)
            .block(Block::default().title("Playlists").borders(Borders::ALL))
            .wrap(Wrap { trim: true });
        f.render_widget(pls, cols[0]);

        // Right: items of selected playlist
        let right_block = Block::default().title("Items (Enter: play | Del: delete | In YouTube: A to add)").borders(Borders::ALL);
        let right_inner = right_block.inner(cols[1]);
        f.render_widget(right_block, cols[1]);

        let mut item_lines: Vec<Line> = Vec::new();
        if let Some(pl) = mgr.list().get(self.pl_selected_playlist_idx) {
            for (j, item) in pl.items.iter().enumerate() {
                let selected = self.pl_focus == 2 && j == self.pl_selected_item_idx;
                let mut style = if selected { Style::default().bg(Color::DarkGray).fg(Color::White) } else { Style::default() };
                let mut prefix = if j == self.pl_selected_item_idx { ">" } else { " " };
                if self.now_playing_playlist_id.as_deref() == Some(&pl.id) && self.now_playing_item_id.as_deref() == Some(&item.id) {
                    style = style.fg(Color::Green).add_modifier(Modifier::BOLD);
                    prefix = "▶";
                }
                item_lines.push(Line::from(vec![
                    Span::styled(format!("{} {}  [{}]  (played {}x)", prefix, item.name, item.duration, item.num_played), style)
                ]));
                if self.pl_show_ids {
                    item_lines.push(Line::from(vec![Span::styled(format!("      id: {}", item.id), Style::default().fg(Color::Gray))]));
                }
            }
            if item_lines.is_empty() {
                item_lines.push(Line::from(Span::styled("No items. Add via :plitemadd or from YouTube (A).", Style::default().fg(Color::Gray))));
            }
        } else {
            item_lines.push(Line::from(Span::styled("No playlist selected.", Style::default().fg(Color::Gray))));
        }
        let items = Paragraph::new(item_lines).wrap(Wrap { trim: true });
        f.render_widget(items, right_inner);
    }

    fn delete_selected_playlist_or_item(&mut self) -> Result<()> {
        if self.pl_focus == 1 {
            let id_opt = self.playlists_manager.list().get(self.pl_selected_playlist_idx).map(|p| p.id.clone());
            if let Some(id) = id_opt {
                let _ = self.command_sender.send(Command::PlaylistDelete { playlist_id: id.clone() });
                let _ = self.playlists_manager.remove_playlist(&id);
                let _ = self.playlists_manager.save();
                let _ = self.playlists_manager.reload();
                let _ = self.command_sender.send(Command::PlaylistReload);
                if self.pl_selected_playlist_idx > 0 { self.pl_selected_playlist_idx -= 1; }
            }
        } else if self.pl_focus == 2 {
            let ids_opt = self.playlists_manager.list().get(self.pl_selected_playlist_idx).and_then(|pl| pl.items.get(self.pl_selected_item_idx).map(|it| (pl.id.clone(), it.id.clone())));
            if let Some((pl_id, item_id)) = ids_opt {
                let _ = self.command_sender.send(Command::PlaylistItemDelete { playlist_id: pl_id.clone(), item_id: item_id.clone() });
                if let Some(pl_mut) = self.playlists_manager.list_mut().get_mut(self.pl_selected_playlist_idx) {
                    let _ = pl_mut.remove_item(&item_id);
                }
                let _ = self.playlists_manager.save();
                let _ = self.playlists_manager.reload();
                let _ = self.command_sender.send(Command::PlaylistReload);
                if self.pl_selected_item_idx > 0 { self.pl_selected_item_idx -= 1; }
            }
        }
        Ok(())
    }

    fn draw_media_info(&self, f: &mut Frame, area: Rect, state: &PlayerState) {
        let info_lines = vec![
            Line::from(vec![
                Span::styled("VLC Connection: ", Style::default().fg(Color::Yellow)),
                if state.connection_status.connected {
                    Span::styled("Connected", Style::default().fg(Color::Green))
                } else {
                    Span::styled("Disconnected", Style::default().fg(Color::Red))
                },
                Span::raw(format!(" ({}:{})", state.connection_status.host, state.connection_status.port)),
            ]),
            Line::from(vec![
                Span::styled("Password: ", Style::default().fg(Color::Yellow)),
                if state.connection_status.password_set && !state.connection_status.password.is_empty() {
                    Span::styled(&state.connection_status.password, Style::default().fg(Color::Cyan))
                } else {
                    Span::styled("Not Set", Style::default().fg(Color::Red))
                },
            ]),
            Line::from(vec![
                Span::styled("Status: ", Style::default().fg(Color::Yellow)),
                Span::raw(state.state.to_string()),
            ]),
            Line::from(vec![
                Span::styled("Title: ", Style::default().fg(Color::Yellow)),
                Span::raw(state.media_info.title.as_deref().unwrap_or("No media loaded")),
            ]),
            Line::from(vec![
                Span::styled("File: ", Style::default().fg(Color::Yellow)),
                Span::raw(&state.media_info.filename),
            ]),
            Line::from(vec![
                Span::styled("Loop: ", Style::default().fg(Color::Yellow)),
                if state.media_info.loop_enabled {
                    Span::styled("ON", Style::default().fg(Color::Green))
                } else {
                    Span::styled("OFF", Style::default().fg(Color::Red))
                },
                Span::raw("  "),
                Span::styled("Fullscreen: ", Style::default().fg(Color::Yellow)),
                if state.fullscreen {
                    Span::styled("ON", Style::default().fg(Color::Green))
                } else {
                    Span::styled("OFF", Style::default().fg(Color::Red))
                },
            ]),
        ];

        let media_info = Paragraph::new(info_lines)
            .block(Block::default().title("Media Info").borders(Borders::ALL))
            .wrap(Wrap { trim: true });
        f.render_widget(media_info, area);
    }

    fn draw_controls(&self, f: &mut Frame, area: Rect, _state: &PlayerState) {
        let controls_text = vec![
            Line::from(vec![
                Span::styled("Space", Style::default().fg(Color::Green)),
                Span::raw(": Play/Pause  "),
                Span::styled("S", Style::default().fg(Color::Green)),
                Span::raw(": Stop  "),
                Span::styled("M", Style::default().fg(Color::Green)),
                Span::raw(": Mute  "),
                Span::styled("F", Style::default().fg(Color::Green)),
                Span::raw(": Fullscreen  "),
                Span::styled("L", Style::default().fg(Color::Green)),
                Span::raw(": Loop"),
            ]),
            Line::from(vec![
                Span::styled("C", Style::default().fg(Color::Yellow)),
                Span::raw(": Test Connection  "),
                Span::styled("Shift+C", Style::default().fg(Color::Magenta)),
                Span::raw(": Config  "),
                Span::styled("P", Style::default().fg(Color::Green)),
                Span::raw(": Playlists  "),
                Span::styled("Y", Style::default().fg(Color::Red)),
                Span::raw(": YouTube Search  "),
                Span::styled("I", Style::default().fg(Color::Green)),
                Span::raw(": Input  "),
                Span::styled("H", Style::default().fg(Color::Green)),
                Span::raw(": Help  "),
                Span::styled("Q", Style::default().fg(Color::Green)),
                Span::raw(": Quit"),
            ]),
        ];

        let controls = Paragraph::new(controls_text)
            .block(Block::default().title("Controls").borders(Borders::ALL))
            .alignment(Alignment::Center);
        f.render_widget(controls, area);
    }

    fn draw_volume(&self, f: &mut Frame, area: Rect, state: &PlayerState) {
        let volume_ratio = (state.media_info.volume / 100.0).clamp(0.0, 1.0);
        let volume_text = utils::format_volume(state.media_info.volume, state.media_info.muted);
        
        let volume_gauge = Gauge::default()
            .block(Block::default().title("Volume").borders(Borders::ALL))
            .gauge_style(Style::default().fg(if state.media_info.muted { 
                Color::Red 
            } else { 
                Color::Blue 
            }))
            .ratio(volume_ratio)
            .label(volume_text);
        f.render_widget(volume_gauge, area);
    }

    fn draw_progress(&self, f: &mut Frame, area: Rect, state: &PlayerState) {
        let progress_ratio = if let Some(duration) = state.media_info.duration {
            if duration > 0.0 {
                (state.media_info.position / duration).clamp(0.0, 1.0)
            } else {
                0.0
            }
        } else {
            0.0
        };

        let position_text = utils::format_duration(state.media_info.position);
        let duration_text = state.media_info.duration
            .map(utils::format_duration)
            .unwrap_or_else(|| "??:??".to_string());
        let speed_text = utils::format_speed(state.media_info.speed);

        let progress_text = format!("{} / {} | {}", position_text, duration_text, speed_text);

        let progress_gauge = Gauge::default()
            .block(Block::default().title("Progress").borders(Borders::ALL))
            .gauge_style(Style::default().fg(Color::Green))
            .ratio(progress_ratio)
            .label(progress_text);
        f.render_widget(progress_gauge, area);
    }

    fn draw_logs(&self, f: &mut Frame, area: Rect) {
        // Calculate how many lines we can display
        let available_height = area.height.saturating_sub(2) as usize; // Subtract 2 for borders
        
        // Get the last N logs that fit in the area, ensuring we show the most recent logs
        let start_index = if self.logs.len() > available_height {
            self.logs.len() - available_height
        } else {
            0
        };
        
        let log_lines: Vec<Line> = self.logs
            .iter()
            .skip(start_index)
            .map(|log| {
                let color = match log.level.as_str() {
                    "ERROR" => Color::Red,
                    "WARN" => Color::Yellow,
                    "INFO" => Color::Green,
                    "DEBUG" => Color::Blue,
                    _ => Color::White,
                };
                
                // Add timestamp for better tracking
                let timestamp = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs() % 86400; // Get seconds since midnight
                
                let hours = timestamp / 3600;
                let minutes = (timestamp % 3600) / 60;
                let seconds = timestamp % 60;
                
                Line::from(vec![
                    Span::styled(
                        format!("[{:02}:{:02}:{:02}] ", hours, minutes, seconds), 
                        Style::default().fg(Color::Gray)
                    ),
                    Span::styled(format!("[{}] ", log.level), Style::default().fg(color)),
                    Span::raw(&log.message),
                ])
            })
            .collect();

        let logs = Paragraph::new(log_lines)
            .block(Block::default().title("Logs").borders(Borders::ALL))
            .wrap(Wrap { trim: true })
            .scroll((0, 0)); // Always show from the top since we're pre-filtering
        f.render_widget(logs, area);
    }

    fn draw_status(&self, f: &mut Frame, area: Rect, state: &PlayerState) {
        let status_text = match self.mode {
            TuiMode::Normal => {
                if self.loading {
                    Line::from(vec![
                        Span::styled("Loading media... ", Style::default().fg(Color::Yellow)),
                        Span::raw(&self.status_message),
                    ])
                } else if let Some(ref error) = state.error_message {
                    Line::from(vec![
                        Span::styled("Error: ", Style::default().fg(Color::Red)),
                        Span::styled(error, Style::default().fg(Color::Red)),
                    ])
                } else {
                    let state_text = format!("State: {} | ", state.state);
                    Line::from(vec![
                        Span::styled("Ready - ", Style::default().fg(Color::Green)),
                        Span::raw(state_text),
                        Span::raw(&self.status_message),
                    ])
                }
            }
            TuiMode::Input => {
                Line::from(vec![
                    Span::styled("Enter file path or URL: ", Style::default().fg(Color::Yellow)),
                    Span::raw(&self.input),
                    Span::styled("█", Style::default().fg(Color::White)),
                ])
            }
            TuiMode::Command => {
                Line::from(vec![
                    Span::styled("Command: :", Style::default().fg(Color::Yellow)),
                    Span::raw(&self.command_input),
                    Span::styled("█", Style::default().fg(Color::White)),
                ])
            }
            TuiMode::Help => {
                Line::from(Span::styled("Press ESC or H to close help", Style::default().fg(Color::Cyan)))
            }
            TuiMode::Config => {
                Line::from(vec![
                    Span::styled("Config Mode - ", Style::default().fg(Color::Magenta)),
                    Span::raw(format!("Section: {} | ", self.config_sections.get(self.config_section_index).unwrap_or(&"Unknown".to_string()))),
                    Span::styled("↑↓: Navigate | ←→: Change section | Enter: Edit | R: Reset | S: Save | ESC: Exit", Style::default().fg(Color::Gray)),
                ])
            }
            TuiMode::YoutubeSearch => {
                let hint = if self.yt_search_input_active {
                    "Type to search, Enter: run, Esc: close, Tab: toggle focus"
                } else {
                    "↑/↓: select, Enter: open, A: toggle audio/video, R: re-run, Tab: focus input, Esc: close"
                };
                Line::from(vec![
                    Span::styled("YouTube Search - ", Style::default().fg(Color::Red)),
                    Span::raw(hint),
                ])
            }
        };

        let status = Paragraph::new(status_text)
            .block(Block::default().title("Status").borders(Borders::ALL))
            .wrap(Wrap { trim: true });
        f.render_widget(status, area);
    }

    // --- YouTube Search UI and logic ---
    fn handle_youtube_search_key(&mut self, key: KeyCode) -> Result<bool> {
        if self.yt_search_input_active {
            match key {
                KeyCode::Esc => {
                    self.mode = TuiMode::Normal;
                }
                KeyCode::Enter => {
                    self.start_youtube_search();
                }
                KeyCode::Backspace => { self.yt_search_query.pop(); }
                KeyCode::Tab => { self.yt_search_input_active = false; }
                KeyCode::Char(c) => { self.yt_search_query.push(c); }
                _ => {}
            }
        } else {
            match key {
                KeyCode::Esc => { self.mode = TuiMode::Normal; }
                KeyCode::Tab => { self.yt_search_input_active = true; }
                KeyCode::Up | KeyCode::Char('k') => {
                    if !self.yt_search_results.is_empty() {
                        if self.yt_selected_index == 0 { self.yt_selected_index = self.yt_search_results.len() - 1; }
                        else { self.yt_selected_index -= 1; }
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    if !self.yt_search_results.is_empty() {
                        self.yt_selected_index = (self.yt_selected_index + 1) % self.yt_search_results.len();
                    }
                }
                KeyCode::Char('r') | KeyCode::Char('R') => { self.start_youtube_search(); }
                KeyCode::Enter => {
                    if let Some(sel) = self.yt_search_results.get(self.yt_selected_index).cloned() {
                        let url_to_open = format!("http://youtube.com/watch?v={}", sel.id);
                        let _ = self.command_sender.send(Command::Open(url_to_open));
                        self.mode = TuiMode::Normal;
                    }
                }
                KeyCode::Char('a') | KeyCode::Char('A') => {
                    if let Some(sel) = self.yt_search_results.get(self.yt_selected_index).cloned() {
                        if let Some(pl) = self.playlists_manager.list().get(self.pl_selected_playlist_idx) {
                            let item = crate::playlists::PlaylistItem {
                                name: sel.title.clone(),
                                id: sel.id.clone(),
                                url: format!("http://youtube.com/watch?v={}", sel.id),
                                num_played: 0,
                                duration: sel.duration.clone().unwrap_or_default(),
                                time_added: 0,
                            };
                            let _ = self.command_sender.send(Command::PlaylistItemAdd { playlist_id: pl.id.clone(), item });
                            // Also add locally for immediate UI feedback
                            if let Some(pl_mut) = self.playlists_manager.list_mut().get_mut(self.pl_selected_playlist_idx) {
                                let item_local = crate::playlists::PlaylistItem {
                                    name: sel.title,
                                    id: sel.id.clone(),
                                    url: format!("http://youtube.com/watch?v={}", sel.id.clone()),
                                    num_played: 0,
                                    duration: sel.duration.unwrap_or_default(),
                                    time_added: 0,
                                };
                                pl_mut.add_item(item_local);
                                let _ = self.playlists_manager.save();
                                let _ = self.playlists_manager.reload();
                                let _ = self.command_sender.send(Command::PlaylistReload);
                            }
                            self.add_log("INFO", "Added to current playlist");
                        }
                    }
                }
                _ => {}
            }
        }

        // poll incremental results if running
        if let Some(rx) = self.yt_result_rx.as_ref() {
            while let Ok(item) = rx.try_recv() {
                // merge or push
                self.yt_search_results.push(item);
            }
        }
        Ok(false)
    }

    fn draw_youtube_search(&self, f: &mut Frame, area: Rect) {
        let popup = centered_rect(90, 80, area);
        f.render_widget(Clear, popup);

        let outer = Block::default()
            .title("YouTube Search")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Red));
        let inner = outer.inner(popup);
        f.render_widget(outer, popup);

        let cols = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3), // input
                Constraint::Min(5),    // results
                Constraint::Length(2), // footer
            ])
            .split(inner);

        // Input
        let input_line = if self.yt_search_input_active { format!("Query: {}█", self.yt_search_query) } else { format!("Query: {}", self.yt_search_query) };
        let input = Paragraph::new(input_line)
            .block(Block::default().title("Search Query (Enter to run)").borders(Borders::ALL))
            .style(Style::default().fg(if self.yt_search_input_active { Color::Yellow } else { Color::Gray }));
        f.render_widget(input, cols[0]);

        // Results list
        let mut lines: Vec<Line> = Vec::new();
        if self.yt_is_searching && self.yt_search_results.is_empty() {
            lines.push(Line::from(Span::styled("Searching... results will appear as they arrive", Style::default().fg(Color::Gray))));
        }
        for (i, r) in self.yt_search_results.iter().enumerate() {
            let sel = i == self.yt_selected_index && !self.yt_search_input_active;
            let mut spans = vec![
                Span::styled(format!("{} ", i + 1), Style::default().fg(Color::Gray)),
                Span::styled(r.title.clone(), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
            ];
            if let Some(d) = &r.duration { spans.push(Span::raw(format!("  [{}]", d))); }
            if sel {
                lines.push(Line::from(spans.into_iter().map(|mut s| { s.style = s.style.bg(Color::DarkGray); s }).collect::<Vec<_>>()));
            } else {
                lines.push(Line::from(spans));
            }
        }
        if self.yt_search_results.is_empty() && !self.yt_is_searching {
            lines.push(Line::from(Span::styled("No results. Type a query and press Enter.", Style::default().fg(Color::Gray))));
        }
        let results = Paragraph::new(lines)
            .block(Block::default().title("Results (↑/↓ to select, Enter to open)").borders(Borders::ALL))
            .wrap(Wrap { trim: true });
        f.render_widget(results, cols[1]);

        // Footer
        let footer_text = if self.yt_is_searching {
            "Status: Searching… Esc: Close | Tab: Toggle focus | Enter: Open | A: Add to playlist"
        } else {
            "Tab: Toggle focus | R: Re-run last query | Enter: Open selected | A: Add to current playlist"
        };
        let footer = Paragraph::new(footer_text)
        .style(Style::default().fg(Color::Gray))
        .alignment(Alignment::Center);
        f.render_widget(footer, cols[2]);
    }

    fn start_youtube_search(&mut self) {
        let query = self.yt_search_query.trim().to_string();
        if query.is_empty() {
            self.add_log("WARN", "YouTube search: empty query");
            return;
        }
        self.yt_search_results.clear();
        self.yt_selected_index = 0;
        self.yt_is_searching = true;

        let (tx, rx) = mpsc::channel::<YouTubeSearchResult>();
        self.yt_result_rx = Some(rx);

        // Spawn worker thread to run yt-dlp and stream results
        let query_for_worker = format!("ytsearch10:{}", query);
        let logger = self.command_sender.clone();
        thread::spawn(move || {
            // Build yt-dlp command. We request fields in the exact order we parse: title, id, duration
            // The user expects ID (not URL); we'll construct the watch URL on selection.
            let mut cmd = OsCommand::new("yt-dlp");
            cmd.arg(&query_for_worker)
                .arg("--no-playlist")
                // Match sample output order: Title, ID, Duration
                .arg("--get-title")
                .arg("--get-id")
                .arg("--get-duration")
                .stdout(Stdio::piped())
                .stderr(Stdio::piped());

            // Log the command we're about to run
            let _ = logger.send(Command::Log(LogEntry { level: "DEBUG".into(), message: format!("Running: {:?}", cmd) }));

            let mut child = match cmd.spawn() {
                Ok(child) => child,
                Err(e) => {
                    let _ = logger.send(Command::Log(LogEntry { level: "ERROR".into(), message: format!("Failed to start yt-dlp: {}", e) }));
                    // Drop sender to signal completion
                    drop(tx);
                    return;
                }
            };

            // Read stdout line by line
            if let Some(stdout) = child.stdout.take() {
                let reader = BufReader::new(stdout);
                let mut field_step = 0usize; // 0: title, 1: id, 2: duration
                let mut cur_title: Option<String> = None;
                let mut cur_id: Option<String> = None;
                let mut cur_duration: Option<String> = None;

                for line_res in reader.lines() {
                    match line_res {
                        Ok(line_raw) => {
                            let line = line_raw.trim().to_string();
                            if line.is_empty() {
                                continue;
                            }
                            match field_step {
                                0 => { // title
                                    cur_title = Some(line);
                                    field_step = 1;
                                }
                                1 => { // id
                                    cur_id = Some(line);
                                    field_step = 2;
                                }
                                2 => { // duration
                                    let result = YouTubeSearchResult {
                                        title: cur_title.take().unwrap_or_default(),
                                        id: cur_id.take().unwrap_or_default(),
                                        duration: Some(line),
                                    };
                                    // Try to send; if receiver gone, stop early
                                    let _ = logger.send(Command::Log(LogEntry { level: "INFO".into(), message: format!("Found YouTube video: [{}] {}", result.id, result.title) }));
                                    if tx.send(result).is_err() {
                                        let _ = logger.send(Command::Log(LogEntry { level: "DEBUG".into(), message: "Search receiver dropped; stopping worker".into() }));
                                        break;
                                    }
                                    field_step = 0;
                                }
                                _ => {
                                    field_step = 0;
                                }
                            }
                        }
                        Err(e) => {
                            let _ = logger.send(Command::Log(LogEntry { level: "ERROR".into(), message: format!("yt-dlp read error: {}", e) }));
                            break;
                        }
                    }
                }

                // If we ended mid-record, try to emit partial only if we have at least title and id
                if field_step != 0 {
                    let _ = logger.send(Command::Log(LogEntry { level: "INFO".into(), message: format!("Incomplete record at end of output; step {}", field_step) }));
                    if let (Some(title), Some(id)) = (cur_title.take(), cur_id.take()) {
                        let _ = tx.send(YouTubeSearchResult { title, id, duration: cur_duration.take() });
                    }
                }
            }

            // Drain and log stderr for diagnostics (optional)
            if let Some(mut stderr) = child.stderr.take() {
                use std::io::Read;
                let mut buf = String::new();
                if stderr.read_to_string(&mut buf).is_ok() && !buf.trim().is_empty() {
                    let _ = logger.send(Command::Log(LogEntry { level: "DEBUG".into(), message: format!("yt-dlp stderr: {}", buf.trim()) }));
                }
            }

            // Wait for process to exit
            if let Err(e) = child.wait() {
                let _ = logger.send(Command::Log(LogEntry { level: "ERROR".into(), message: format!("yt-dlp wait failed: {}", e) }));
            }

            // Close the channel to signal completion
            drop(tx);
        });

    }


    fn draw_help(&self, f: &mut Frame, area: Rect) {
        let help_text = vec![
            Line::from("BCK Player - VLC HTTP Interface"),
            Line::from(""),
            Line::from("BASIC CONTROLS:"),
            Line::from("  Space    - Play/Pause"),
            Line::from("  S        - Stop"),
            Line::from("  I        - Input mode (load file/URL)"),
            Line::from("  :        - Command mode (vim-like commands)"),
            Line::from(""),
            Line::from("VOLUME & NAVIGATION:"),
            Line::from("  M        - Toggle Mute"),
            Line::from("  ↑/↓      - Volume Up/Down"),
            Line::from("  ←/→      - Seek Backward/Forward"),
            Line::from(""),
            Line::from("PLAYBACK:"),
            Line::from("  +/-      - Speed Up/Down (limited support)"),
            Line::from("  R        - Reset Speed"),
            Line::from("  F        - Toggle Fullscreen"),
            Line::from(""),
            Line::from("OTHER:"),
            Line::from("  Y        - Open YouTube Search"),
            Line::from("  H        - Toggle this help"),
            Line::from("  Q        - Quit"),
            Line::from("  C        - Test VLC connection"),
            Line::from(""),
            Line::from("YOUTUBE SEARCH:"),
            Line::from("  Press Y to open the search window."),
            Line::from("  Type your query, press Enter to run. Results stream in as found."),
            Line::from("  Use ↑/↓ to select, Enter to open the selected result in player."),
            Line::from("  Tab toggles focus between input and results. Esc closes."),
            Line::from("  Example query: lebron james (fetches top 10 via yt-dlp)."),
            Line::from(""),
            Line::from("COMMAND MODE (vim-like):"),
            Line::from("  Press : to enter command mode"),
            Line::from("  Smart fuzzy matching with multiple strategies:"),
            Line::from("    • Exact matches (highest priority)"),
            Line::from("    • Prefix matches (e.g., 'vol' → volume commands)"),
            Line::from("    • Keyword matches (e.g., 'louder' → volumeup)"),
            Line::from("    • Fuzzy matches (e.g., 'sped' → speed commands)"),
            Line::from("  Press Enter to execute, Esc to cancel"),
            Line::from(""),
            Line::from("PLAYBACK COMMANDS:"),
            Line::from("  :play, :pause, :stop, :toggle"),
            Line::from(""),
            Line::from("MEDIA LOADING:"),
            Line::from("  :open /path/to/file.mp4"),
            Line::from("  :open https://example.com/video.mp4"),
            Line::from("  :load <path>  (alias for open)"),
            Line::from(""),
            Line::from("VOLUME CONTROL:"),
            Line::from("  :volume 50, :vol 75    (set volume 0-100)"),
            Line::from("  :volumeup, :volup      (increase volume)"),
            Line::from("  :volumedown, :voldown  (decrease volume)"),
            Line::from("  :mute, :unmute         (toggle/set mute)"),
            Line::from(""),
            Line::from("SEEKING:"),
            Line::from("  :seek 30        (seek forward 30 seconds)"),
            Line::from("  :seek -10       (seek backward 10 seconds)"),
            Line::from("  :seekto 120     (seek to 2 minutes)"),
            Line::from("  :forward 10     (seek forward, default 10s)"),
            Line::from("  :backward 5     (seek backward, default 10s)"),
            Line::from(""),
            Line::from("PLAYBACK SPEED:"),
            Line::from("  :speed 1.5      (set speed to 1.5x)"),
            Line::from("  :speed 0.5      (set speed to 0.5x)"),
            Line::from("  :speedup        (increase speed)"),
            Line::from("  :speeddown      (decrease speed)"),
            Line::from("  :speedreset     (reset to 1.0x)"),
            Line::from(""),
            Line::from("DISPLAY:"),
            Line::from("  :fullscreen           (enter fullscreen)"),
            Line::from("  :windowed             (exit fullscreen)"),
            Line::from("  :togglefullscreen     (toggle fullscreen)"),
            Line::from(""),
            Line::from("SYSTEM:"),
            Line::from("  :quit, :exit    (quit application)"),
            Line::from("  :help           (show this help)"),
            Line::from("  :test           (test VLC connection)"),
            Line::from(""),
            Line::from("CONNECTION (future):"),
            Line::from("  :connect <host> [port]  (connect to VLC instance)"),
            Line::from("  :disconnect             (disconnect from VLC)"),
            Line::from(""),
            Line::from("CONFIG (future):"),
            Line::from("  :config         (show configuration)"),
            Line::from("  :save           (save configuration)"),
            Line::from("  :reload         (reload configuration)"),
            Line::from(""),
            Line::from("HELP NAVIGATION:"),
            Line::from("  ↑/↓, j/k       - Scroll up/down"),
            Line::from("  Page Up/Down   - Scroll by page"),
            Line::from("  Home/End       - Go to top/bottom"),
            Line::from("  ESC, H, Q      - Close help"),
            Line::from(""),
            Line::from("NOTES:"),
            Line::from("  • VLC is started automatically with HTTP interface"),
            Line::from("  • Smart fuzzy search with multiple matching strategies"),
            Line::from("  • Commands ranked by relevance (exact > prefix > fuzzy)"),
            Line::from("  • Keyword aliases supported (e.g., 'louder', 'fs', 'goto')"),
            Line::from("  • Parameters are validated with helpful error messages"),
            Line::from("  • Real-time suggestions appear as you type"),
            Line::from(""),
            Line::from("Press ESC, H, or Q to close help"),
        ];

        // Clear the background
        let clear = Clear;
        f.render_widget(clear, area);

        // Calculate centered area for help
        let help_area = centered_rect(90, 90, area);
        
        // Calculate scrolling
        let content_height = help_text.len();
        let display_height = help_area.height.saturating_sub(2) as usize; // Account for borders
        let max_scroll = content_height.saturating_sub(display_height);
        let scroll_pos = (self.help_scroll as usize).min(max_scroll);
        
        // Get the visible portion of help text
        let visible_text: Vec<Line> = help_text
            .into_iter()
            .skip(scroll_pos)
            .take(display_height)
            .collect();

        let scroll_info = if max_scroll > 0 {
            format!(" - Scroll: {}/{} (↑↓/jk/PgUp/PgDn)", scroll_pos + 1, max_scroll + 1)
        } else {
            String::new()
        };

        let help = Paragraph::new(visible_text)
            .block(
                Block::default()
                    .title(format!("Help{}", scroll_info))
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Cyan))
                    .style(Style::default().bg(Color::Black))
            )
            .alignment(Alignment::Left)
            .wrap(Wrap { trim: true });
        f.render_widget(help, help_area);
    }

    fn draw_command_popup(&self, f: &mut Frame, area: Rect) {
        // Get command suggestions based on current input
        let suggestions = get_command_suggestions(&self.command_input);
        
        // Create command input display
        let command_display = format!(":{}", self.command_input);
        
        // Calculate popup area - positioned at the top
        let popup_height = if suggestions.is_empty() { 
            3  // Just space for command input
        } else { 
            // Command input (3) + suggestions with borders (at least 3) = minimum 6
            // Add extra space for multiple suggestions: 3 + max(3, suggestions.len() + 2)
            let suggestions_height = (suggestions.len() as u16 + 2).max(3); // +2 for borders, min 3 total
            (3 + suggestions_height).min(15) // Max 15 lines total
        };
        
        let popup_area = Rect {
            x: area.x + 1,
            y: area.y + 1,
            width: area.width.saturating_sub(2),
            height: popup_height.min(area.height.saturating_sub(2)),
        };
        
        // Clear the background
        f.render_widget(Clear, popup_area);
        
        // Create the command input widget
        let command_input = Paragraph::new(command_display)
            .style(Style::default().fg(Color::Yellow))
            .block(
                Block::default()
                    .title("Command")
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Yellow))
                    .style(Style::default().bg(Color::Black))
            );
        
        // Calculate areas for input and suggestions
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3), // Command input
                Constraint::Min(0),    // Suggestions
            ])
            .split(popup_area);
        
        f.render_widget(command_input, chunks[0]);
        
        // Draw suggestions if available (always show, even for single suggestion)
        if !suggestions.is_empty() && chunks.len() > 1 {
            // Ensure suggestion index is within bounds
            let bounded_index = if self.command_suggestion_index >= suggestions.len() {
                0
            } else {
                self.command_suggestion_index
            };
            
            let suggestion_lines: Vec<Line> = suggestions
                .iter()
                .enumerate()
                .take(10) // Limit to 10 suggestions
                .map(|(i, s)| {
                    let is_selected = i == bounded_index;
                    
                    Line::from(vec![
                        Span::styled(
                            format!("  {} ", s.command),
                            if is_selected {
                                Style::default().fg(Color::Black).bg(Color::Yellow).add_modifier(Modifier::BOLD)
                            } else {
                                Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)
                            }
                        ),
                        Span::styled(
                            s.description.clone(),
                            if is_selected {
                                Style::default().fg(Color::Black).bg(Color::Yellow)
                            } else {
                                Style::default().fg(Color::Gray)
                            }
                        ),
                    ])
                })
                .collect();
            
            let title = if suggestions.len() > 10 {
                format!("Suggestions (showing 10 of {}) - ↑↓ to navigate, Tab to complete", suggestions.len())
            } else if suggestions.len() > 1 {
                format!("Suggestions ({}) - ↑↓ to navigate, Tab to complete", suggestions.len())
            } else {
                "Suggestion - Tab to complete".to_string()
            };
            
            let suggestions_widget = Paragraph::new(suggestion_lines)
                .block(
                    Block::default()
                        .title(title)
                        .borders(Borders::ALL)
                        .border_style(Style::default().fg(Color::Green))
                        .style(Style::default().bg(Color::Black))
                )
                .wrap(Wrap { trim: true });
            
            f.render_widget(suggestions_widget, chunks[1]);
        }
    }

    fn draw_config_window(&self, f: &mut Frame, area: Rect) {
        use crate::config_manager::ConfigManager;
        use crate::config::Config;
        use crate::config_modules::{NetworkConfig, AppearanceConfig, MediaConfig, AdvancedConfig, YoutubeConfig};
        
        let popup_area = centered_rect(80, 80, area);
        
        // Clear the area behind the popup
        f.render_widget(Clear, popup_area);
        
        let block = Block::default()
            .title("Configuration Manager")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Magenta));
        
        let inner_area = block.inner(popup_area);
        f.render_widget(block, popup_area);
        
        // Create layout for config sections and content
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(25), // Section list
                Constraint::Percentage(75), // Config content
            ])
            .split(inner_area);
        
        // Draw section list
        let mut section_items = Vec::new();
        for (i, section) in self.config_sections.iter().enumerate() {
            let style = if i == self.config_section_index {
                Style::default().fg(Color::Black).bg(Color::Magenta)
            } else {
                Style::default().fg(Color::White)
            };
            section_items.push(Line::from(Span::styled(format!(" {} ", section), style)));
        }
        
        let sections_block = Block::default()
            .title("Sections")
            .borders(Borders::ALL);
        let sections = Paragraph::new(section_items)
            .block(sections_block)
            .wrap(Wrap { trim: true });
        f.render_widget(sections, chunks[0]);
        
        // Draw config content based on selected section
        let content_block = Block::default()
            .title("Settings")
            .borders(Borders::ALL);
        
        let config_manager = match ConfigManager::new() {
            Ok(manager) => manager,
            Err(_) => {
                let error_content = Paragraph::new("Error: Could not access config manager")
                    .block(content_block)
                    .style(Style::default().fg(Color::Red));
                f.render_widget(error_content, chunks[1]);
                return;
            }
        };
        
        let content_lines = match self.config_section_index {
            0 => { // Player config
                let config: Config = config_manager.get();
                vec![
                    Line::from(format!("Default Volume: {:.1}", config.default_volume)),
                    Line::from(format!("Default Speed: {:.1}x", config.default_speed)),
                    Line::from(format!("Fullscreen by Default: {}", config.fullscreen_by_default)),
                    Line::from(format!("Update Interval: {}ms", config.ui.update_interval_ms)),
                    Line::from(format!("Volume Step: {:.1}", config.ui.volume_step)),
                    Line::from(format!("Seek Step: {:.1}s", config.ui.seek_step)),
                    Line::from(format!("Speed Step: {:.1}", config.ui.speed_step)),
                    Line::from(format!("Show Milliseconds: {}", config.ui.show_milliseconds)),
                ]
            },
            1 => { // Network config
                let config: NetworkConfig = config_manager.get();
                vec![
                    Line::from(format!("Timeout: {}s", config.timeout_seconds)),
                    Line::from(format!("Retry Attempts: {}", config.retry_attempts)),
                    Line::from(format!("User Agent: {}", config.user_agent)),
                    Line::from(format!("Proxy URL: {}", config.proxy_url.as_deref().unwrap_or("None"))),
                    Line::from(format!("Max Redirects: {}", config.max_redirects)),
                ]
            },
            2 => { // Appearance config
                let config: AppearanceConfig = config_manager.get();
                vec![
                    Line::from(format!("Theme: {}", config.theme)),
                    Line::from(format!("Font Size: {}", config.font_size)),
                    Line::from(format!("Show FPS: {}", config.show_fps)),
                    Line::from(format!("Show Logs: {}", config.show_logs)),
                    Line::from(format!("Log Level: {}", config.log_level)),
                    Line::from(format!("Progress Bar Style: {}", config.progress_bar_style)),
                ]
            },
            3 => { // Media config
                let config: MediaConfig = config_manager.get();
                vec![
                    Line::from(format!("Auto Load Subtitles: {}", config.auto_load_subtitles)),
                    Line::from(format!("Subtitle Languages: {}", config.subtitle_languages.join(", "))),
                    Line::from(format!("Audio Languages: {}", config.audio_languages.join(", "))),
                    Line::from(format!("Hardware Decoding: {}", config.hardware_decoding)),
                    Line::from(format!("Buffer Size: {:.1}s", config.buffer_size_seconds)),
                    Line::from(format!("Skip Intro: {}", config.skip_intro_seconds.map_or("None".to_string(), |s| format!("{:.1}s", s)))),
                    Line::from(format!("Skip Outro: {}", config.skip_outro_seconds.map_or("None".to_string(), |s| format!("{:.1}s", s)))),
                ]
            },
            4 => { // Advanced config
                let config: AdvancedConfig = config_manager.get();
                vec![
                    Line::from(format!("Debug Mode: {}", config.debug_mode)),
                    Line::from(format!("Memory Limit: {}", config.memory_limit_mb.map_or("None".to_string(), |m| format!("{}MB", m)))),
                    Line::from(format!("CPU Cores: {}", config.cpu_cores.map_or("Auto".to_string(), |c| c.to_string()))),
                    Line::from(format!("Experimental Features: {}", config.experimental_features)),
                    Line::from(format!("Custom FFmpeg Args: {}", config.custom_ffmpeg_args.join(" "))),
                    Line::from(format!("Log File: {}", config.log_file_path.as_ref().map_or("None".to_string(), |p| p.display().to_string()))),
                    Line::from(format!("Performance Monitoring: {}", config.performance_monitoring)),
                ]
            },
            5 => { // YouTube config
                let config: YoutubeConfig = config_manager.get();
                vec![
                    Line::from(format!("Enabled: {}", config.enabled)),
                    Line::from(format!("Cache Directory: {}", config.cache_directory.display())),
                    Line::from(format!("Max Cache Size: {}MB", config.max_cache_size_mb)),
                    Line::from(format!("Max Cache Age: {} days", config.max_cache_age_days)),
                    Line::from(format!("Preferred Quality: {}", config.preferred_quality)),
                    Line::from(format!("Audio Only: {}", config.audio_only)),
                    Line::from(format!("yt-dlp Path: {}", config.ytdlp_path.as_ref().map_or("Auto".to_string(), |p| p.display().to_string()))),
                    Line::from(format!("Concurrent Downloads: {}", config.concurrent_downloads)),
                    Line::from(format!("Retry Attempts: {}", config.retry_attempts)),
                ]
            },
            _ => vec![Line::from("Invalid section")],
        };
        
        // Highlight selected item and show editing mode
        let highlighted_lines: Vec<Line> = content_lines.into_iter().enumerate().map(|(i, mut line)| {
            if i == self.config_item_index {
                if self.config_editing {
                    // Show editing mode with input
                    let field_name = line.spans[0].content.split(':').next().unwrap_or("Field");
                    line = Line::from(vec![
                        Span::styled(format!("{}: ", field_name), Style::default().fg(Color::Yellow)),
                        Span::styled(&self.config_edit_input, Style::default().fg(Color::White).bg(Color::Blue)),
                        Span::styled("_", Style::default().fg(Color::White).bg(Color::Blue)), // Cursor
                    ]);
                } else {
                    // Apply normal highlight style to all spans in the line
                    for span in &mut line.spans {
                        span.style = span.style.bg(Color::DarkGray);
                    }
                }
            }
            line
        }).collect();
        
        let content = Paragraph::new(highlighted_lines)
            .block(content_block)
            .wrap(Wrap { trim: true });
        f.render_widget(content, chunks[1]);
        
        // Add instructions at the bottom
        let instructions_text = if self.config_editing {
            "Enter: Save | ESC: Cancel | Type to edit value"
        } else {
            "↑↓: Navigate | ←→: Change section | Enter: Edit | R: Reset | S: Save | ESC: Exit"
        };
        let instructions = Paragraph::new(instructions_text)
            .style(Style::default().fg(Color::Gray))
            .alignment(Alignment::Center);
        
        let instruction_area = Rect {
            x: popup_area.x + 1,
            y: popup_area.y + popup_area.height - 2,
            width: popup_area.width - 2,
            height: 1,
        };
        f.render_widget(instructions, instruction_area);
    }

    fn get_config_item_count(&self) -> usize {
        match self.config_section_index {
            0 => 8,  // Player config items
            1 => 5,  // Network config items (updated to match actual fields)
            2 => 6,  // Appearance config items (updated to match actual fields)  
            3 => 7,  // Media config items (updated to match actual fields)
            4 => 7,  // Advanced config items
            5 => 9,  // YouTube config items (enabled, cache_directory, max_cache_size_mb, max_cache_age_days, preferred_quality, audio_only, ytdlp_path, concurrent_downloads, retry_attempts)
            _ => 1,
        }
    }

    fn start_config_edit(&mut self) -> Result<()> {
        use crate::config_manager::ConfigManager;
        use crate::config::Config;
        use crate::config_modules::{NetworkConfig, AppearanceConfig, MediaConfig, AdvancedConfig, YoutubeConfig};

        let config_manager = ConfigManager::new()?;
        
        // Get current value and set it as edit input
        let current_value = match self.config_section_index {
            0 => { // Player config
                let config: Config = config_manager.get();
                match self.config_item_index {
                    0 => config.default_volume.to_string(),
                    1 => config.default_speed.to_string(),
                    2 => config.fullscreen_by_default.to_string(),
                    3 => config.ui.update_interval_ms.to_string(),
                    4 => config.ui.volume_step.to_string(),
                    5 => config.ui.seek_step.to_string(),
                    6 => config.ui.speed_step.to_string(),
                    7 => config.ui.show_milliseconds.to_string(),
                    _ => "unknown".to_string(),
                }
            },
            1 => { // Network config
                let config: NetworkConfig = config_manager.get();
                match self.config_item_index {
                    0 => config.timeout_seconds.to_string(),
                    1 => config.retry_attempts.to_string(),
                    2 => config.user_agent.clone(),
                    3 => config.proxy_url.as_ref().map_or("None".to_string(), |p| p.clone()),
                    4 => config.max_redirects.to_string(),
                    _ => "unknown".to_string(),
                }
            },
            2 => { // Appearance config
                let config: AppearanceConfig = config_manager.get();
                match self.config_item_index {
                    0 => config.theme,
                    1 => config.font_size.to_string(),
                    2 => config.show_fps.to_string(),
                    3 => config.show_logs.to_string(),
                    4 => config.log_level,
                    5 => config.progress_bar_style,
                    _ => "unknown".to_string(),
                }
            },
            3 => { // Media config
                let config: MediaConfig = config_manager.get();
                match self.config_item_index {
                    0 => config.auto_load_subtitles.to_string(),
                    1 => config.subtitle_languages.join(","),
                    2 => config.audio_languages.join(","),
                    3 => config.hardware_decoding.to_string(),
                    4 => config.buffer_size_seconds.to_string(),
                    5 => config.skip_intro_seconds.map_or("None".to_string(), |s| s.to_string()),
                    6 => config.skip_outro_seconds.map_or("None".to_string(), |s| s.to_string()),
                    _ => "unknown".to_string(),
                }
            },
            4 => { // Advanced config
                let config: AdvancedConfig = config_manager.get();
                match self.config_item_index {
                    0 => config.debug_mode.to_string(),
                    1 => config.memory_limit_mb.map_or("None".to_string(), |m| format!("{}MB", m)),
                    2 => config.cpu_cores.map_or("Auto".to_string(), |c| c.to_string()),
                    3 => config.experimental_features.to_string(),
                    4 => config.custom_ffmpeg_args.join(" "),
                    5 => config.log_file_path.as_ref().map_or("None".to_string(), |p| p.display().to_string()),
                    6 => config.performance_monitoring.to_string(),
                    _ => "unknown".to_string(),
                }
            },
            5 => { // YouTube config
                let config: YoutubeConfig = config_manager.get();
                match self.config_item_index {
                    0 => config.enabled.to_string(),
                    1 => config.cache_directory.display().to_string(),
                    2 => config.max_cache_size_mb.to_string(),
                    3 => config.max_cache_age_days.to_string(),
                    4 => config.preferred_quality,
                    5 => config.audio_only.to_string(),
                    6 => config.ytdlp_path.as_ref().map_or("Auto".to_string(), |p| p.display().to_string()),
                    7 => config.concurrent_downloads.to_string(),
                    8 => config.retry_attempts.to_string(),
                    _ => "unknown".to_string(),
                }
            },
            _ => "unknown".to_string(),
        };

        self.config_edit_input = current_value.clone();
        self.config_editing = true;
        self.add_log("DEBUG", &format!("Started editing config value: {} (current: {})", 
                     self.config_edit_input, current_value));
        
        Ok(())
    }

    fn save_config_edit(&mut self) -> Result<()> {
        use crate::config_manager::ConfigManager;
        use crate::config::Config;
        use crate::config_modules::{NetworkConfig, AppearanceConfig, MediaConfig, AdvancedConfig, YoutubeConfig};

        let config_manager = ConfigManager::new()?;
        
        self.add_log("DEBUG", &format!("Saving config edit: section={}, item={}, value={}", 
                     self.config_section_index, self.config_item_index, self.config_edit_input));
        
        match self.config_section_index {
            0 => { // Player config
                let mut config: Config = config_manager.get();
                self.add_log("DEBUG", &format!("Before edit - volume: {}, speed: {}", 
                             config.default_volume, config.default_speed));
                match self.config_item_index {
                    0 => { // default_volume
                        if let Ok(value) = self.config_edit_input.parse::<f64>() {
                            if (0.0..=100.0).contains(&value) {
                                config.default_volume = value;
                                config_manager.set(config)?;
                                config_manager.sync()?; // Force immediate save
                                
                                // Verify the save worked
                                let saved_config: Config = config_manager.get();
                                self.add_log("DEBUG", &format!("After save - volume: {} (expected: {})", saved_config.default_volume, value));
                                
                                if (saved_config.default_volume - value).abs() < 0.001 {
                                    self.add_log("INFO", &format!("✓ Successfully updated default volume to: {}", value));
                                } else {
                                    self.add_log("ERROR", &format!("✗ Save failed! Expected: {}, Got: {}", value, saved_config.default_volume));
                                }
                            } else {
                                self.add_log("ERROR", "Volume must be between 0 and 100");
                            }
                        } else {
                            self.add_log("ERROR", "Invalid volume value");
                        }
                    },
                    1 => { // default_speed
                        if let Ok(value) = self.config_edit_input.parse::<f64>() {
                            if (0.1..=10.0).contains(&value) {
                                config.default_speed = value;
                                config_manager.set(config)?;
                                config_manager.sync()?; // Force immediate save
                                self.add_log("INFO", &format!("Updated default speed to: {}x", value));
                            } else {
                                self.add_log("ERROR", "Speed must be between 0.1 and 10.0");
                            }
                        } else {
                            self.add_log("ERROR", "Invalid speed value");
                        }
                    },
                    2 => { // fullscreen_by_default
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.fullscreen_by_default = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated fullscreen by default to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    3 => { // update_interval_ms
                        if let Ok(value) = self.config_edit_input.parse::<u64>() {
                            config.ui.update_interval_ms = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated update interval to: {}ms", value));
                        } else {
                            self.add_log("ERROR", "Invalid interval value");
                        }
                    },
                    4 => { // volume_step
                        if let Ok(value) = self.config_edit_input.parse::<f64>() {
                            if (0.1..=50.0).contains(&value) {
                                config.ui.volume_step = value;
                                config_manager.set(config)?;
                                self.add_log("INFO", &format!("Updated volume step to: {}", value));
                            } else {
                                self.add_log("ERROR", "Volume step must be between 0.1 and 50.0");
                            }
                        } else {
                            self.add_log("ERROR", "Invalid volume step value");
                        }
                    },
                    5 => { // seek_step
                        if let Ok(value) = self.config_edit_input.parse::<f64>() {
                            if (0.1..=300.0).contains(&value) {
                                config.ui.seek_step = value;
                                config_manager.set(config)?;
                                self.add_log("INFO", &format!("Updated seek step to: {}s", value));
                            } else {
                                self.add_log("ERROR", "Seek step must be between 0.1 and 300.0");
                            }
                        } else {
                            self.add_log("ERROR", "Invalid seek step value");
                        }
                    },
                    6 => { // speed_step
                        if let Ok(value) = self.config_edit_input.parse::<f64>() {
                            if (0.01..=1.0).contains(&value) {
                                config.ui.speed_step = value;
                                config_manager.set(config)?;
                                self.add_log("INFO", &format!("Updated speed step to: {}", value));
                            } else {
                                self.add_log("ERROR", "Speed step must be between 0.01 and 1.0");
                            }
                        } else {
                            self.add_log("ERROR", "Invalid speed step value");
                        }
                    },
                    7 => { // show_milliseconds
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.ui.show_milliseconds = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated show milliseconds to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    _ => self.add_log("ERROR", "Unknown config item"),
                }
            },
            1 => { // Network config
                let mut config: NetworkConfig = config_manager.get();
                match self.config_item_index {
                    0 => { // timeout_seconds
                        if let Ok(value) = self.config_edit_input.parse::<u64>() {
                            config.timeout_seconds = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated timeout to: {}s", value));
                        } else {
                            self.add_log("ERROR", "Invalid timeout value");
                        }
                    },
                    1 => { // retry_attempts
                        if let Ok(value) = self.config_edit_input.parse::<u32>() {
                            config.retry_attempts = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated retry attempts to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid retry attempts value");
                        }
                    },
                    2 => { // user_agent
                        config.user_agent = self.config_edit_input.clone();
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated user agent to: {}", self.config_edit_input));
                    },
                    3 => { // proxy_url
                        let proxy = if self.config_edit_input.trim().is_empty() || self.config_edit_input.trim().to_lowercase() == "none" {
                            None
                        } else {
                            Some(self.config_edit_input.clone())
                        };
                        config.proxy_url = proxy.clone();
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated proxy URL to: {:?}", proxy));
                    },
                    4 => { // max_redirects
                        if let Ok(value) = self.config_edit_input.parse::<u32>() {
                            config.max_redirects = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated max redirects to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid max redirects value");
                        }
                    },
                    _ => self.add_log("ERROR", "Unknown config item"),
                }
            },
            2 => { // Appearance config
                let mut config: AppearanceConfig = config_manager.get();
                match self.config_item_index {
                    0 => { // theme
                        config.theme = self.config_edit_input.clone();
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated theme to: {}", self.config_edit_input));
                    },
                    1 => { // font_size
                        if let Ok(value) = self.config_edit_input.parse::<u16>() {
                            config.font_size = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated font size to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid font size value");
                        }
                    },
                    2 => { // show_fps
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.show_fps = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated show FPS to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    3 => { // show_logs
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.show_logs = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated show logs to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    4 => { // log_level
                        config.log_level = self.config_edit_input.clone();
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated log level to: {}", self.config_edit_input));
                    },
                    5 => { // progress_bar_style
                        config.progress_bar_style = self.config_edit_input.clone();
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated progress bar style to: {}", self.config_edit_input));
                    },
                    _ => self.add_log("ERROR", "Unknown config item"),
                }
            },
            3 => { // Media config
                let mut config: MediaConfig = config_manager.get();
                match self.config_item_index {
                    0 => { // auto_load_subtitles
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.auto_load_subtitles = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated auto load subtitles to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    1 => { // subtitle_languages
                        let languages: Vec<String> = self.config_edit_input
                            .split(',')
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty())
                            .collect();
                        config.subtitle_languages = languages;
                        config_manager.set(config)?;
                        self.add_log("INFO", "Updated subtitle languages");
                    },
                    2 => { // audio_languages
                        let languages: Vec<String> = self.config_edit_input
                            .split(',')
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty())
                            .collect();
                        config.audio_languages = languages;
                        config_manager.set(config)?;
                        self.add_log("INFO", "Updated audio languages");
                    },
                    3 => { // hardware_decoding
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.hardware_decoding = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated hardware decoding to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    4 => { // buffer_size_seconds
                        if let Ok(value) = self.config_edit_input.parse::<f64>() {
                            config.buffer_size_seconds = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated buffer size to: {}s", value));
                        } else {
                            self.add_log("ERROR", "Invalid buffer size value");
                        }
                    },
                    5 => { // skip_intro_seconds
                        let skip_intro = if self.config_edit_input.trim().is_empty() || self.config_edit_input.trim().to_lowercase() == "none" {
                            None
                        } else if let Ok(value) = self.config_edit_input.parse::<f64>() {
                            Some(value)
                        } else {
                            self.add_log("ERROR", "Invalid skip intro value");
                            return Ok(());
                        };
                        config.skip_intro_seconds = skip_intro;
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated skip intro to: {:?}s", skip_intro));
                    },
                    6 => { // skip_outro_seconds
                        let skip_outro = if self.config_edit_input.trim().is_empty() || self.config_edit_input.trim().to_lowercase() == "none" {
                            None
                        } else if let Ok(value) = self.config_edit_input.parse::<f64>() {
                            Some(value)
                        } else {
                            self.add_log("ERROR", "Invalid skip outro value");
                            return Ok(());
                        };
                        config.skip_outro_seconds = skip_outro;
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated skip outro to: {:?}s", skip_outro));
                    },
                    _ => self.add_log("ERROR", "Unknown config item"),
                }
            },
            4 => { // Advanced config
                let mut config: AdvancedConfig = config_manager.get();
                match self.config_item_index {
                    0 => { // debug_mode
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.debug_mode = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated debug mode to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    1 => { // memory_limit_mb
                        let memory_limit = if self.config_edit_input.trim().is_empty() || self.config_edit_input.trim().to_lowercase() == "none" {
                            None
                        } else if let Ok(value) = self.config_edit_input.parse::<u64>() {
                            Some(value)
                        } else {
                            self.add_log("ERROR", "Invalid memory limit value");
                            return Ok(());
                        };
                        config.memory_limit_mb = memory_limit;
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated memory limit to: {:?}MB", memory_limit));
                    },
                    2 => { // cpu_cores
                        let cpu_cores = if self.config_edit_input.trim().is_empty() || self.config_edit_input.trim().to_lowercase() == "auto" {
                            None
                        } else if let Ok(value) = self.config_edit_input.parse::<u32>() {
                            Some(value)
                        } else {
                            self.add_log("ERROR", "Invalid CPU cores value");
                            return Ok(());
                        };
                        config.cpu_cores = cpu_cores;
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated CPU cores to: {:?}", cpu_cores));
                    },
                    3 => { // experimental_features
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.experimental_features = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated experimental features to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    4 => { // custom_ffmpeg_args
                        let args: Vec<String> = self.config_edit_input
                            .split_whitespace()
                            .map(|s| s.to_string())
                            .collect();
                        config.custom_ffmpeg_args = args;
                        config_manager.set(config)?;
                        self.add_log("INFO", "Updated custom FFmpeg args");
                    },
                    5 => { // log_file_path
                        let log_path = if self.config_edit_input.trim().is_empty() || self.config_edit_input.trim().to_lowercase() == "none" {
                            None
                        } else {
                            Some(PathBuf::from(self.config_edit_input.clone()))
                        };
                        config.log_file_path = log_path.clone();
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated log file path to: {:?}", log_path));
                    },
                    6 => { // performance_monitoring
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.performance_monitoring = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated performance monitoring to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    _ => self.add_log("ERROR", "Unknown config item"),
                }
            },
            5 => { // YouTube config
                let mut config: YoutubeConfig = config_manager.get();
                match self.config_item_index {
                    0 => { // enabled
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.enabled = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated YouTube enabled to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    1 => { // cache_directory
                        config.cache_directory = PathBuf::from(self.config_edit_input.clone());
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated cache directory to: {}", self.config_edit_input));
                    },
                    2 => { // max_cache_size_mb
                        if let Ok(value) = self.config_edit_input.parse::<u64>() {
                            config.max_cache_size_mb = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated max cache size to: {}MB", value));
                        } else {
                            self.add_log("ERROR", "Invalid cache size value");
                        }
                    },
                    3 => { // max_cache_age_days
                        if let Ok(value) = self.config_edit_input.parse::<u64>() {
                            config.max_cache_age_days = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated max cache age to: {} days", value));
                        } else {
                            self.add_log("ERROR", "Invalid cache age value");
                        }
                    },
                    4 => { // preferred_quality
                        config.preferred_quality = self.config_edit_input.clone();
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated preferred quality to: {}", self.config_edit_input));
                    },
                    5 => { // audio_only
                        if let Ok(value) = self.config_edit_input.parse::<bool>() {
                            config.audio_only = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated audio only to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid boolean value (use true or false)");
                        }
                    },
                    6 => { // ytdlp_path
                        let ytdlp_path = if self.config_edit_input.trim().is_empty() || self.config_edit_input.trim().to_lowercase() == "auto" {
                            None
                        } else {
                            Some(PathBuf::from(self.config_edit_input.clone()))
                        };
                        config.ytdlp_path = ytdlp_path.clone();
                        config_manager.set(config)?;
                        self.add_log("INFO", &format!("Updated yt-dlp path to: {:?}", ytdlp_path));
                    },
                    7 => { // concurrent_downloads
                        if let Ok(value) = self.config_edit_input.parse::<u32>() {
                            config.concurrent_downloads = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated concurrent downloads to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid concurrent downloads value");
                        }
                    },
                    8 => { // retry_attempts
                        if let Ok(value) = self.config_edit_input.parse::<u32>() {
                            config.retry_attempts = value;
                            config_manager.set(config)?;
                            self.add_log("INFO", &format!("Updated retry attempts to: {}", value));
                        } else {
                            self.add_log("ERROR", "Invalid retry attempts value");
                        }
                    },
                    _ => self.add_log("ERROR", "Unknown config item"),
                }
            },
            _ => {
                self.add_log("ERROR", "Editing for this config section is not yet implemented");
            }
        }

        Ok(())
    }

    fn reset_config_section(&mut self) -> Result<()> {
        use crate::config_manager::{ConfigManager, ConfigModule};
        use crate::config::Config;
        use crate::config_modules::{NetworkConfig, AppearanceConfig, MediaConfig, AdvancedConfig, YoutubeConfig};

        let config_manager = ConfigManager::new()?;
        
        match self.config_section_index {
            0 => { // Player config
                let default_config = <Config as ConfigModule>::default();
                config_manager.set(default_config)?;
                self.add_log("INFO", "Reset Player config to defaults");
            },
            1 => { // Network config
                let default_config = <NetworkConfig as ConfigModule>::default();
                config_manager.set(default_config)?;
                self.add_log("INFO", "Reset Network config to defaults");
            },
            2 => { // Appearance config
                let default_config = <AppearanceConfig as ConfigModule>::default();
                config_manager.set(default_config)?;
                self.add_log("INFO", "Reset Appearance config to defaults");
            },
            3 => { // Media config
                let default_config = <MediaConfig as ConfigModule>::default();
                config_manager.set(default_config)?;
                self.add_log("INFO", "Reset Media config to defaults");
            },
            4 => { // Advanced config
                let default_config = <AdvancedConfig as ConfigModule>::default();
                config_manager.set(default_config)?;
                self.add_log("INFO", "Reset Advanced config to defaults");
            },
            5 => { // YouTube config
                let default_config = <YoutubeConfig as ConfigModule>::default();
                config_manager.set(default_config)?;
                self.add_log("INFO", "Reset YouTube config to defaults");
            },
            _ => self.add_log("ERROR", "Unknown config section"),
        }

        Ok(())
    }
}

// Helper function to create a centered rect
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}

pub struct TuiManager;

impl TuiManager {
    pub fn setup() -> Result<Terminal<CrosstermBackend<io::Stdout>>> {
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
        let backend = CrosstermBackend::new(stdout);
        let terminal = Terminal::new(backend)?;
        Ok(terminal)
    }

    pub fn cleanup() -> Result<()> {
        disable_raw_mode()?;
        execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)?;
        Ok(())
    }
}