twig-tmux 0.1.3

Tmux session manager with git worktree support
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
//! Interactive tree view for projects and worktrees using Ratatui.

use std::env;
use std::io::{self, stdout, IsTerminal};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use crossterm::ExecutableCommand;
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use ratatui::prelude::*;
use ratatui::widgets::{Block, BorderType, Borders, Paragraph};
use tui_tree_widget::{Tree, TreeItem, TreeState};

use crate::config::Project;
use crate::git::{self, WorktreeInfo};
use crate::tmux::{self, SessionBuilder};

/// Current session context from environment
struct CurrentContext {
    project: Option<String>,
    worktree: Option<String>,
}

impl CurrentContext {
    fn from_env() -> Self {
        Self {
            project: env::var("TWIG_PROJECT").ok(),
            worktree: env::var("TWIG_WORKTREE").ok(),
        }
    }

    fn is_current_project(&self, name: &str) -> bool {
        self.project.as_deref() == Some(name) && self.worktree.is_none()
    }

    fn is_current_worktree(&self, project: &str, branch: &str) -> bool {
        self.project.as_deref() == Some(project) && self.worktree.as_deref() == Some(branch)
    }
}

/// Unique identifier for tree nodes
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum TreeNodeId {
    #[default]
    Root,
    Project(String),
    Worktree {
        project: String,
        branch: String,
    },
}

/// Action to perform after tree view exits
#[derive(Debug, Clone)]
pub enum SelectedAction {
    StartProject(String),
    StartWorktree { project: String, branch: String },
    KillProject(String),
    KillWorktree { project: String, branch: String },
}

/// Search candidate for fuzzy matching
struct SearchCandidate {
    /// Searchable text (e.g., "project / branch")
    label: String,
    /// Full path to this node in the tree
    node_path: Vec<TreeNodeId>,
    /// Parent project name (for opening parent when searching)
    project: String,
}

/// Data for a project and its worktrees
struct ProjectData {
    name: String,
    worktrees: Vec<WorktreeInfo>,
    session_running: bool,
}

/// Mode for the tree view
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TreeViewMode {
    /// Normal mode: show all projects/worktrees, start sessions on select
    Start,
    /// Kill mode: show only running sessions, kill on select
    Kill,
}

/// Status message to display in the tree view
#[derive(Debug, Clone)]
struct StatusMessage {
    text: String,
    is_error: bool,
    timestamp: Instant,
}

struct BusyState {
    message: String,
    spinner_index: usize,
    last_tick: Instant,
    receiver: mpsc::Receiver<BusyResult>,
}

enum BusyResult {
    Ready(String),
    Error(String),
}

impl StatusMessage {
    fn info(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            is_error: false,
            timestamp: Instant::now(),
        }
    }

    fn error(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            is_error: true,
            timestamp: Instant::now(),
        }
    }

    fn is_expired(&self) -> bool {
        self.timestamp.elapsed() > Duration::from_secs(3)
    }
}

/// App state for the tree view
struct TreeViewApp<'a> {
    tree_items: Vec<TreeItem<'a, TreeNodeId>>,
    tree_state: TreeState<TreeNodeId>,
    candidates: Vec<SearchCandidate>,
    query: String,
    no_match: bool,
    search_mode: bool,
    mode: TreeViewMode,
    status_message: Option<StatusMessage>,
    /// Session to switch to after exiting (when current session was deleted)
    switch_to_session: Option<String>,
    busy: Option<BusyState>,
}

impl<'a> TreeViewApp<'a> {
    fn new(
        projects: Vec<ProjectData>,
        running_sessions: &[String],
        mode: TreeViewMode,
        current: &CurrentContext,
        focus_current: bool,
    ) -> Result<Self> {
        let tree_items = build_tree_items(&projects, running_sessions, current)?;
        let candidates = build_candidates(&projects);

        let mut tree_state = TreeState::default();

        // Open all projects by default and select first item
        for project in &projects {
            tree_state.open(vec![TreeNodeId::Project(project.name.clone())]);
        }
        if focus_current {
            let mut selected = None;

            if let Some(project_name) = current.project.as_deref() {
                let has_project = projects.iter().any(|project| project.name == project_name);

                if has_project {
                    if let Some(branch) = current.worktree.as_deref() {
                        let has_worktree = projects.iter().any(|project| {
                            project.name == project_name
                                && project.worktrees.iter().any(|wt| wt.branch == branch)
                        });

                        if has_worktree {
                            selected = Some(vec![
                                TreeNodeId::Project(project_name.to_string()),
                                TreeNodeId::Worktree {
                                    project: project_name.to_string(),
                                    branch: branch.to_string(),
                                },
                            ]);
                        }
                    }

                    if selected.is_none() {
                        selected = Some(vec![TreeNodeId::Project(project_name.to_string())]);
                    }
                }
            }

            if let Some(node_path) = selected {
                tree_state.select(node_path);
                tree_state.scroll_selected_into_view();
            } else if !projects.is_empty() {
                tree_state.select(vec![TreeNodeId::Project(projects[0].name.clone())]);
            }
        } else if !projects.is_empty() {
            tree_state.select(vec![TreeNodeId::Project(projects[0].name.clone())]);
        }

        Ok(Self {
            tree_items,
            tree_state,
            candidates,
            query: String::new(),
            search_mode: false,
            no_match: false,
            mode,
            status_message: None,
            switch_to_session: None,
            busy: None,
        })
    }

    /// Refresh tree data (after worktree operations)
    fn refresh(&mut self, select_project: Option<&str>) -> Result<()> {
        let running_sessions = tmux::list_sessions().unwrap_or_default();
        let current = CurrentContext::from_env();

        // Reload all project data
        let opts = LoadOptions {
            project_filter: None,
            running_only: self.mode == TreeViewMode::Kill,
            include_worktrees: true,
        };
        let projects = load_project_data(opts)?;

        self.tree_items = build_tree_items(&projects, &running_sessions, &current)?;
        self.candidates = build_candidates(&projects);

        // Re-open all projects
        for project in &projects {
            self.tree_state
                .open(vec![TreeNodeId::Project(project.name.clone())]);
        }

        // Select the specified project or first item
        if let Some(project_name) = select_project {
            self.tree_state
                .select(vec![TreeNodeId::Project(project_name.to_string())]);
        } else if !projects.is_empty() {
            self.tree_state
                .select(vec![TreeNodeId::Project(projects[0].name.clone())]);
        }

        Ok(())
    }

