s8n 0.2.1

A beautiful unified system manager, package manager, and file manager TUI — built for Lilith Linux and Katie
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
//! S8n TUI — Full-screen Charm-style terminal interface
//!
//! Rendering strategy:
//! - GridTable (grid_table.rs): custom Buffer-writing widget with real Unicode box-drawing grid lines
//! - bubbletea_rs::gradient::gradient_filled_segment for animated gradient progress bars
//! - braille spinner frames + LGStyle coloring matching bubbletea-rs package-manager example
//! - ratatui for layout, input widgets, overlays

pub mod color_picker;
pub mod file_manager;
pub mod grid_table;
pub mod menu;
pub mod paginator;
pub mod tabs;
pub mod theme;

use crate::pm::{PackageInfo, PackageManager, PmResult};
use crossterm::{
    cursor,
    event::{self, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{self, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Style},
    text::{Line, Span, Text},
    widgets::{Block, Borders, Clear, List, ListItem, Paragraph, TableState, Wrap},
    Terminal,
};
use std::io::{self, stdout};
use std::time::Duration;

// lipgloss-style spinner colors

// ── App state ───────────────────────────────────────────────────────────────

/// Braille spinner — from the bubbletea-rs package-manager example
const SPINNER_FRAMES: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];

#[derive(Clone, PartialEq)]
pub enum AppMode {
    Menu,
    FileManager,
    ColorTheme,
    PackManSearch,
    PackManProgress,
}

#[derive(Clone, PartialEq)]
enum Mode {
    Input,         // typing search query
    Browse,        // navigating results with ↑↓
    Confirm,       // install/remove confirmation
    Progress,      // operation running
    Done,          // finished, press q to exit
    InstalledView, // viewing installed packages system-wide
}

struct App {
    mode: Mode,
    search_input: String,
    cursor_pos: usize,
    tick: u64, // animation tick

    // Results grouped by source
    results_by_source: Vec<(String, Vec<PackageInfo>)>,
    all_results: Vec<PackageInfo>,

    // Tab navigation
    tab_titles: Vec<String>,
    active_tab: usize,

    // List navigation
    list_state: TableState,
    page: usize,
    page_size: usize,

    // Source selector for highlighted package
    source_options: Vec<String>,
    source_selected: usize,

    // Confirm / progress
    confirm_action: String, // "install" or "remove"
    confirm_packages: Vec<String>,
    confirm_source: String,     // source manager for the confirmed action
    confirm_selected_yes: bool, // Tracks which button is highlighted
    progress_items: Vec<ProgressItem>,
    status_message: String,

    // Installed packages view
    installed_results: Vec<PackageInfo>,
    installed_loaded: bool,

    should_quit: bool,
}

#[derive(Clone)]
struct ProgressItem {
    name: String,
    done: bool,
    success: bool,
}

impl App {
    fn new() -> Self {
        Self {
            mode: Mode::Input,
            search_input: String::new(),
            cursor_pos: 0,
            tick: 0,
            results_by_source: Vec::new(),
            all_results: Vec::new(),
            tab_titles: vec!["All".into()],
            active_tab: 0,
            list_state: TableState::default(),
            page: 0,
            page_size: 20,
            source_options: Vec::new(),
            source_selected: 0,
            confirm_action: String::new(),
            confirm_packages: Vec::new(),
            confirm_source: String::new(),
            confirm_selected_yes: true,
            progress_items: Vec::new(),
            status_message: String::new(),
            installed_results: Vec::new(),
            installed_loaded: false,
            should_quit: false,
        }
    }

    fn current_results(&self) -> &[PackageInfo] {
        if self.active_tab == 0 {
            &self.all_results
        } else if let Some((_src, results)) = self.results_by_source.get(self.active_tab - 1) {
            results
        } else {
            &[]
        }
    }

    fn page_items(&self) -> Vec<(usize, &PackageInfo)> {
        let results = self.current_results();
        let start = self.page * self.page_size;
        results
            .iter()
            .enumerate()
            .skip(start)
            .take(self.page_size)
            .collect()
    }

    fn total_pages(&self) -> usize {
        let total = self.current_results().len();
        if total == 0 {
            1
        } else {
            total.div_ceil(self.page_size)
        }
    }

    fn selected_absolute_index(&self) -> Option<usize> {
        self.list_state
            .selected()
            .map(|rel| self.page * self.page_size + rel)
    }

    fn selected_package(&self) -> Option<&PackageInfo> {
        self.selected_absolute_index()
            .and_then(|idx| self.current_results().get(idx))
    }

    fn update_source_options(&mut self) {
        if let Some(pkg) = self.selected_package() {
            let name = &pkg.name;
            let sources: Vec<String> = self
                .all_results
                .iter()
                .filter(|p| p.name == *name)
                .map(|p| p.source.clone())
                .collect::<std::collections::HashSet<_>>()
                .into_iter()
                .collect();
            self.source_options = sources;
            self.source_selected = 0;
        } else {
            self.source_options.clear();
        }
    }

    fn set_results(&mut self, results_by_source: Vec<(String, Vec<PackageInfo>)>) {
        self.tab_titles = vec!["All".into()];
        self.all_results.clear();
        self.results_by_source.clear();

        for (source, pkgs) in results_by_source {
            self.tab_titles.push(format!("{} ({})", source, pkgs.len()));
            self.all_results.extend(pkgs.clone());
            self.results_by_source.push((source, pkgs));
        }

        self.active_tab = 0;
        self.page = 0;
        self.list_state.select(if self.all_results.is_empty() {
            None
        } else {
            Some(0)
        });
        self.update_source_options();
        self.mark_installed();
    }

    /// Mark search results as installed by cross-referencing with installed list
    fn mark_installed(&mut self) {
        if self.installed_results.is_empty() {
            return;
        }
        let installed_names: std::collections::HashSet<(String, String)> = self
            .installed_results
            .iter()
            .map(|p| (p.name.clone(), p.source.clone()))
            .collect();
        for pkg in &mut self.all_results {
            if installed_names.contains(&(pkg.name.clone(), pkg.source.clone())) {
                pkg.installed = true;
            }
        }
        for (_src, pkgs) in &mut self.results_by_source {
            for pkg in pkgs {
                if installed_names.contains(&(pkg.name.clone(), pkg.source.clone())) {
                    pkg.installed = true;
                }
            }
        }
    }
}

// ── Rendering ───────────────────────────────────────────────────────────────

fn render(terminal: &mut Terminal<CrosstermBackend<io::Stdout>>, app: &mut App) -> io::Result<()> {
    terminal.draw(|f| {
        let size = f.area();
        // Dark background
        f.render_widget(
            Block::default().style(Style::default().bg(theme::bg_color())),
            size,
        );

        match app.mode {
            Mode::Input | Mode::Browse => render_search_view(f, app, size),
            Mode::Confirm => {
                render_search_view(f, app, size);
                render_confirm_overlay(f, app, size);
            }
            Mode::Progress => render_progress_view(f, app, size),
            Mode::Done => render_done_view(f, app, size),
            Mode::InstalledView => render_installed_view(f, app, size),
        }
    })?;
    Ok(())
}