    fn handle_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> Option<HandleResult> {
        if self.busy.is_some() {
            return None;
        }

        // Search mode handling
        if self.search_mode {
            return self.handle_search_key(code, modifiers);
        }

        match code {
            // Quit
            KeyCode::Char('q') | KeyCode::Esc => {
                return Some(HandleResult::Quit);
            }
            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
                return Some(HandleResult::Quit);
            }

            // Enter search mode
            KeyCode::Char('/') => {
                self.search_mode = true;
                self.query.clear();
                self.no_match = false;
            }

            // Stop/Kill session
            KeyCode::Char('s') | KeyCode::Char('S') => {
                if let Some(action) = self.get_selected_action() {
                    let kill_action = match action {
                        SelectedAction::StartProject(name) | SelectedAction::KillProject(name) => {
                            SelectedAction::KillProject(name)
                        }
                        SelectedAction::StartWorktree { project, branch }
                        | SelectedAction::KillWorktree { project, branch } => {
                            SelectedAction::KillWorktree { project, branch }
                        }
                    };
                    return Some(HandleResult::KillSession(kill_action));
                }
            }

            // Fork worktree
            KeyCode::Char('f') | KeyCode::Char('F') => {
                if let Some(project) = self.get_selected_project() {
                    return Some(HandleResult::ForkWorktree(project));
                }
            }

            // Merge worktree (only on worktree nodes)
            KeyCode::Char('m') | KeyCode::Char('M') => {
                if let Some((project, branch)) = self.get_selected_worktree() {
                    return Some(HandleResult::MergeWorktree { project, branch });
                }
            }

            // Delete worktree (only on worktree nodes)
            KeyCode::Char('d') | KeyCode::Char('D') => {
                if let Some((project, branch)) = self.get_selected_worktree() {
                    return Some(HandleResult::DeleteWorktree { project, branch });
                }
            }

            // Navigation
            KeyCode::Up | KeyCode::Char('k') => {
                self.tree_state.key_up();
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.tree_state.key_down();
            }
            KeyCode::Char('p') if modifiers.contains(KeyModifiers::CONTROL) => {
                self.tree_state.key_up();
            }
            KeyCode::Char('n') if modifiers.contains(KeyModifiers::CONTROL) => {
                self.tree_state.key_down();
            }
            KeyCode::Left | KeyCode::Char('h') => {
                self.tree_state.key_left();
            }
            KeyCode::Right | KeyCode::Char('l') => {
                self.tree_state.key_right();
            }

            // Selection
            KeyCode::Enter => {
                if let Some(action) = self.get_selected_action() {
                    if self.mode == TreeViewMode::Start {
                        self.begin_start_session(action);
                        return None;
                    }
                    return Some(HandleResult::Action(action));
                }
            }

            _ => {}
        }
        None
    }

    fn begin_start_session(&mut self, action: SelectedAction) {
        let message = match &action {
            SelectedAction::StartProject(name) => format!("Starting '{}'...", name),
            SelectedAction::StartWorktree { project, branch } => {
                format!("Starting '{}:{}'...", project, branch)
            }
            _ => return,
        };

        let (tx, rx) = mpsc::channel();

        self.search_mode = false;
        self.query.clear();
        self.no_match = false;
        self.busy = Some(BusyState {
            message,
            spinner_index: 0,
            last_tick: Instant::now(),
            receiver: rx,
        });

        thread::spawn(move || {
            let result = start_session_for_action(action).map_err(|err| err.to_string());
            let _ = match result {
                Ok(session) => tx.send(BusyResult::Ready(session)),
                Err(message) => tx.send(BusyResult::Error(message)),
            };
        });
    }

    fn tick_busy(&mut self) {
        let Some(ref mut busy) = self.busy else {
            return;
        };

        if busy.last_tick.elapsed() >= Duration::from_millis(120) {
            busy.spinner_index = (busy.spinner_index + 1) % SPINNER_FRAMES.len();
            busy.last_tick = Instant::now();
        }
    }

    fn poll_busy(&mut self) -> Option<BusyResult> {
        let busy = self.busy.as_ref()?;
        busy.receiver.try_recv().ok()
    }

    fn handle_search_key(
        &mut self,
        code: KeyCode,
        modifiers: KeyModifiers,
    ) -> Option<HandleResult> {
        match code {
            // Exit search mode (keep cursor position)
            KeyCode::Esc => {
                self.search_mode = false;
                self.query.clear();
                self.no_match = false;
            }
            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
                self.search_mode = false;
                self.query.clear();
                self.no_match = false;
            }

            // Confirm search and trigger selection action
            KeyCode::Enter => {
                if let Some(action) = self.get_selected_action() {
                    self.search_mode = false;
                    self.query.clear();
                    self.no_match = false;
                    return Some(HandleResult::Action(action));
                }
            }

            // Search input
            KeyCode::Backspace => {
                self.query.pop();
                if self.query.is_empty() {
                    self.no_match = false;
                } else {
                    self.do_fuzzy_search();
                }
            }
            KeyCode::Char(c) if !modifiers.contains(KeyModifiers::CONTROL) => {
                self.query.push(c);
                self.do_fuzzy_search();
            }

            // Allow navigation while searching
            KeyCode::Up => {
                self.tree_state.key_up();
            }
            KeyCode::Down => {
                self.tree_state.key_down();
            }
            KeyCode::Char('p') if modifiers.contains(KeyModifiers::CONTROL) => {
                self.tree_state.key_up();
            }
            KeyCode::Char('n') if modifiers.contains(KeyModifiers::CONTROL) => {
                self.tree_state.key_down();
            }

            _ => {}
        }
        None
    }

    fn do_fuzzy_search(&mut self) {
        if self.query.is_empty() {
            self.no_match = false;
            return;
        }

        let matcher = SkimMatcherV2::default();
        let mut best_match: Option<(&SearchCandidate, i64)> = None;

        for candidate in &self.candidates {
            if let Some(score) = matcher.fuzzy_match(&candidate.label, &self.query) {
                match &best_match {
                    None => best_match = Some((candidate, score)),
                    Some((_, best_score)) if score > *best_score => {
                        best_match = Some((candidate, score));
                    }
                    _ => {}
                }
            }
        }

        if let Some((candidate, _)) = best_match {
            self.no_match = false;
            // Ensure parent project is open
            self.tree_state
                .open(vec![TreeNodeId::Project(candidate.project.clone())]);
            // Select the matched node
            self.tree_state.select(candidate.node_path.clone());
            self.tree_state.scroll_selected_into_view();
        } else {
            self.no_match = true;
        }
    }

    fn get_selected_action(&self) -> Option<SelectedAction> {
        let selected = self.tree_state.selected();
        if selected.is_empty() {
            return None;
        }

        match &selected[selected.len() - 1] {
            TreeNodeId::Root => None,
            TreeNodeId::Project(name) => match self.mode {
                TreeViewMode::Start => Some(SelectedAction::StartProject(name.clone())),
                TreeViewMode::Kill => Some(SelectedAction::KillProject(name.clone())),
            },
            TreeNodeId::Worktree { project, branch } => match self.mode {
                TreeViewMode::Start => Some(SelectedAction::StartWorktree {
                    project: project.clone(),
                    branch: branch.clone(),
                }),
                TreeViewMode::Kill => Some(SelectedAction::KillWorktree {
                    project: project.clone(),
                    branch: branch.clone(),
                }),
            },
        }
    }

    /// Get the project name from the current selection (works for both project and worktree nodes)
    fn get_selected_project(&self) -> Option<String> {
        let selected = self.tree_state.selected();
        if selected.is_empty() {
            return None;
        }

        match &selected[selected.len() - 1] {
            TreeNodeId::Root => None,
            TreeNodeId::Project(name) => Some(name.clone()),
            TreeNodeId::Worktree { project, .. } => Some(project.clone()),
        }
    }

    /// Get worktree info if current selection is a worktree
    fn get_selected_worktree(&self) -> Option<(String, String)> {
        let selected = self.tree_state.selected();
        if selected.is_empty() {
            return None;
        }

        match &selected[selected.len() - 1] {
            TreeNodeId::Worktree { project, branch } => Some((project.clone(), branch.clone())),
            _ => None,
        }
    }

    /// Check if current selection is a worktree
    fn is_worktree_selected(&self) -> bool {
        self.get_selected_worktree().is_some()
    }

    fn build_default_status_line(&self) -> Line<'static> {
        let separator_color = match self.mode {
            TreeViewMode::Start => Color::LightMagenta,
            TreeViewMode::Kill => Color::LightRed,
        };
        let is_worktree = self.is_worktree_selected();

        let mut spans = vec![
            Span::styled("j/k", Style::default().fg(Color::LightCyan)),
            Span::styled(" or ", Style::default().fg(Color::Gray)),
            Span::styled("^p/^n", Style::default().fg(Color::LightCyan)),
            Span::styled(" nav ", Style::default().fg(Color::Gray)),
            Span::styled("\u{2502} ", Style::default().fg(separator_color)),
            Span::styled("/", Style::default().fg(Color::LightCyan)),
            Span::styled(" search ", Style::default().fg(Color::Gray)),
            Span::styled("\u{2502} ", Style::default().fg(separator_color)),
            Span::styled("f", Style::default().fg(Color::LightCyan)),
            Span::styled("ork ", Style::default().fg(Color::Gray)),
            Span::styled("\u{2502} ", Style::default().fg(separator_color)),
            Span::styled("s", Style::default().fg(Color::LightCyan)),
            Span::styled("top ", Style::default().fg(Color::Gray)),
        ];

        // Show worktree-specific shortcuts only when on a worktree
        if is_worktree {
            spans.extend([
                Span::styled("\u{2502} ", Style::default().fg(separator_color)),
                Span::styled("m", Style::default().fg(Color::LightCyan)),
                Span::styled("erge ", Style::default().fg(Color::Gray)),
                Span::styled("\u{2502} ", Style::default().fg(separator_color)),
                Span::styled("d", Style::default().fg(Color::LightCyan)),
                Span::styled("elete ", Style::default().fg(Color::Gray)),
            ]);
        }

        spans.extend([
            Span::styled("\u{2502} ", Style::default().fg(separator_color)),
            Span::styled("q", Style::default().fg(Color::LightCyan)),
            Span::styled("uit", Style::default().fg(Color::Gray)),
        ]);

        Line::from(spans)
    }

    fn render(&mut self, frame: &mut Frame) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(3), Constraint::Length(1)])
            .split(frame.size());

        // Tree widget with glamorous styling
        let (title, border_color) = match self.mode {
            TreeViewMode::Start => (" Projects / Worktrees ", Color::LightMagenta),
            TreeViewMode::Kill => (" Kill Session ", Color::LightRed),
        };

        let tree = Tree::new(&self.tree_items)
            .expect("unique identifiers")
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(Style::default().fg(border_color))
                    .title(title)
                    .title_style(Style::default().fg(Color::LightCyan).bold()),
            )
            .style(Style::default().fg(Color::White))
            .highlight_style(
                Style::default()
                    .bg(Color::Rgb(80, 60, 120)) // Soft purple background
                    .fg(Color::White)
                    .bold(),
            )
            .highlight_symbol("\u{276f} ") // Heavy right-pointing angle ❯
            .node_closed_symbol("\u{25b8} ") // Small arrow right ▸
            .node_open_symbol("\u{25be} ") // Small arrow down ▾
            .node_no_children_symbol("  ");

        frame.render_stateful_widget(tree, chunks[0], &mut self.tree_state);

        // Status bar with styling
        // Check for status message (takes priority)
        let status_line = if let Some(ref busy) = self.busy {
            let frame = SPINNER_FRAMES[busy.spinner_index];
            Line::from(vec![Span::styled(
                format!("{} {}", frame, busy.message),
                Style::default().fg(Color::Yellow),
            )])
        } else if let Some(ref msg) = self.status_message {
            if !msg.is_expired() {
                let color = if msg.is_error {
                    Color::LightRed
                } else {
                    Color::LightGreen
                };
                Line::from(vec![Span::styled(&msg.text, Style::default().fg(color))])
            } else {
                self.build_default_status_line()
            }
        } else if self.search_mode {
            // Search mode - show search input
            let mut spans = vec![Span::styled(
                "/",
                Style::default().fg(Color::LightMagenta).bold(),
            )];
            if self.query.is_empty() {
                spans.push(Span::styled(
                    "type to search...",
                    Style::default().fg(Color::DarkGray).italic(),
                ));
            } else {
                let query_color = if self.no_match {
                    Color::LightRed
                } else {
                    Color::LightGreen
                };
                spans.push(Span::styled(
                    &self.query,
                    Style::default().fg(query_color).bold(),
                ));
            }
            spans.push(Span::styled("_", Style::default().fg(Color::LightMagenta)));
            spans.push(Span::styled(
                "  (Esc to exit)",
                Style::default().fg(Color::DarkGray),
            ));
            Line::from(spans)
        } else {
            self.build_default_status_line()
        };

        let status = Paragraph::new(status_line);
        frame.render_widget(status, chunks[1]);
    }
}

const SPINNER_FRAMES: [&str; 4] = ["|", "/", "-", "\\"];

enum HandleResult {
    Quit,
    Action(SelectedAction),
    /// Fork worktree - handled internally, returns to tree view if cancelled
    ForkWorktree(String),
    /// Merge worktree - handled internally with refresh
    MergeWorktree {
        project: String,
        branch: String,
    },
    /// Delete worktree - handled internally with refresh
    DeleteWorktree {
        project: String,
        branch: String,
    },
    /// Kill session - handled internally with confirmation modal
    KillSession(SelectedAction),
}

/// Build tree items from project data
fn build_tree_items<'a>(
    projects: &[ProjectData],
    running_sessions: &[String],
    current: &CurrentContext,
) -> Result<Vec<TreeItem<'a, TreeNodeId>>> {
    let mut items = Vec::new();

    for project in projects {
        let is_current = current.is_current_project(&project.name);

        // Build styled project text - use magenta for current, yellow for others
        let name_style = if is_current {
            Style::default().fg(Color::LightMagenta).bold()
        } else {
            Style::default().fg(Color::LightYellow).bold()
        };

        // Current indicator before name, with spacing for alignment
        let mut spans = if is_current {
            vec![Span::styled(
                "\u{25b6} ", // ▶ current indicator
                Style::default().fg(Color::LightMagenta),
            )]
        } else {
            vec![Span::raw("  ")] // spacing for alignment
        };

        spans.push(Span::styled(project.name.clone(), name_style));

        if project.session_running {
            spans.push(Span::styled(
                " \u{25cf}",
                Style::default().fg(Color::LightGreen),
            ));
            spans.push(Span::styled(
                " running",
                Style::default().fg(Color::LightGreen).italic(),
            ));
        }

        let project_line: Line = Line::from(spans);

        let children: Vec<TreeItem<'a, TreeNodeId>> = project
            .worktrees
            .iter()
            .map(|wt| {
                let session_name = format!("{}__{}", project.name, wt.branch);
                let is_running = running_sessions.contains(&session_name);
                let is_current_wt = current.is_current_worktree(&project.name, &wt.branch);

                // Build styled worktree text - use magenta for current, cyan for others
                let branch_style = if is_current_wt {
                    Style::default().fg(Color::LightMagenta).bold()
                } else {
                    Style::default().fg(Color::LightCyan)
                };

                // Current indicator before name, with spacing for alignment
                let mut wt_spans = if is_current_wt {
                    vec![Span::styled(
                        "\u{25b6} ", // ▶ current indicator
                        Style::default().fg(Color::LightMagenta),
                    )]
                } else {
                    vec![Span::raw("  ")] // spacing for alignment
                };

                wt_spans.push(Span::styled(wt.branch.clone(), branch_style));

                if is_running {
                    wt_spans.push(Span::styled(
                        " \u{25cf}",
                        Style::default().fg(Color::LightGreen),
                    ));
                    wt_spans.push(Span::styled(
                        " running",
                        Style::default().fg(Color::LightGreen).italic(),
                    ));
                }

                let wt_line: Line = Line::from(wt_spans);

                TreeItem::new_leaf(
                    TreeNodeId::Worktree {
                        project: project.name.clone(),
                        branch: wt.branch.clone(),
                    },
                    wt_line,
                )
            })
            .collect();

        let item = if children.is_empty() {
            TreeItem::new_leaf(TreeNodeId::Project(project.name.clone()), project_line)
        } else {
            TreeItem::new(
                TreeNodeId::Project(project.name.clone()),
                project_line,
                children,
            )
            .context("Failed to create tree item")?
        };

        items.push(item);
    }

    Ok(items)
}