fn render_search_view(f: &mut ratatui::Frame, app: &mut App, area: Rect) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // tabs
            Constraint::Length(3), // search input
            Constraint::Min(5),    // results table
            Constraint::Length(1), // paginator
            Constraint::Length(1), // status bar
        ])
        .split(area);

    // ── Dynamic Tabs ──
    // If a multi-source package is highlighted, show source selection tabs
    // Otherwise show normal source filter tabs (or page tabs if navigating pages)
    let tab_mode = if app.mode == Mode::Browse && app.source_options.len() > 1 {
        let pkg_name = app
            .selected_package()
            .map(|p| p.name.as_str())
            .unwrap_or("");
        tabs::TabMode::PackageSources {
            sources: &app.source_options,
            selected: app.source_selected,
            pkg_name,
        }
    } else if app.total_pages() > 1 && app.mode == Mode::Browse {
        tabs::TabMode::Pages {
            current: app.page,
            total: app.total_pages(),
        }
    } else {
        tabs::TabMode::Sources {
            titles: &app.tab_titles,
            active: app.active_tab,
        }
    };
    f.render_widget(tabs::TabBar { mode: tab_mode }, chunks[0]);

    // ── Search input ──
    let input_block = Block::default()
        .borders(Borders::ALL)
        .border_style(if app.mode == Mode::Input {
            Style::default().fg(theme::hot_pink())
        } else {
            theme::border()
        })
        .title(Span::styled(" 🔍 Search ", theme::search_label()))
        .style(Style::default().bg(theme::bg_color()));

    let input_text = if app.search_input.is_empty() && app.mode != Mode::Input {
        Paragraph::new(Span::styled("Type to search packages...", theme::dim()))
    } else {
        let mut display = app.search_input.clone();
        if app.mode == Mode::Input {
            // Animated cursor: alternate between │ and ▏
            let cursor_char = if app.tick % 6 < 3 { '' } else { '' };
            display.insert(app.cursor_pos, cursor_char);
        }
        Paragraph::new(Span::styled(display, theme::input()))
    };
    f.render_widget(input_text.block(input_block), chunks[1]);

    // ── Searching spinner ──
    if !app.status_message.is_empty() {
        let spinner_frames = ["", "", "", "", "", "", "", "", "", ""];
        let frame = spinner_frames[(app.tick as usize) % spinner_frames.len()];
        let input_display_width: usize = app
            .search_input
            .chars()
            .map(|c| unicode_width::UnicodeWidthChar::width(c).unwrap_or(1))
            .sum();
        let spinner_text_width = 2 + 1 + app.status_message.chars().take(30).count();
        let available = chunks[1].width.saturating_sub(2) as usize;
        let text_w = input_display_width.min(available);
        let spinner_x = chunks[1].x + text_w as u16 + 1;
        if spinner_x + (spinner_text_width as u16) < chunks[1].x + chunks[1].width {
            let spinner_area = Rect::new(spinner_x, chunks[1].y + 1, spinner_text_width as u16, 1);
            f.render_widget(
                Paragraph::new(Span::styled(
                    format!(
                        "{} {}",
                        frame,
                        app.status_message.chars().take(30).collect::<String>()
                    ),
                    Style::default().fg(theme::hot_pink()),
                )),
                spinner_area,
            );
        }
    }

    // ── Package table via GridTable (writes Unicode grid lines directly to Buffer) ──
    app.page_size = (chunks[2].height as usize).saturating_sub(4).max(1);

    let items = app.page_items();
    let selected_rel = app.list_state.selected();

    let desc_col_max = (chunks[2].width as usize)
        .saturating_sub(5 + 26 + 14 + 12 + 6)
        .max(10);

    let grid_rows: Vec<grid_table::GridRow> = items
        .iter()
        .map(|(global_idx, pkg)| {
            let installed_badge = if pkg.installed { "" } else { "  " };
            let name_raw = format!("{}{}", installed_badge, pkg.name);
            let ver = if pkg.version.is_empty() {
                "".to_string()
            } else {
                pkg.version.chars().take(12).collect()
            };
            let src: String = pkg.source.chars().take(10).collect();
            let desc: String = pkg.description.chars().take(desc_col_max).collect();

            grid_table::GridRow {
                cells: vec![
                    grid_table::GridCell {
                        text: format!("{}", global_idx + 1),
                        style: theme::number(),
                    },
                    grid_table::GridCell {
                        text: name_raw,
                        style: if pkg.installed {
                            theme::installed_pkg()
                        } else {
                            theme::pkg_name()
                        },
                    },
                    grid_table::GridCell {
                        text: ver,
                        style: theme::version(),
                    },
                    grid_table::GridCell {
                        text: src,
                        style: theme::source_tag(),
                    },
                    grid_table::GridCell {
                        text: desc,
                        style: theme::desc(),
                    },
                ],
            }
        })
        .collect();

    let columns = [
        grid_table::Column {
            header: "#",
            width: Constraint::Length(5),
        },
        grid_table::Column {
            header: "Name",
            width: Constraint::Percentage(25),
        },
        grid_table::Column {
            header: "Version",
            width: Constraint::Length(14),
        },
        grid_table::Column {
            header: "Source",
            width: Constraint::Length(12),
        },
        grid_table::Column {
            header: "Description",
            width: Constraint::Min(10),
        },
    ];

    let result_count = app.current_results().len();
    // Render block title separately before the grid table
    f.render_widget(
        Block::default()
            .borders(Borders::NONE)
            .title(Span::styled(
                format!("{} packages ", result_count),
                theme::title(),
            ))
            .style(Style::default().bg(theme::bg_color())),
        chunks[2],
    );

    f.render_widget(
        grid_table::GridTable {
            columns: &columns,
            rows: &grid_rows,
            selected: selected_rel,
            header_style: theme::grid_header(),
            separator_style: theme::grid_separator(),
            selected_style: theme::highlight(),
        },
        chunks[2],
    );

    // ── Paginator ──
    f.render_widget(
        paginator::Paginator {
            current_page: app.page,
            total_pages: app.total_pages(),
            tick: app.tick,
        },
        chunks[3],
    );

    // ── Status / help bar ──
    let help = match app.mode {
        Mode::Input => " ↩ search • tab results • esc quit",
        Mode::Browse => {
            " ↑↓ navigate • ←→ source/page • tab filter • i install • d remove • v installed • / search • q quit"
        }
        _ => " q quit",
    };
    let status_line = Line::from(vec![
        Span::styled(" S8N ", theme::status_bar()),
        Span::styled(" ", Style::default()),
        Span::styled(help, theme::status_text()),
    ]);
    f.render_widget(Paragraph::new(status_line), chunks[4]);
}