/// Build search candidates from project data
fn build_candidates(projects: &[ProjectData]) -> Vec<SearchCandidate> {
    let mut candidates = Vec::new();

    for project in projects {
        // Add project as candidate
        candidates.push(SearchCandidate {
            label: project.name.clone(),
            node_path: vec![TreeNodeId::Project(project.name.clone())],
            project: project.name.clone(),
        });

        // Add worktrees as candidates (with project name for better matching)
        for wt in &project.worktrees {
            candidates.push(SearchCandidate {
                label: format!("{} / {}", project.name, wt.branch),
                node_path: vec![
                    TreeNodeId::Project(project.name.clone()),
                    TreeNodeId::Worktree {
                        project: project.name.clone(),
                        branch: wt.branch.clone(),
                    },
                ],
                project: project.name.clone(),
            });
        }
    }

    candidates
}

/// Options for loading project data
struct LoadOptions {
    /// Filter to a specific project name
    project_filter: Option<String>,
    /// Only show running sessions
    running_only: bool,
    /// Include worktrees (false = projects only)
    include_worktrees: bool,
}

impl Default for LoadOptions {
    fn default() -> Self {
        Self {
            project_filter: None,
            running_only: false,
            include_worktrees: true,
        }
    }
}

/// Load project data (projects + optionally their worktrees)
fn load_project_data(opts: LoadOptions) -> Result<Vec<ProjectData>> {
    let project_names = Project::list_all()?;
    let running_sessions = tmux::list_sessions().unwrap_or_default();

    let mut data = Vec::new();

    for name in project_names {
        // Apply filter if provided
        if let Some(ref filter) = opts.project_filter {
            if name != *filter {
                continue;
            }
        }

        let project = match Project::load(&name) {
            Ok(p) => p,
            Err(_) => continue, // Skip projects that fail to load
        };

        let session_running = running_sessions.contains(&name);

        // Get worktrees only if requested
        let filtered_worktrees: Vec<WorktreeInfo> = if opts.include_worktrees {
            let worktrees = git::list_worktrees(&project).unwrap_or_default();

            // Filter worktrees to only running ones if running_only
            if opts.running_only {
                worktrees
                    .into_iter()
                    .filter(|wt| {
                        let session_name = format!("{}__{}", name, wt.branch);
                        running_sessions.contains(&session_name)
                    })
                    .collect()
            } else {
                worktrees
            }
        } else {
            Vec::new()
        };

        // In running_only mode, skip projects with no running sessions
        if opts.running_only && !session_running && filtered_worktrees.is_empty() {
            continue;
        }

        data.push(ProjectData {
            name,
            worktrees: filtered_worktrees,
            session_running,
        });
    }

    Ok(data)
}

/// Run the interactive tree view for starting sessions (with worktrees)
pub fn run(project_filter: Option<String>, focus_current: bool) -> Result<Option<SelectedAction>> {
    run_with_options(
        LoadOptions {
            project_filter,
            running_only: false,
            include_worktrees: true,
        },
        TreeViewMode::Start,
        focus_current,
    )
}

/// Run the interactive tree view for killing sessions (shows only running)
pub fn run_for_kill(session_filter: Option<String>) -> Result<Option<SelectedAction>> {
    run_with_options(
        LoadOptions {
            project_filter: session_filter,
            running_only: true,
            include_worktrees: true,
        },
        TreeViewMode::Kill,
        false,
    )
}

/// Run the interactive tree view with specified options
fn run_with_options(
    opts: LoadOptions,
    mode: TreeViewMode,
    focus_current: bool,
) -> Result<Option<SelectedAction>> {
    let filter = opts.project_filter.clone();
    let running_only = opts.running_only;
    let projects = load_project_data(opts)?;

    if projects.is_empty() {
        if running_only {
            anyhow::bail!("No twig sessions running");
        } else if filter.is_some() {
            anyhow::bail!("Project '{}' not found", filter.as_deref().unwrap_or(""));
        } else {
            println!("No projects found. Create one with: twig new <name>");
            return Ok(None);
        }
    }

    // Check if running in a terminal
    if !stdout().is_terminal() {
        anyhow::bail!(
            "Interactive tree view requires a terminal. Run in a TTY or use a different command."
        );
    }

    let running_sessions = tmux::list_sessions().unwrap_or_default();
    let current = CurrentContext::from_env();
    let mut app = TreeViewApp::new(projects, &running_sessions, mode, &current, focus_current)?;

    // Setup terminal
    enable_raw_mode()?;
    stdout().execute(EnterAlternateScreen)?;
    let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;

    let result = run_event_loop(&mut terminal, &mut app);

    // Restore terminal
    disable_raw_mode()?;
    stdout().execute(LeaveAlternateScreen)?;

    match result? {
        EventLoopOutcome::Quit => Ok(None),
        EventLoopOutcome::Attach(session) => {
            tmux::connect_to_session(&session)?;
            Ok(None)
        }
        EventLoopOutcome::Action(action) => {
            if mode == TreeViewMode::Start {
                match action {
                    SelectedAction::StartProject(name) => {
                        tmux::connect_to_session(&name)?;
                        Ok(None)
                    }
                    SelectedAction::StartWorktree { project, branch } => {
                        let session_name = format!("{}__{}", project, branch);
                        tmux::connect_to_session(&session_name)?;
                        Ok(None)
                    }
                    _ => Ok(Some(action)),
                }
            } else {
                Ok(Some(action))
            }
        }
    }
}

fn run_event_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut TreeViewApp,
) -> Result<EventLoopOutcome> {
    loop {
        if let Some(result) = app.poll_busy() {
            app.busy = None;
            match result {
                BusyResult::Ready(session) => {
                    return Ok(EventLoopOutcome::Attach(session));
                }
                BusyResult::Error(message) => {
                    app.status_message = Some(StatusMessage::error(message));
                }
            }
        }

        app.tick_busy();

        // Clear expired status messages
        if let Some(ref msg) = app.status_message {
            if msg.is_expired() {
                app.status_message = None;
            }
        }

        terminal.draw(|frame| app.render(frame))?;

        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    if let Some(result) = app.handle_key(key.code, key.modifiers) {
                        match result {
                            HandleResult::Quit => {
                                // If we need to switch sessions, return that info
                                if let Some(session) = app.switch_to_session.take() {
                                    return Ok(EventLoopOutcome::Action(
                                        SelectedAction::StartProject(session),
                                    ));
                                }
                                return Ok(EventLoopOutcome::Quit);
                            }
                            HandleResult::Action(action) => {
                                return Ok(EventLoopOutcome::Action(action));
                            }
                            HandleResult::ForkWorktree(project) => {
                                // If fork creates a session, return the action to start it
                                if let Some(action) = handle_fork_worktree(terminal, app, &project)?
                                {
                                    return Ok(EventLoopOutcome::Action(action));
                                }
                            }
                            HandleResult::MergeWorktree { project, branch } => {
                                handle_merge_worktree(terminal, app, &project, &branch)?;
                            }
                            HandleResult::DeleteWorktree { project, branch } => {
                                handle_delete_worktree(terminal, app, &project, &branch)?;
                            }
                            HandleResult::KillSession(action) => {
                                handle_kill_session(terminal, app, action)?;
                            }
                        }
                    }
                }
            }
        }
    }
}