fn render_confirm_overlay(f: &mut ratatui::Frame, app: &App, area: Rect) {
    let w = 55.min(area.width.saturating_sub(4));
    let h = 8.min(area.height.saturating_sub(2));
    let x = (area.width - w) / 2;
    let y = (area.height - h) / 2;
    let dialog = Rect::new(x, y, w, h);

    f.render_widget(Clear, dialog);

    let action = if app.confirm_action == "install" {
        "Install"
    } else {
        "Remove"
    };
    let pkgs = app.confirm_packages.join(", ");
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme::vivid_purple()))
        .title(Span::styled(
            format!(" {} Confirmation ", action),
            Style::default()
                .fg(theme::hot_pink())
                .add_modifier(ratatui::style::Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::overlay_color()));

    let yes_style = if app.confirm_selected_yes {
        theme::btn_yes()
    } else {
        theme::btn_dim()
    };

    let no_style = if !app.confirm_selected_yes {
        theme::btn_no()
    } else {
        theme::btn_dim()
    };

    let text = vec![
        Line::from(""),
        Line::from(Span::styled(
            format!(
                "  Are you sure you want to {} {}?",
                action.to_lowercase(),
                pkgs
            ),
            theme::pkg_name(),
        )),
        Line::from(""),
        Line::from(""),
        Line::from(vec![
            Span::styled("         ", Style::default()),
            Span::styled("  Yes  ", yes_style),
            Span::styled("   ", Style::default()),
            Span::styled(" Cancel ", no_style),
        ]),
    ];

    f.render_widget(
        Paragraph::new(text).block(block).wrap(Wrap { trim: true }),
        dialog,
    );
}

fn render_progress_view(f: &mut ratatui::Frame, app: &App, area: Rect) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // title
            Constraint::Min(3),    // items
            Constraint::Length(4), // gradient progress bar
        ])
        .split(area);

    // Title with braille spinner (theme-colored)
    let action_text = if app.confirm_action == "install" {
        "Installing"
    } else {
        "Removing"
    };
    let frame = SPINNER_FRAMES[(app.tick as usize) % SPINNER_FRAMES.len()];
    let spinner_str = format!(
        "\x1b[38;2;{};{};{}m{}\x1b[0m",
        match theme::vivid_purple() {
            Color::Rgb(r, _, _) => r,
            _ => 138,
        },
        match theme::vivid_purple() {
            Color::Rgb(_, g, _) => g,
            _ => 43,
        },
        match theme::vivid_purple() {
            Color::Rgb(_, _, b) => b,
            _ => 226,
        },
        frame
    );
    let title = Paragraph::new(Text::raw(format!(
        "  {} {} packages...",
        spinner_str, action_text
    )))
    .block(Block::default().style(Style::default().bg(theme::bg_color())));
    f.render_widget(title, chunks[0]);

    // Items list with per-item braille spinners (offset from main spinner)
    let items: Vec<ListItem> = app
        .progress_items
        .iter()
        .enumerate()
        .map(|(i, item)| {
            let vp = theme::vivid_purple();
            let _vp_r = match vp {
                Color::Rgb(r, _, _) => r,
                _ => 138,
            };
            let _vp_g = match vp {
                Color::Rgb(_, g, _) => g,
                _ => 43,
            };
            let _vp_b = match vp {
                Color::Rgb(_, _, b) => b,
                _ => 226,
            };

            let (icon, icon_style) = if item.done {
                if item.success {
                    let ng = theme::neon_green();
                    let style = Style::default().fg(ng);
                    ("", style)
                } else {
                    let br = theme::THEME.read().unwrap().bright_red;
                    let style = Style::default().fg(br);
                    ("", style)
                }
            } else {
                let spin = SPINNER_FRAMES[(app.tick as usize + i * 3) % SPINNER_FRAMES.len()];
                let style = Style::default().fg(vp);
                (spin, style)
            };

            let name_style = if item.done {
                theme::dim()
            } else {
                Style::default()
                    .fg(theme::hot_pink())
                    .add_modifier(ratatui::style::Modifier::BOLD)
            };

            let line = Line::from(vec![
                Span::styled(
                    if !item.done {
                        format!("  {} ", icon)
                    } else {
                        icon.to_string()
                    },
                    icon_style,
                ),
                Span::styled(item.name.clone(), name_style),
            ]);
            ListItem::new(line)
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme::border())
            .style(Style::default().bg(theme::bg_color())),
    );
    f.render_widget(list, chunks[1]);

    // Animated gradient progress bar using ratatui-native colored Spans
    let done_count = app.progress_items.iter().filter(|i| i.done).count();
    let total = app.progress_items.len().max(1);
    let ratio = done_count as f64 / total as f64;
    let bar_width = (chunks[2].width as usize).saturating_sub(4).min(80);
    let filled = (bar_width as f64 * ratio).round() as usize;
    let empty = bar_width.saturating_sub(filled);

    // Build gradient bar as a Line of colored Spans
    let gradient_colors = theme::gradient_stops();
    let color_count = gradient_colors.len();
    let phase = (app.tick as usize) % (color_count * 4);

    let mut spans: Vec<Span> = Vec::with_capacity(filled + empty + 4);
    spans.push(Span::raw("  "));

    for i in 0..filled {
        let color_idx = (phase + i * color_count / filled.max(1)) % color_count;
        let next_idx = (color_idx + 1) % color_count;
        let blend = ((i * color_count) % filled.max(1)) as f64 / filled.max(1) as f64;
        let c1 = gradient_colors[color_idx];
        let c2 = gradient_colors[next_idx];
        let color = match (c1, c2) {
            (Color::Rgb(r1, g1, b1), Color::Rgb(r2, g2, b2)) => {
                let b = blend.min(1.0);
                Color::Rgb(
                    (r1 as f64 * (1.0 - b) + r2 as f64 * b) as u8,
                    (g1 as f64 * (1.0 - b) + g2 as f64 * b) as u8,
                    (b1 as f64 * (1.0 - b) + b2 as f64 * b) as u8,
                )
            }
            _ => c1,
        };
        spans.push(Span::styled("", Style::default().fg(color)));
    }

    spans.push(Span::styled(
        "".repeat(empty),
        Style::default().fg(theme::THEME.read().unwrap().surface),
    ));
    spans.push(Span::raw(format!("  {}/{}", done_count, total)));

    let progress_line = Line::from(spans);
    f.render_widget(
        Paragraph::new(progress_line).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(theme::border())
                .title(Span::styled(" Progress ", theme::search_label()))
                .style(Style::default().bg(theme::bg_color())),
        ),
        chunks[2],
    );
}