enum EventLoopOutcome {
    Quit,
    Action(SelectedAction),
    Attach(String),
}

fn start_session_for_action(action: SelectedAction) -> Result<String> {
    match action {
        SelectedAction::StartProject(name) => {
            let project = Project::load(&name)?;
            if tmux::session_exists(&project.name)? {
                return Ok(project.name);
            }

            project.clone_if_needed()?;
            SessionBuilder::new(&project).start_with_control()?;
            Ok(project.name)
        }
        SelectedAction::StartWorktree { project, branch } => {
            let config = Project::load(&project)?;
            let session_name = config.worktree_session_name(&branch);

            if tmux::session_exists(&session_name)? {
                return Ok(session_name);
            }

            let worktrees = git::list_worktrees(&config)?;
            let worktree = worktrees
                .iter()
                .find(|wt| wt.branch == branch)
                .ok_or_else(|| anyhow::anyhow!("Worktree '{}' not found", branch))?;

            SessionBuilder::new(&config)
                .with_session_name(session_name.clone())
                .with_root(worktree.path.to_string_lossy().to_string())
                .with_worktree(branch)
                .start_with_control()?;

            Ok(session_name)
        }
        SelectedAction::KillProject(name) => Ok(name),
        SelectedAction::KillWorktree { project, branch } => Ok(format!("{}__{}", project, branch)),
    }
}

/// Handle fork worktree operation with input overlay
fn handle_fork_worktree(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut TreeViewApp,
    project_name: &str,
) -> Result<Option<SelectedAction>> {
    let project = match Project::load(project_name) {
        Ok(p) => p,
        Err(e) => {
            app.status_message = Some(StatusMessage::error(format!(
                "Failed to load project: {}",
                e
            )));
            return Ok(None);
        }
    };

    // Show input overlay for branch name
    let title = format!("New worktree for '{}'", project_name);
    let branch_name =
        match show_input_overlay(terminal, app, &title, "Enter branch name or #PR...")? {
            Some(name) if !name.trim().is_empty() => name,
            _ => return Ok(None), // Cancelled or empty
        };

    let input = branch_name.trim().to_string();
    let (worktree_path, branch_name) = if let Some(pr_number) = git::parse_pr_number(&input) {
        app.status_message = Some(StatusMessage::info(format!(
            "Fetching PR #{}...",
            pr_number
        )));
        terminal.draw(|frame| app.render(frame))?;

        match git::create_worktree_from_pr(&project, pr_number) {
            Ok(result) => (result.path, result.branch),
            Err(e) => {
                app.status_message = Some(StatusMessage::error(format!(
                    "Failed to create worktree from PR: {}",
                    e
                )));
                return Ok(None);
            }
        }
    } else {
        // Show progress
        app.status_message = Some(StatusMessage::info(format!("Creating '{}'...", input)));
        terminal.draw(|frame| app.render(frame))?;

        // Create the git worktree
        let worktree_path = match git::create_worktree(&project, &input) {
            Ok(path) => path,
            Err(e) => {
                app.status_message = Some(StatusMessage::error(format!(
                    "Failed to create worktree: {}",
                    e
                )));
                return Ok(None);
            }
        };

        (worktree_path, input)
    };

    // Create and start tmux session for the worktree
    let session_name = project.worktree_session_name(&branch_name);

    // Check if session already exists (unlikely but possible)
    if tmux::session_exists(&session_name)? {
        app.status_message = Some(StatusMessage::info(format!(
            "Session '{}' already exists",
            session_name
        )));
        return Ok(Some(SelectedAction::StartWorktree {
            project: project_name.to_string(),
            branch: branch_name,
        }));
    }

    // Create the session with setup window
    let builder = SessionBuilder::new(&project)
        .with_session_name(session_name.clone())
        .with_root(worktree_path.to_string_lossy().to_string())
        .with_worktree(branch_name.clone());

    if let Err(e) = builder.start_with_control() {
        app.status_message = Some(StatusMessage::error(format!(
            "Failed to start session: {}",
            e
        )));
        return Ok(None);
    }

    // Return action to start the worktree session
    Ok(Some(SelectedAction::StartWorktree {
        project: project_name.to_string(),
        branch: branch_name,
    }))
}

/// Handle merge worktree operation with confirmation
fn handle_merge_worktree(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut TreeViewApp,
    project_name: &str,
    branch_name: &str,
) -> Result<()> {
    let project = match Project::load(project_name) {
        Ok(p) => p,
        Err(e) => {
            app.status_message = Some(StatusMessage::error(format!(
                "Failed to load project: {}",
                e
            )));
            return Ok(());
        }
    };

    let default_branch = match git::get_default_branch(&project.root_expanded()) {
        Ok(b) => b,
        Err(e) => {
            app.status_message = Some(StatusMessage::error(format!(
                "Failed to get default branch: {}",
                e
            )));
            return Ok(());
        }
    };

    // Show confirmation
    let message = format!("Merge '{}' into '{}'?", branch_name, default_branch);
    if !show_confirm_overlay(terminal, app, &message)? {
        return Ok(());
    }

    // Show progress
    app.status_message = Some(StatusMessage::info(format!("Merging '{}'...", branch_name)));
    terminal.draw(|frame| app.render(frame))?;

    // Perform the merge
    if let Err(e) = git::merge_branch_to_default(&project.root_expanded(), branch_name) {
        app.status_message = Some(StatusMessage::error(format!("Merge failed: {}", e)));
        return Ok(());
    }

    // Ask if user wants to delete the worktree
    let delete_msg = format!("Delete worktree '{}' and its session?", branch_name);
    if show_confirm_overlay(terminal, app, &delete_msg)? {
        delete_worktree_internal(terminal, app, &project, branch_name)?;
    } else {
        app.status_message = Some(StatusMessage::info(format!(
            "Merged '{}' into '{}'",
            branch_name, default_branch
        )));
        app.refresh(Some(project_name))?;
    }

    Ok(())
}