fn render_done_view(f: &mut ratatui::Frame, app: &App, area: Rect) {
    render_progress_view(f, app, area);
    // Overlay done message in a lipgloss-style card
    let msg_w = 50.min(area.width.saturating_sub(4));
    let x = (area.width - msg_w) / 2;
    let y = area.height / 2;
    let msg_area = Rect::new(x, y, msg_w, 5);
    f.render_widget(Clear, msg_area);

    let success_count = app.progress_items.iter().filter(|i| i.success).count();
    let fail_count = app
        .progress_items
        .iter()
        .filter(|i| i.done && !i.success)
        .count();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme::neon_green()))
        .title(Span::styled(" Complete ", theme::success()))
        .style(Style::default().bg(theme::overlay_color()));
    let text = vec![
        Line::from(""),
        Line::from(vec![
            Span::styled(format!("{} succeeded", success_count), theme::success()),
            Span::styled("  ", Style::default()),
            if fail_count > 0 {
                Span::styled(format!("{} failed", fail_count), theme::error())
            } else {
                Span::styled("", Style::default())
            },
        ]),
        Line::from(Span::styled("  Press q to exit", theme::dim())),
    ];
    f.render_widget(Paragraph::new(text).block(block), msg_area);
}

fn render_installed_view(f: &mut ratatui::Frame, app: &mut App, area: Rect) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // title bar
            Constraint::Length(3), // search input
            Constraint::Min(5),    // results table
            Constraint::Length(1), // paginator
            Constraint::Length(1), // status bar
        ])
        .split(area);

    // Title bar
    f.render_widget(
        Block::default()
            .borders(Borders::NONE)
            .title(Span::styled(
                format!(" 📦 {} installed packages ", app.installed_results.len()),
                theme::title(),
            ))
            .style(Style::default().bg(theme::bg_color())),
        chunks[0],
    );

    // Search input
    let input_block = Block::default()
        .borders(Borders::ALL)
        .border_style(if app.mode == Mode::InstalledView {
            Style::default().fg(theme::hot_pink())
        } else {
            theme::border()
        })
        .title(Span::styled(" 🔍 Filter installed ", theme::search_label()))
        .style(Style::default().bg(theme::bg_color()));

    let input_text = if app.search_input.is_empty() {
        Paragraph::new(Span::styled(
            "Type to filter installed packages...",
            theme::dim(),
        ))
    } else {
        let mut display = app.search_input.clone();
        let cursor_char = if app.tick % 6 < 3 { '' } else { '' };
        display.insert(app.cursor_pos, cursor_char);
        Paragraph::new(Span::styled(display, theme::input()))
    };
    f.render_widget(input_text.block(input_block), chunks[1]);

    // Filtered results
    let filter = app.search_input.to_lowercase();
    let filtered: Vec<&PackageInfo> = app
        .installed_results
        .iter()
        .filter(|p| {
            filter.is_empty()
                || p.name.to_lowercase().contains(&filter)
                || p.source.to_lowercase().contains(&filter)
                || p.version.to_lowercase().contains(&filter)
        })
        .collect();

    app.page_size = (chunks[2].height as usize).saturating_sub(4).max(1);
    let total = filtered.len();
    let pages = if total == 0 {
        1
    } else {
        total.div_ceil(app.page_size)
    };
    let page = app.page.min(pages.saturating_sub(1));
    let start = page * app.page_size;
    let page_items: Vec<&PackageInfo> = filtered
        .iter()
        .skip(start)
        .take(app.page_size)
        .copied()
        .collect();

    let desc_col_max = (chunks[2].width as usize)
        .saturating_sub(5 + 26 + 14 + 12 + 6)
        .max(10);

    let grid_rows: Vec<grid_table::GridRow> = page_items
        .iter()
        .enumerate()
        .map(|(rel_idx, pkg)| {
            let global_idx = start + rel_idx;
            let installed_badge = "";
            let name_raw = format!("{}{}", installed_badge, pkg.name);
            let ver = if pkg.version.is_empty() {
                "".to_string()
            } else {
                pkg.version.chars().take(12).collect()
            };
            let src: String = pkg.source.chars().take(10).collect();
            let desc: String = pkg.description.chars().take(desc_col_max).collect();
            let is_selected = app.list_state.selected() == Some(rel_idx);

            grid_table::GridRow {
                cells: vec![
                    grid_table::GridCell {
                        text: format!("{}", global_idx + 1),
                        style: theme::number(),
                    },
                    grid_table::GridCell {
                        text: name_raw,
                        style: if is_selected {
                            theme::highlight()
                        } else {
                            theme::installed_pkg()
                        },
                    },
                    grid_table::GridCell {
                        text: ver,
                        style: theme::version(),
                    },
                    grid_table::GridCell {
                        text: src,
                        style: theme::source_tag(),
                    },
                    grid_table::GridCell {
                        text: desc,
                        style: theme::desc(),
                    },
                ],
            }
        })
        .collect();

    let columns = [
        grid_table::Column {
            header: "#",
            width: Constraint::Length(5),
        },
        grid_table::Column {
            header: "Name",
            width: Constraint::Percentage(25),
        },
        grid_table::Column {
            header: "Version",
            width: Constraint::Length(14),
        },
        grid_table::Column {
            header: "Source",
            width: Constraint::Length(12),
        },
        grid_table::Column {
            header: "Description",
            width: Constraint::Min(10),
        },
    ];

    f.render_widget(
        grid_table::GridTable {
            columns: &columns,
            rows: &grid_rows,
            selected: app.list_state.selected(),
            header_style: theme::grid_header(),
            separator_style: theme::grid_separator(),
            selected_style: theme::highlight(),
        },
        chunks[2],
    );

    // Paginator
    f.render_widget(
        paginator::Paginator {
            current_page: page,
            total_pages: pages,
            tick: app.tick,
        },
        chunks[3],
    );

    // Status bar
    let status_line = Line::from(vec![
        Span::styled(" INSTALLED ", theme::status_bar()),
        Span::styled(" ", Style::default()),
        Span::styled(
            " ↑↓ navigate • i install • d remove • / filter • Ctrl+F fuzzy • q back",
            theme::status_text(),
        ),
    ]);
    f.render_widget(Paragraph::new(status_line), chunks[4]);
}

// ── Event handling ──────────────────────────────────────────────────────────

fn handle_key(app: &mut App, key: KeyCode, modifiers: KeyModifiers) -> Option<Action> {
    match app.mode {
        Mode::Input => handle_input_key(app, key, modifiers),
        Mode::Browse => handle_browse_key(app, key, modifiers),
        Mode::Confirm => handle_confirm_key(app, key),
        Mode::Done => {
            if matches!(key, KeyCode::Char('q') | KeyCode::Esc) {
                app.should_quit = true;
            }
            None
        }
        Mode::Progress => None,
        Mode::InstalledView => handle_installed_key(app, key, modifiers),
    }
}

enum Action {
    Search(String),
    Install(Vec<String>, String), // packages, source
    Remove(Vec<String>, String),  // packages, source
    FuzzySearch,
    FuzzySearchInstalled,
    LoadInstalled,
}

fn handle_input_key(app: &mut App, key: KeyCode, _modifiers: KeyModifiers) -> Option<Action> {
    match key {
        KeyCode::Char('v') => {
            if !app.installed_loaded {
                return Some(Action::LoadInstalled);
            } else {
                app.mode = Mode::InstalledView;
                app.page = 0;
                app.list_state.select(if app.installed_results.is_empty() {
                    None
                } else {
                    Some(0)
                });
                app.search_input.clear();
                app.cursor_pos = 0;
            }
        }
        KeyCode::Char(c) => {
            app.search_input.insert(app.cursor_pos, c);
            app.cursor_pos += 1;
        }
        KeyCode::Backspace => {
            if app.cursor_pos > 0 {
                app.cursor_pos -= 1;
                app.search_input.remove(app.cursor_pos);
            }
        }
        KeyCode::Delete => {
            if app.cursor_pos < app.search_input.len() {
                app.search_input.remove(app.cursor_pos);
            }
        }
        KeyCode::Left => {
            app.cursor_pos = app.cursor_pos.saturating_sub(1);
        }
        KeyCode::Right => {
            app.cursor_pos = (app.cursor_pos + 1).min(app.search_input.len());
        }
        KeyCode::Home => app.cursor_pos = 0,
        KeyCode::End => app.cursor_pos = app.search_input.len(),
        KeyCode::Enter => {
            if !app.search_input.is_empty() {
                let query = app.search_input.clone();
                app.status_message = format!("Searching for '{}'...", query);
                return Some(Action::Search(query));
            }
        }
        KeyCode::Tab => {
            // Switch to browse mode if we have results
            if !app.all_results.is_empty() {
                app.mode = Mode::Browse;
                if app.list_state.selected().is_none() {
                    app.list_state.select(Some(0));
                    app.update_source_options();
                }
            }
        }
        KeyCode::Esc => app.should_quit = true,
        _ => {}
    }
    None
}

fn handle_browse_key(app: &mut App, key: KeyCode, modifiers: KeyModifiers) -> Option<Action> {
    if modifiers.contains(KeyModifiers::CONTROL) && key == KeyCode::Char('f') {
        return Some(Action::FuzzySearch);
    }
    let results_len = app.current_results().len();
    let page_start = app.page * app.page_size;
    let page_end = (page_start + app.page_size).min(results_len);
    let page_items = page_end - page_start;

    match key {
        KeyCode::Up => {
            if let Some(sel) = app.list_state.selected() {
                if sel > 0 {
                    app.list_state.select(Some(sel - 1));
                } else if app.page > 0 {
                    app.page -= 1;
                    let new_page_items = app.page_size.min(results_len - app.page * app.page_size);
                    app.list_state
                        .select(Some(new_page_items.saturating_sub(1)));
                }
            }
            app.update_source_options();
        }
        KeyCode::Down => {
            if let Some(sel) = app.list_state.selected() {
                if sel + 1 < page_items {
                    app.list_state.select(Some(sel + 1));
                } else if app.page + 1 < app.total_pages() {
                    app.page += 1;
                    app.list_state.select(Some(0));
                }
            }
            app.update_source_options();
        }
        KeyCode::Left => {
            if app.source_options.len() > 1 {
                app.source_selected = app.source_selected.saturating_sub(1);
            } else if app.page > 0 {
                app.page -= 1;
                app.list_state.select(Some(0));
                app.update_source_options();
            }
        }
        KeyCode::Right => {
            if app.source_options.len() > 1 {
                app.source_selected = (app.source_selected + 1).min(app.source_options.len() - 1);
            } else if app.page + 1 < app.total_pages() {
                app.page += 1;
                app.list_state.select(Some(0));
                app.update_source_options();
            }
        }
        KeyCode::Tab => {
            app.active_tab = (app.active_tab + 1) % app.tab_titles.len();
            app.page = 0;
            app.list_state.select(if app.current_results().is_empty() {
                None
            } else {
                Some(0)
            });
            app.update_source_options();
        }
        KeyCode::BackTab => {
            app.active_tab = if app.active_tab == 0 {
                app.tab_titles.len() - 1
            } else {
                app.active_tab - 1
            };
            app.page = 0;
            app.list_state.select(if app.current_results().is_empty() {
                None
            } else {
                Some(0)
            });
            app.update_source_options();
        }
        KeyCode::Char('i') | KeyCode::Enter => {
            if let Some(pkg) = app.selected_package() {
                if pkg.installed {
                    app.status_message = format!("{} is already installed", pkg.name);
                    return None;
                }
                let source = if app.source_options.len() > 1 {
                    app.source_options
                        .get(app.source_selected)
                        .cloned()
                        .unwrap_or_default()
                } else {
                    pkg.source.clone()
                };
                let pkg_name = pkg.name.clone();
                app.confirm_action = "install".to_string();
                app.confirm_packages = vec![pkg_name];
                app.confirm_source = source;
                app.confirm_selected_yes = true;
                app.mode = Mode::Confirm;
                return None;
            }
        }
        KeyCode::Char('d') | KeyCode::Char('r') => {
            if let Some(pkg) = app.selected_package() {
                let source = if app.source_options.len() > 1 {
                    app.source_options
                        .get(app.source_selected)
                        .cloned()
                        .unwrap_or_default()
                } else {
                    pkg.source.clone()
                };
                let pkg_name = pkg.name.clone();
                app.confirm_action = "remove".to_string();
                app.confirm_packages = vec![pkg_name];
                app.confirm_source = source;
                app.confirm_selected_yes = true;
                app.mode = Mode::Confirm;
            }
        }
        KeyCode::Char('/') => {
            app.mode = Mode::Input;
        }
        KeyCode::Char('v') => {
            if !app.installed_loaded {
                return Some(Action::LoadInstalled);
            } else {
                app.mode = Mode::InstalledView;
                app.page = 0;
                app.list_state.select(if app.installed_results.is_empty() {
                    None
                } else {
                    Some(0)
                });
                app.search_input.clear();
                app.cursor_pos = 0;
            }
        }
        KeyCode::Char('q') | KeyCode::Esc => {
            app.should_quit = true;
        }
        _ => {}
    }
    None
}