/// Handle delete worktree operation with confirmation
fn handle_delete_worktree(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut TreeViewApp,
    project_name: &str,
    branch_name: &str,
) -> Result<()> {
    let project = match Project::load(project_name) {
        Ok(p) => p,
        Err(e) => {
            app.status_message = Some(StatusMessage::error(format!(
                "Failed to load project: {}",
                e
            )));
            return Ok(());
        }
    };

    // Show confirmation
    let message = format!(
        "Delete worktree '{}' for project '{}'?",
        branch_name, project_name
    );
    if !show_confirm_overlay(terminal, app, &message)? {
        return Ok(());
    }

    delete_worktree_internal(terminal, app, &project, branch_name)
}

/// Internal helper to delete a worktree with progress feedback
fn delete_worktree_internal(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut TreeViewApp,
    project: &Project,
    branch_name: &str,
) -> Result<()> {
    let session_name = project.worktree_session_name(branch_name);
    let current = CurrentContext::from_env();

    // Check if we're deleting the current session
    let is_current = current.is_current_worktree(&project.name, branch_name);

    // Show progress
    app.status_message = Some(StatusMessage::info(format!(
        "Deleting '{}'...",
        branch_name
    )));
    terminal.draw(|frame| app.render(frame))?;

    // Kill the tmux session if running
    if tmux::session_exists(&session_name).unwrap_or(false) {
        if let Err(e) = tmux::safe_kill_session(&session_name) {
            app.status_message = Some(StatusMessage::error(format!(
                "Failed to kill session: {}",
                e
            )));
            return Ok(());
        }
    }

    // Delete the worktree
    if let Err(e) = git::delete_worktree(project, branch_name) {
        app.status_message = Some(StatusMessage::error(format!(
            "Failed to delete worktree: {}",
            e
        )));
        return Ok(());
    }

    // If we deleted the current session, switch to the project session on exit
    if is_current {
        app.switch_to_session = Some(project.name.clone());
        app.status_message = Some(StatusMessage::info(format!(
            "Deleted '{}'. Will switch to '{}' on exit.",
            branch_name, project.name
        )));
    } else {
        app.status_message = Some(StatusMessage::info(format!(
            "Deleted worktree '{}'",
            branch_name
        )));
    }

    // Refresh the tree view
    app.refresh(Some(&project.name))?;

    Ok(())
}

/// Handle kill session operation with confirmation modal
fn handle_kill_session(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut TreeViewApp,
    action: SelectedAction,
) -> Result<()> {
    let (session_name, display_name, project_name) = match &action {
        SelectedAction::KillProject(name) => (name.clone(), name.clone(), name.clone()),
        SelectedAction::KillWorktree { project, branch } => {
            let project_config = Project::load(project).ok();
            let session = project_config
                .as_ref()
                .map(|p| p.worktree_session_name(branch))
                .unwrap_or_else(|| format!("{}__{}", project, branch.replace('/', "-")));
            (
                session,
                format!("{} / {}", project, branch),
                project.clone(),
            )
        }
        _ => return Ok(()), // Not a kill action
    };

    // Check if session is running
    if !tmux::session_exists(&session_name).unwrap_or(false) {
        app.status_message = Some(StatusMessage::info(format!(
            "Session '{}' is not running",
            display_name
        )));
        return Ok(());
    }

    // Show confirmation modal
    let message = format!("Stop session '{}'?", display_name);
    if !show_confirm_overlay(terminal, app, &message)? {
        return Ok(()); // Cancelled - stay in tree view
    }

    let current = CurrentContext::from_env();
    let is_current = match &action {
        SelectedAction::KillProject(name) => current.is_current_project(name),
        SelectedAction::KillWorktree { project, branch } => {
            current.is_current_worktree(project, branch)
        }
        _ => false,
    };

    // Show progress
    app.status_message = Some(StatusMessage::info(format!(
        "Stopping '{}'...",
        display_name
    )));
    terminal.draw(|frame| app.render(frame))?;

    // Kill the session
    if let Err(e) = tmux::safe_kill_session(&session_name) {
        app.status_message = Some(StatusMessage::error(format!(
            "Failed to stop session: {}",
            e
        )));
        return Ok(());
    }

    // If we killed the current session, we need to handle session switching
    if is_current {
        // Try to switch to the project session (for worktrees) or another session
        if let SelectedAction::KillWorktree { project, .. } = &action {
            app.switch_to_session = Some(project.clone());
            app.status_message = Some(StatusMessage::info(format!(
                "Stopped '{}'. Will switch to '{}' on exit.",
                display_name, project
            )));
        } else {
            app.status_message = Some(StatusMessage::info(format!("Stopped '{}'", display_name)));
        }
    } else {
        app.status_message = Some(StatusMessage::info(format!("Stopped '{}'", display_name)));
    }

    // Refresh the tree view
    app.refresh(Some(&project_name))?;

    Ok(())
}

/// Show an input overlay and return the entered text (None if cancelled)
fn show_input_overlay(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut TreeViewApp,
    title: &str,
    placeholder: &str,
) -> Result<Option<String>> {
    let mut value = String::new();

    loop {
        terminal.draw(|frame| {
            // Render the tree view in the background
            app.render(frame);
            // Render input dialog on top
            render_input_dialog(frame, title, placeholder, &value);
        })?;

        if event::poll(Duration::from_millis(50))? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    match key.code {
                        KeyCode::Esc => return Ok(None),
                        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                            return Ok(None)
                        }
                        KeyCode::Enter => return Ok(Some(value)),
                        KeyCode::Backspace => {
                            value.pop();
                        }
                        KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                            value.push(c);
                        }
                        _ => {}
                    }
                }
            }
        }
    }
}