fn handle_confirm_key(app: &mut App, key: KeyCode) -> Option<Action> {
    let confirm_yes = || {
        let pkgs = app.confirm_packages.clone();
        let action = app.confirm_action.clone();
        let source = app.confirm_source.clone();

        let new_app_mode = Mode::Progress;
        let progress_items = pkgs
            .iter()
            .map(|p| ProgressItem {
                name: p.clone(),
                done: false,
                success: false,
            })
            .collect();

        if action == "install" {
            Some((new_app_mode, progress_items, Action::Install(pkgs, source)))
        } else {
            Some((new_app_mode, progress_items, Action::Remove(pkgs, source)))
        }
    };

    match key {
        KeyCode::Left | KeyCode::Right | KeyCode::Tab => {
            app.confirm_selected_yes = !app.confirm_selected_yes;
            None
        }
        KeyCode::Enter => {
            if app.confirm_selected_yes {
                if let Some((m, items, act)) = confirm_yes() {
                    app.mode = m;
                    app.progress_items = items;
                    return Some(act);
                }
                None
            } else {
                app.mode = Mode::Browse;
                None
            }
        }
        KeyCode::Char('y') | KeyCode::Char('Y') => {
            if let Some((m, items, act)) = confirm_yes() {
                app.mode = m;
                app.progress_items = items;
                return Some(act);
            }
            None
        }
        KeyCode::Char('n')
        | KeyCode::Char('N')
        | KeyCode::Char('c')
        | KeyCode::Char('C')
        | KeyCode::Char('b')
        | KeyCode::Char('B')
        | KeyCode::Esc => {
            app.mode = Mode::Browse;
            None
        }
        _ => None,
    }
}

fn handle_installed_key(app: &mut App, key: KeyCode, modifiers: KeyModifiers) -> Option<Action> {
    if modifiers.contains(KeyModifiers::CONTROL) && key == KeyCode::Char('f') {
        return Some(Action::FuzzySearchInstalled);
    }
    let _total = app.installed_results.len();
    let filter = app.search_input.to_lowercase();
    let filtered_count = app
        .installed_results
        .iter()
        .filter(|p| {
            filter.is_empty()
                || p.name.to_lowercase().contains(&filter)
                || p.source.to_lowercase().contains(&filter)
        })
        .count();
    let pages = if filtered_count == 0 {
        1
    } else {
        filtered_count.div_ceil(app.page_size)
    };

    match key {
        KeyCode::Up => {
            if let Some(sel) = app.list_state.selected() {
                if sel > 0 {
                    app.list_state.select(Some(sel - 1));
                } else if app.page > 0 {
                    app.page -= 1;
                    let new_page_items =
                        app.page_size.min(filtered_count - app.page * app.page_size);
                    app.list_state
                        .select(Some(new_page_items.saturating_sub(1)));
                }
            }
        }
        KeyCode::Down => {
            if let Some(sel) = app.list_state.selected() {
                if sel + 1 < app.page_size
                    && sel + 1 < filtered_count.saturating_sub(app.page * app.page_size)
                {
                    app.list_state.select(Some(sel + 1));
                } else if app.page + 1 < pages {
                    app.page += 1;
                    app.list_state.select(Some(0));
                }
            }
        }
        KeyCode::Char('i') | KeyCode::Enter => {
            // Install from installed list - find selected package
            let filter = app.search_input.to_lowercase();
            let filtered: Vec<&PackageInfo> = app
                .installed_results
                .iter()
                .filter(|p| {
                    filter.is_empty()
                        || p.name.to_lowercase().contains(&filter)
                        || p.source.to_lowercase().contains(&filter)
                })
                .collect();
            if let Some(sel) = app.list_state.selected() {
                let global_idx = app.page * app.page_size + sel;
                if let Some(pkg) = filtered.get(global_idx) {
                    // Check if already installed (it is, since this is the installed view)
                    // Show a popup informing the user
                    app.status_message = format!("{} is already installed", pkg.name);
                }
            }
        }
        KeyCode::Char('d') | KeyCode::Char('r') => {
            // Remove from installed list
            let filter = app.search_input.to_lowercase();
            let filtered: Vec<&PackageInfo> = app
                .installed_results
                .iter()
                .filter(|p| {
                    filter.is_empty()
                        || p.name.to_lowercase().contains(&filter)
                        || p.source.to_lowercase().contains(&filter)
                })
                .collect();
            if let Some(sel) = app.list_state.selected() {
                let global_idx = app.page * app.page_size + sel;
                if let Some(pkg) = filtered.get(global_idx) {
                    app.confirm_action = "remove".to_string();
                    app.confirm_packages = vec![pkg.name.clone()];
                    app.confirm_source = pkg.source.clone();
                    app.confirm_selected_yes = true;
                    app.mode = Mode::Confirm;
                }
            }
        }
        KeyCode::Char('/') => {
            app.mode = Mode::Input;
        }
        KeyCode::Char('q') | KeyCode::Esc => {
            app.mode = Mode::Browse;
        }
        _ => {}
    }
    None
}

// ── Public API ──────────────────────────────────────────────────────────────

/// Launch the full-screen search TUI (used by `s8n search` direct CLI)
pub async fn run_search_tui(
    managers: &[Box<dyn PackageManager>],
    initial_query: Option<&str>,
) -> io::Result<()> {
    // Load config theme
    theme::reload();

    // Setup terminal
    terminal::enable_raw_mode()?;
    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen, cursor::Hide)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    run_search_tui_inner(&mut terminal, managers, initial_query).await?;

    // Restore terminal
    terminal::disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen, cursor::Show)?;
    Ok(())
}