/// Render a centered input dialog
fn render_input_dialog(frame: &mut Frame, title: &str, placeholder: &str, value: &str) {
    use ratatui::widgets::Clear;

    let area = frame.size();

    // Center the dialog
    let dialog_width = 50.min(area.width - 4);
    let dialog_height = 5;
    let dialog_x = (area.width.saturating_sub(dialog_width)) / 2;
    let dialog_y = (area.height.saturating_sub(dialog_height)) / 2;

    let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);

    // Clear background
    frame.render_widget(Clear, dialog_area);

    // Dialog box
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::LightMagenta))
        .title(format!(" {} ", title))
        .title_style(Style::default().fg(Color::LightCyan).bold());

    let inner = block.inner(dialog_area);
    frame.render_widget(block, dialog_area);

    // Input text
    let input_area = Rect::new(inner.x + 1, inner.y + 1, inner.width - 2, 1);
    let input_text = if value.is_empty() {
        Line::from(vec![
            Span::styled(placeholder, Style::default().fg(Color::DarkGray).italic()),
            Span::styled("_", Style::default().fg(Color::LightMagenta)),
        ])
    } else {
        Line::from(vec![
            Span::styled(value, Style::default().fg(Color::White)),
            Span::styled("_", Style::default().fg(Color::LightMagenta)),
        ])
    };
    let input_widget = Paragraph::new(input_text);
    frame.render_widget(input_widget, input_area);

    // Help text
    let help_area = Rect::new(inner.x, inner.y + inner.height - 1, inner.width, 1);
    let help = Paragraph::new("Enter to confirm, Esc to cancel")
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, help_area);
}

/// Show a confirmation overlay and return true if user confirmed
fn show_confirm_overlay(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut TreeViewApp,
    message: &str,
) -> Result<bool> {
    let mut selected = false; // false = No (default), true = Yes

    loop {
        terminal.draw(|frame| {
            // Render the tree view in the background
            app.render(frame);
            // Render confirmation dialog on top
            render_confirm_dialog(frame, message, selected);
        })?;

        if event::poll(Duration::from_millis(50))? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    match key.code {
                        KeyCode::Char('y') | KeyCode::Char('Y') => return Ok(true),
                        KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => return Ok(false),
                        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                            return Ok(false)
                        }
                        KeyCode::Left => selected = true,
                        KeyCode::Right => selected = false,
                        KeyCode::Tab => selected = !selected,
                        KeyCode::Enter => return Ok(selected),
                        _ => {}
                    }
                }
            }
        }
    }
}

/// Render a centered confirmation dialog
fn render_confirm_dialog(frame: &mut Frame, title: &str, selected_yes: bool) {
    use ratatui::widgets::Clear;

    let area = frame.size();

    // Center the dialog
    let dialog_width = (title.len() as u16 + 8).max(30).min(area.width - 4);
    let dialog_height = 7;
    let dialog_x = (area.width.saturating_sub(dialog_width)) / 2;
    let dialog_y = (area.height.saturating_sub(dialog_height)) / 2;

    let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);

    // Clear background
    frame.render_widget(Clear, dialog_area);

    // Dialog box
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::LightYellow))
        .title(" Confirm ")
        .title_style(Style::default().fg(Color::LightCyan).bold());

    let inner = block.inner(dialog_area);
    frame.render_widget(block, dialog_area);

    // Title text
    let title_area = Rect::new(inner.x, inner.y + 1, inner.width, 1);
    let title_widget = Paragraph::new(title)
        .style(Style::default().fg(Color::White))
        .alignment(Alignment::Center);
    frame.render_widget(title_widget, title_area);

    // Buttons
    let buttons_area = Rect::new(inner.x, inner.y + 3, inner.width, 1);

    let yes_style = if selected_yes {
        Style::default()
            .fg(Color::Black)
            .bg(Color::LightGreen)
            .bold()
    } else {
        Style::default().fg(Color::LightGreen)
    };

    let no_style = if !selected_yes {
        Style::default().fg(Color::Black).bg(Color::LightRed).bold()
    } else {
        Style::default().fg(Color::LightRed)
    };

    let buttons = Line::from(vec![
        Span::raw("        "),
        Span::styled(" Yes ", yes_style),
        Span::raw("   "),
        Span::styled(" No ", no_style),
        Span::raw("        "),
    ]);

    let buttons_widget = Paragraph::new(buttons).alignment(Alignment::Center);
    frame.render_widget(buttons_widget, buttons_area);

    // Help text
    let help_area = Rect::new(inner.x, inner.y + inner.height - 1, inner.width, 1);
    let help = Paragraph::new("y/n or Enter to confirm")
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, help_area);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_candidates() {
        let projects = vec![
            ProjectData {
                name: "proj-a".to_string(),
                worktrees: vec![
                    WorktreeInfo {
                        path: "/tmp/a/main".into(),
                        branch: "main".to_string(),
                    },
                    WorktreeInfo {
                        path: "/tmp/a/feat".into(),
                        branch: "feature-x".to_string(),
                    },
                ],
                session_running: false,
            },
            ProjectData {
                name: "proj-b".to_string(),
                worktrees: vec![],
                session_running: true,
            },
        ];

        let candidates = build_candidates(&projects);

        // 2 projects + 2 worktrees = 4 candidates
        assert_eq!(candidates.len(), 4);

        // Check project candidate
        assert_eq!(candidates[0].label, "proj-a");
        assert_eq!(
            candidates[0].node_path,
            vec![TreeNodeId::Project("proj-a".to_string())]
        );

        // Check worktree candidate includes project name
        assert_eq!(candidates[1].label, "proj-a / main");
        assert_eq!(candidates[1].project, "proj-a");
    }

    #[test]
    fn test_tree_node_id_equality() {
        let a = TreeNodeId::Project("test".to_string());
        let b = TreeNodeId::Project("test".to_string());
        let c = TreeNodeId::Project("other".to_string());

        assert_eq!(a, b);
        assert_ne!(a, c);

        let wt1 = TreeNodeId::Worktree {
            project: "proj".to_string(),
            branch: "main".to_string(),
        };
        let wt2 = TreeNodeId::Worktree {
            project: "proj".to_string(),
            branch: "main".to_string(),
        };
        let wt3 = TreeNodeId::Worktree {
            project: "proj".to_string(),
            branch: "dev".to_string(),
        };

        assert_eq!(wt1, wt2);
        assert_ne!(wt1, wt3);
    }
}