/// The inner loop of the search TUI (callable without taking over terminal setup)
pub async fn run_search_tui_inner(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    managers: &[Box<dyn PackageManager>],
    initial_query: Option<&str>,
) -> io::Result<()> {
    let mut app = App::new();

    // Pre-fill query if provided
    if let Some(q) = initial_query {
        app.search_input = q.to_string();
        app.cursor_pos = q.len();
        // Immediately search
        app.status_message = format!("Searching for '{}'...", q);
        let results = search_all(managers, q).await;
        app.set_results(results);
        app.mode = Mode::Browse;
        if app.list_state.selected().is_none() && !app.all_results.is_empty() {
            app.list_state.select(Some(0));
            app.update_source_options();
        }
        app.status_message.clear();
    }

    // Main loop
    loop {
        app.tick += 1;
        render(terminal, &mut app)?;

        if app.should_quit {
            break;
        }

        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key_event) = event::read()? {
                if let Some(action) = handle_key(&mut app, key_event.code, key_event.modifiers) {
                    match action {
                        Action::Search(query) => {
                            app.status_message = format!("Searching for '{}'...", query);
                            render(terminal, &mut app)?;
                            let results = search_all(managers, &query).await;
                            app.set_results(results);
                            app.mode = Mode::Browse;
                            if app.list_state.selected().is_none() && !app.all_results.is_empty() {
                                app.list_state.select(Some(0));
                                app.update_source_options();
                            }
                            app.status_message.clear();
                        }
                        Action::Install(pkgs, source) => {
                            render(terminal, &mut app)?;
                            // Find the right manager
                            let pm = managers
                                .iter()
                                .find(|m| m.name() == source)
                                .or_else(|| managers.first());
                            if let Some(pm) = pm {
                                for (i, pkg) in pkgs.iter().enumerate() {
                                    let result = pm.install(std::slice::from_ref(pkg)).await;
                                    if let Some(item) = app.progress_items.get_mut(i) {
                                        item.done = true;
                                        item.success = matches!(result, PmResult::Success);
                                    }
                                    render(terminal, &mut app)?;
                                }
                            }
                            app.mode = Mode::Done;
                        }
                        Action::Remove(pkgs, source) => {
                            render(terminal, &mut app)?;
                            let pm = managers
                                .iter()
                                .find(|m| m.name() == source)
                                .or_else(|| managers.first());
                            if let Some(pm) = pm {
                                for (i, pkg) in pkgs.iter().enumerate() {
                                    let result = pm.remove(std::slice::from_ref(pkg)).await;
                                    if let Some(item) = app.progress_items.get_mut(i) {
                                        item.done = true;
                                        item.success = matches!(result, PmResult::Success);
                                    }
                                    render(terminal, &mut app)?;
                                }
                            }
                            app.mode = Mode::Done;
                        }
                        Action::FuzzySearch => {
                            if app.all_results.is_empty() {
                                continue;
                            }
                            // Suspend TUI
                            terminal::disable_raw_mode()?;
                            execute!(terminal.backend_mut(), LeaveAlternateScreen, cursor::Show)?;

                            // Prepare items for Skim
                            use std::io::Write;
                            use std::process::{Command, Stdio};

                            let child_res = Command::new("sk")
                                .arg("--ansi")
                                .stdin(Stdio::piped())
                                .stdout(Stdio::piped())
                                .spawn();

                            match child_res {
                                Ok(mut child) => {
                                    let mut items_text = String::new();
                                    for pkg in &app.all_results {
                                        items_text
                                            .push_str(&format!("{} [{}]\n", pkg.name, pkg.source));
                                    }

                                    if let Some(mut stdin) = child.stdin.take() {
                                        let _ = stdin.write_all(items_text.as_bytes());
                                    }

                                    let output = child.wait_with_output().unwrap_or_else(|_| {
                                        std::process::Output {
                                            status: std::os::unix::process::ExitStatusExt::from_raw(
                                                1,
                                            ),
                                            stdout: Vec::new(),
                                            stderr: Vec::new(),
                                        }
                                    });

                                    // Restore TUI
                                    terminal::enable_raw_mode()?;
                                    execute!(
                                        terminal.backend_mut(),
                                        EnterAlternateScreen,
                                        cursor::Hide
                                    )?;
                                    terminal.clear()?;

                                    if output.status.success() {
                                        let selected = String::from_utf8_lossy(&output.stdout);
                                        let selected_line = selected.trim();
                                        if !selected_line.is_empty() {
                                            if let Some(idx) = selected_line.rfind(" [") {
                                                let name = &selected_line[..idx];
                                                let filtered: Vec<PackageInfo> = app
                                                    .all_results
                                                    .clone()
                                                    .into_iter()
                                                    .filter(|p| p.name == name)
                                                    .collect();
                                                if !filtered.is_empty() {
                                                    let mut map = std::collections::HashMap::new();
                                                    for p in filtered {
                                                        map.entry(p.source.clone())
                                                            .or_insert_with(Vec::new)
                                                            .push(p);
                                                    }
                                                    let mut new_results: Vec<(
                                                        String,
                                                        Vec<PackageInfo>,
                                                    )> = map.into_iter().collect();
                                                    new_results.sort_by(|a, b| a.0.cmp(&b.0));
                                                    app.set_results(new_results);
                                                }
                                            }
                                        }
                                    }
                                }
                                Err(_) => {
                                    // Restore TUI and show error
                                    terminal::enable_raw_mode()?;
                                    execute!(
                                        terminal.backend_mut(),
                                        EnterAlternateScreen,
                                        cursor::Hide
                                    )?;
                                    terminal.clear()?;
                                    app.status_message =
                                        "Error: Skim (sk) fuzzy finder is not installed."
                                            .to_string();
                                }
                            }
                        }
                        Action::FuzzySearchInstalled => {
                            if app.installed_results.is_empty() {
                                continue;
                            }
                            // Suspend TUI
                            terminal::disable_raw_mode()?;
                            execute!(terminal.backend_mut(), LeaveAlternateScreen, cursor::Show)?;

                            use std::io::Write;
                            use std::process::{Command, Stdio};

                            let child_res = Command::new("sk")
                                .arg("--ansi")
                                .stdin(Stdio::piped())
                                .stdout(Stdio::piped())
                                .spawn();

                            match child_res {
                                Ok(mut child) => {
                                    let mut items_text = String::new();
                                    for pkg in &app.installed_results {
                                        items_text.push_str(&format!(
                                            "{} [{}] {}\n",
                                            pkg.name, pkg.source, pkg.version
                                        ));
                                    }

                                    if let Some(mut stdin) = child.stdin.take() {
                                        let _ = stdin.write_all(items_text.as_bytes());
                                    }

                                    let output = child.wait_with_output().unwrap_or_else(|_| {
                                        std::process::Output {
                                            status: std::os::unix::process::ExitStatusExt::from_raw(
                                                1,
                                            ),
                                            stdout: Vec::new(),
                                            stderr: Vec::new(),
                                        }
                                    });

                                    // Restore TUI
                                    terminal::enable_raw_mode()?;
                                    execute!(
                                        terminal.backend_mut(),
                                        EnterAlternateScreen,
                                        cursor::Hide
                                    )?;
                                    terminal.clear()?;

                                    if output.status.success() {
                                        let selected = String::from_utf8_lossy(&output.stdout);
                                        let selected_line = selected.trim();
                                        if !selected_line.is_empty() {
                                            if let Some(idx) = selected_line.rfind(" [") {
                                                let name = &selected_line[..idx];
                                                let filtered: Vec<&PackageInfo> = app
                                                    .installed_results
                                                    .iter()
                                                    .filter(|p| p.name == name)
                                                    .collect();
                                                if !filtered.is_empty() {
                                                    app.search_input = name.to_string();
                                                    app.cursor_pos = name.len();
                                                }
                                            }
                                        }
                                    }
                                }
                                Err(_) => {
                                    terminal::enable_raw_mode()?;
                                    execute!(
                                        terminal.backend_mut(),
                                        EnterAlternateScreen,
                                        cursor::Hide
                                    )?;
                                    terminal.clear()?;
                                    app.status_message =
                                        "Error: Skim (sk) fuzzy finder is not installed."
                                            .to_string();
                                }
                            }
                        }
                        Action::LoadInstalled => {
                            app.status_message = "Loading installed packages...".to_string();
                            render(terminal, &mut app)?;
                            let mut all_installed: Vec<PackageInfo> = Vec::new();
                            for pm in managers {
                                if !pm.is_available() {
                                    continue;
                                }
                                if let Ok(pkgs) = pm.list_installed().await {
                                    all_installed.extend(pkgs);
                                }
                            }
                            all_installed.sort_by_key(|a| a.name.to_lowercase());
                            app.installed_results = all_installed;
                            app.installed_loaded = true;
                            app.mark_installed();
                            app.mode = Mode::InstalledView;
                            app.page = 0;
                            app.list_state.select(if app.installed_results.is_empty() {
                                None
                            } else {
                                Some(0)
                            });
                            app.search_input.clear();
                            app.cursor_pos = 0;
                            app.status_message.clear();
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

/// The unified application loop for `s8n` CLI command without subcommands
pub async fn run_main_tui(
    managers: Vec<Box<dyn PackageManager>>,
    requested_manager: Option<&str>,
) -> io::Result<()> {
    // Load config theme
    theme::reload();

    // Setup terminal
    terminal::enable_raw_mode()?;
    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen, cursor::Hide)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut current_mode = AppMode::Menu;
    let mut menu_state = menu::MenuState::new();
    let mut fm_state = file_manager::FileManagerState::new();
    let mut cp_state = color_picker::ColorPickerState::new();

    let search_managers: Vec<Box<dyn PackageManager>> = if let Some(requested) = requested_manager {
        managers
            .into_iter()
            .filter(|m| m.name() == requested)
            .collect()
    } else {
        managers
    };

    loop {
        match current_mode {
            AppMode::Menu => {
                terminal.draw(|f| {
                    let size = f.area();
                    f.render_widget(
                        ratatui::widgets::Block::default()
                            .style(ratatui::style::Style::default().bg(theme::bg_color())),
                        size,
                    );
                    menu::render_menu(f, &mut menu_state, size);
                })?;

                if event::poll(Duration::from_millis(100))? {
                    if let Event::Key(key) = event::read()? {
                        if let Some(action) = menu_state.handle_key(key.code) {
                            match action {
                                menu::MenuAction::PackMan => current_mode = AppMode::PackManSearch,
                                menu::MenuAction::FileManager => {
                                    current_mode = AppMode::FileManager
                                }
                                menu::MenuAction::ColorTheme => current_mode = AppMode::ColorTheme,
                                menu::MenuAction::Quit => break,
                            }
                        }
                    }
                }
            }
            AppMode::FileManager => {
                terminal.draw(|f| {
                    let size = f.area();
                    f.render_widget(
                        ratatui::widgets::Block::default()
                            .style(ratatui::style::Style::default().bg(theme::bg_color())),
                        size,
                    );
                    file_manager::render_file_manager(f, &mut fm_state, size);
                })?;

                if event::poll(Duration::from_millis(100))? {
                    if let Event::Key(key) = event::read()? {
                        if fm_state.handle_key(key.code) {
                            current_mode = AppMode::Menu;
                        }
                    }
                }
            }
            AppMode::ColorTheme => {
                terminal.draw(|f| {
                    let size = f.area();
                    f.render_widget(
                        ratatui::widgets::Block::default()
                            .style(ratatui::style::Style::default().bg(theme::bg_color())),
                        size,
                    );
                    color_picker::render_color_picker(f, &mut cp_state, size);
                })?;

                if event::poll(Duration::from_millis(100))? {
                    if let Event::Key(key) = event::read()? {
                        if cp_state.handle_key(key.code) {
                            current_mode = AppMode::Menu;
                        }
                    }
                }
            }
            AppMode::PackManSearch => {
                // Hand off terminal control entirely to the search sub-app
                run_search_tui_inner(&mut terminal, &search_managers, None).await?;
                // Once it returns (user pressed q or Esc), go back to main menu
                current_mode = AppMode::Menu;
            }
            _ => {
                // Return to menu as fallback
                current_mode = AppMode::Menu;
            }
        }
    }

    // Restore terminal
    terminal::disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen, cursor::Show)?;
    Ok(())
}

/// Launch inline progress TUI for install/remove/update (non-search operations)
pub async fn run_progress_tui(
    pm: &dyn PackageManager,
    packages: Vec<String>,
    action: &str, // "install", "remove", "update"
) -> io::Result<()> {
    terminal::enable_raw_mode()?;
    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen, cursor::Hide)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let items: Vec<String> = if action == "update" && packages.is_empty() {
        vec!["System Packages".to_string()]
    } else {
        packages.clone()
    };

    let mut app = App::new();
    app.confirm_action = action.to_string();
    app.mode = Mode::Progress;
    app.progress_items = items
        .iter()
        .map(|p| ProgressItem {
            name: p.clone(),
            done: false,
            success: false,
        })
        .collect();

    render(&mut terminal, &mut app)?;

    for (i, pkg) in items.iter().enumerate() {
        let result = match action {
            "install" => pm.install(std::slice::from_ref(pkg)).await,
            "remove" => pm.remove(std::slice::from_ref(pkg)).await,
            "update" => pm.update().await,
            _ => PmResult::Error("Unknown action".into()),
        };
        if let Some(item) = app.progress_items.get_mut(i) {
            item.done = true;
            item.success = matches!(result, PmResult::Success);
        }
        render(&mut terminal, &mut app)?;
    }

    app.mode = Mode::Done;
    render(&mut terminal, &mut app)?;

    // Wait for quit
    loop {
        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key_event) = event::read()? {
                if matches!(
                    key_event.code,
                    KeyCode::Char('q') | KeyCode::Esc | KeyCode::Enter
                ) {
                    break;
                }
            }
        }
    }

    terminal::disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen, cursor::Show)?;
    Ok(())
}

/// Search all available managers concurrently and collect results
/// Search all available managers concurrently and collect results
async fn search_all(
    managers: &[Box<dyn PackageManager>],
    query: &str,
) -> Vec<(String, Vec<PackageInfo>)> {
    let mut results: std::collections::HashMap<String, Vec<PackageInfo>> =
        std::collections::HashMap::new();
    let terms: Vec<&str> = query
        .split(',')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .collect();

    // Search sequentially to avoid overwhelming the terminal
    for pm in managers {
        if !pm.is_available() || matches!(pm.name(), "topgrade" | "bun") {
            continue;
        }
        for term in &terms {
            if let Ok(pkgs) = pm.search_captured(term).await {
                if !pkgs.is_empty() {
                    results
                        .entry(pm.name().to_string())
                        .or_default()
                        .extend(pkgs);
                }
            }
        }
    }

    // Convert hashmap back to vec and sort
    let mut final_results: Vec<(String, Vec<PackageInfo>)> = results.into_iter().collect();
    final_results.sort_by(|a, b| a.0.cmp(&b.0));
    final_results
}