mars-terminal 0.3.2

A terminal editor, multiplexer, and built-in AI agent in one binary — non-modal and Emacs-compatible, with tmux-style persistent sessions.
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
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span, Text},
    widgets::{Block, Borders, Clear, Paragraph},
    Frame,
};

use crate::{
    app::App,
    layout::PaneLayout,
    mode::Mode,
    palette::{Action, BarMode, ItemKind},
    pane::{PaneContent, PaneId},
};

/// Width of the "NNNN│ " line-number prefix when `line_numbers` is on.
pub const LINE_NUM_W: u16 = 6;
/// Width of the default gutter: a 1-char cursor-line pointer + 1 space.
pub const POINTER_W: u16 = 2;

/// Default is a slim pointer gutter (current-line marker only); the full
/// line-number gutter is opt-in (`line_numbers` knob). Either way the live
/// line/col lives in the status bar.
pub fn gutter_width(tuning: &crate::tuning::Tuning) -> u16 {
    if tuning.line_numbers { LINE_NUM_W } else { POINTER_W }
}

/// Tuning stores colors as [r, g, b] so they stay agent-editable JSON.
fn rgb(c: [u8; 3]) -> Color {
    Color::Rgb(c[0], c[1], c[2])
}

// ── Entry point ──────────────────────────────────────────────────────────────

pub fn render(frame: &mut Frame, app: &mut App) {
    let area = frame.area();

    // Layout: tab-bar (1) | pane area (min) | status (1) | control bar (1)
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // tab bar
            Constraint::Min(1),    // pane area
            Constraint::Length(1), // status bar
            Constraint::Length(1), // control bar
        ])
        .split(area);

    let (tab_area, full_pane_area, status_area, bar_area) =
        (chunks[0], chunks[1], chunks[2], chunks[3]);

    // Carve a left sidebar for the file tree when it's open; panes take the rest.
    let pane_area = if app.tree_open {
        let tw = app.tuning.tree_width.min(full_pane_area.width.saturating_sub(20));
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(tw), Constraint::Min(1)])
            .split(full_pane_area);
        render_file_tree(frame, app, cols[0]);
        cols[1]
    } else {
        full_pane_area
    };

    render_tab_bar(frame, app, tab_area);
    render_panes(frame, app, pane_area);
    // Session-start splash: the MARS banner overlays the workspace (terminal or
    // editor) until the first keypress dismisses it.
    if app.show_splash {
        render_splash(frame, app, pane_area);
    }
    // Proactive notice (W6): one dim line at the bottom of the workspace, the
    // agent's only path to the screen. Failures first; Esc dismisses.
    if !app.notices.is_empty() && !app.show_splash {
        render_notice(frame, app, pane_area);
    }
    render_status(frame, app, status_area);
    render_control_bar(frame, app, bar_area);

    // Bar dropdown / ask-panel drawn last so it sits on top (grows upward).
    if app.palette.is_some() && matches!(app.mode, Mode::Bar) {
        match app.palette.as_ref().map(|p| p.bar_mode.clone()) {
            Some(BarMode::Ask)     => render_ask_panel(frame, app, pane_area, bar_area),
            Some(BarMode::Command) => {
                let dropdown = render_bar_dropdown(frame, app, pane_area, bar_area);
                // In a terminal, the unified composer also shows the red inline
                // overlay at the cursor (type-in-place) — but the menu outranks
                // it: when the two would collide, the overlay stays hidden.
                if app.bar_return == Mode::Terminal {
                    render_shell_overlay(frame, app, pane_area, dropdown);
                }
            }
            // Shell: an inline composer anchored at the cursor (no eye-jump).
            Some(BarMode::Shell)   => render_shell_overlay(frame, app, pane_area, None),
            None => {}
        }
    }

    // which-key: after a short hesitation on a prefix, show the continuations.
    if !app.pending_prefix.is_empty()
        && app.frame_tick.saturating_sub(app.prefix_tick) >= app.tuning.which_key_delay_ticks()
    {
        render_which_key(frame, app, pane_area, status_area);
    }

    // C-t travel mode: always-on cheat panel — the characters tell you what to do.
    if matches!(app.mode, Mode::Tab) {
        render_travel_panel(frame, app, pane_area, status_area);
    }
}

// ── C-t travel panel ─────────────────────────────────────────────────────────

fn render_travel_panel(frame: &mut Frame, app: &App, pane_area: Rect, status_area: Rect) {
    let panel_width = app.tuning.travel_panel_width;
    let rows: &[(&str, &str)] = &[
        ("t / n",   "new tab"),
        ("r",       "rename tab"),
        ("h l ← →", "switch tab"),
        ("1-9",     "jump to tab"),
        ("H L",     "move tab"),
        ("T",       "open terminal (new tab)"),
        ("d",       "close tab"),
        ("",        ""),
        ("o / Tab", "next pane"),
        ("|",       "split right"),
        ("-",       "split below"),
        ("z",       "zoom pane (toggle)"),
        ("< >",     "resize pane"),
        ("x",       "move pane"),
        ("q / 0",   "close pane"),
        ("",        ""),
        ("?",       "why did this fail? (triage)"),
        ("w",       "watch this pane (summarize when done)"),
        ("D",       "detach session (keeps running)"),
        ("Esc ⏎",   "done  ·  creation exits, navigation stays"),
    ];

    let mut lines: Vec<Line> = Vec::new();
    for (keys, what) in rows {
        if keys.is_empty() {
            lines.push(Line::from(Span::raw("")));
            continue;
        }
        lines.push(Line::from(vec![
            Span::styled(
                format!(" {:<9}", keys),
                Style::default().fg(rgb(app.tuning.theme_accent_bright)).add_modifier(Modifier::BOLD),
            ),
            Span::styled(format!(" {}", what), Style::default().fg(Color::White)),
        ]));
    }

    let panel_h = (lines.len() as u16 + 1).min(pane_area.height.saturating_sub(1));
    let width = panel_width.min(status_area.width);
    let rect = Rect {
        x: status_area.x + status_area.width.saturating_sub(width),
        y: status_area.y.saturating_sub(panel_h),
        width,
        height: panel_h,
    };
    frame.render_widget(Clear, rect);
    let block = Block::default()
        .title(Span::styled(
            " C-t · space warp ",
            Style::default().fg(rgb(app.tuning.theme_accent)).add_modifier(Modifier::BOLD),
        ))
        .borders(Borders::TOP | Borders::LEFT)
        .border_style(Style::default().fg(Color::DarkGray));
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    frame.render_widget(Paragraph::new(Text::from(lines)), inner);
}

// ── which-key panel ──────────────────────────────────────────────────────────

fn render_which_key(frame: &mut Frame, app: &App, pane_area: Rect, status_area: Rect) {
    let conts = app.keys.continuations(&app.pending_prefix);
    if conts.is_empty() {
        return;
    }
    let prefix = crate::config::render_chords(&app.pending_prefix);

    let mut lines: Vec<Line> = Vec::new();
    for (tail, action) in &conts {
        lines.push(Line::from(vec![
            Span::styled(
                format!(" {:<4}", tail),
                Style::default()
                    .fg(rgb(app.tuning.theme_accent_bright))
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!(" {}", action.label()),
                Style::default().fg(Color::White),
            ),
        ]));
    }

    let panel_h = (lines.len() as u16 + 1).min(pane_area.height.saturating_sub(1)); // +1 border
    let width = app.tuning.which_key_panel_width.min(status_area.width);
    let rect = Rect {
        x: status_area.x + status_area.width.saturating_sub(width),
        y: status_area.y.saturating_sub(panel_h),
        width,
        height: panel_h,
    };
    frame.render_widget(Clear, rect);
    let block = Block::default()
        .title(Span::styled(
            format!(" {} - ", prefix),
            Style::default()
                .fg(rgb(app.tuning.theme_accent_bright))
                .add_modifier(Modifier::BOLD),
        ))
        .borders(Borders::TOP | Borders::LEFT)
        .border_style(Style::default().fg(Color::DarkGray));
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    frame.render_widget(Paragraph::new(Text::from(lines)), inner);
}

// ── Tab bar ──────────────────────────────────────────────────────────────────

fn render_tab_bar(frame: &mut Frame, app: &App, area: Rect) {
    let mut spans: Vec<Span> = Vec::new();
    for (i, tab) in app.tabs.iter().enumerate() {
        let buf_name = {
            let pane = app.panes.get(&tab.focused_pane);
            pane.and_then(|p| {
                if let PaneContent::Editor(buf_id) = p.content {
                    app.buffers.get(&buf_id).map(|b| b.name.as_str())
                } else {
                    Some("terminal")
                }
            })
            .unwrap_or(&tab.name)
        };
        let label = format!(" {} {} ", tab.name, buf_name);
        if i == app.active_tab {
            spans.push(Span::styled(
                label,
                Style::default()
                    .fg(rgb(app.tuning.theme_chip_fg))
                    .bg(rgb(app.tuning.theme_accent))
                    .add_modifier(Modifier::BOLD),
            ));
        } else {
            // Readable (not near-invisible DarkGray) so you can see inactive tab names.
            spans.push(Span::styled(
                label,
                Style::default().fg(rgb(app.tuning.theme_accent_bright)),
            ));
        }
        spans.push(Span::styled("", Style::default().fg(Color::DarkGray)));
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

// ── Pane layout ───────────────────────────────────────────────────────────────

fn compute_rects(layout: &PaneLayout, area: Rect) -> Vec<(PaneId, Rect)> {
    match layout {
        PaneLayout::Single(id) => vec![(*id, area)],
        PaneLayout::HSplit { top, bottom, ratio } => {
            let halves = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Percentage(*ratio), Constraint::Percentage(100 - *ratio)])
                .split(area);
            let mut v = compute_rects(top, halves[0]);
            v.extend(compute_rects(bottom, halves[1]));
            v
        }
        PaneLayout::VSplit { left, right, ratio } => {
            let halves = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Percentage(*ratio), Constraint::Percentage(100 - *ratio)])
                .split(area);
            let mut v = compute_rects(left, halves[0]);
            v.extend(compute_rects(right, halves[1]));
            v
        }
    }
}

fn render_panes(frame: &mut Frame, app: &mut App, area: Rect) {
    let focused_id = app.focused_pane_id();

    // Zoom follows focus: moving focus away (or closing the pane) unzooms.
    {
        let tab = &mut app.tabs[app.active_tab];
        let stale = match tab.zoomed {
            Some(z) => z != focused_id || !tab.layout.pane_ids().contains(&z),
            None => false,
        };
        if stale {
            tab.zoomed = None;
        }
    }
    let rects: Vec<(PaneId, Rect)> = {
        let tab = &app.tabs[app.active_tab];
        match tab.zoomed {
            Some(z) => vec![(z, area)],
            None => compute_rects(&tab.layout, area),
        }
    };

    // Remember pane rects for mouse hit-testing.
    app.pane_rects = rects.clone();

    // Update scroll offsets now that we know the real viewport heights.
    let margin = app.tuning.scroll_margin;
    for (pane_id, rect) in &rects {
        let inner_h = rect.height.saturating_sub(2) as usize;
        if let Some(p) = app.panes.get_mut(pane_id) {
            p.view_h = inner_h;
            p.ensure_scroll(inner_h, margin);
        }
    }

    // Keep terminal PTYs sized to their panes' inner area.
    for (pane_id, rect) in &rects {
        let tid = match app.panes.get(pane_id).map(|p| p.content.clone()) {
            Some(PaneContent::Terminal(id)) => Some(id),
            _ => None,
        };
        if let Some(tid) = tid {
            let iw = rect.width.saturating_sub(2);
            let ih = rect.height.saturating_sub(2);
            if let Some(t) = app.terms.get_mut(&tid) {
                t.resize(ih, iw);
            }
        }
    }

    let bar_open = app.palette.is_some() && matches!(app.mode, Mode::Bar);
    let mut cursor_screen: Option<(u16, u16)> = None;
    for (pane_id, rect) in &rects {
        let is_focused = *pane_id == focused_id;
        if let Some(pos) = render_pane(frame, app, *pane_id, *rect, is_focused) {
            cursor_screen = Some(pos);
        }
    }
    app.cursor_screen = cursor_screen; // anchors the shell-translate overlay

    // Place the terminal cursor — but not while the bar owns it.
    if !bar_open {
        if let Some((cx, cy)) = cursor_screen {
            if matches!(app.mode, Mode::Edit | Mode::Terminal) {
                frame.set_cursor_position((cx, cy));
            }
        }
    }
}

fn render_pane(
    frame: &mut Frame,
    app: &App,
    pane_id: PaneId,
    rect: Rect,
    focused: bool,
) -> Option<(u16, u16)> {
    let pane = app.panes.get(&pane_id)?;

    match pane.content.clone() {
        PaneContent::Editor(buf_id) => render_editor_pane(frame, app, pane_id, buf_id, rect, focused),
        PaneContent::Terminal(_term_id) => render_terminal_pane(frame, app, pane_id, rect, focused),
    }
}

fn render_editor_pane(
    frame: &mut Frame,
    app: &App,
    pane_id: PaneId,
    buf_id: usize,
    rect: Rect,
    focused: bool,
) -> Option<(u16, u16)> {
    let pane = app.panes.get(&pane_id)?;
    let buf  = app.buffers.get(&buf_id)?;

    let border_style = if focused {
        Style::default().fg(rgb(app.tuning.theme_accent))
    } else {
        Style::default().fg(Color::DarkGray)
    };
    let title_mod = if focused { Modifier::BOLD } else { Modifier::empty() };
    let marker    = if buf.modified { "" } else { "" };
    let shown     = pane.title.as_deref().unwrap_or(&buf.name);
    let title     = format!(" {}{} ", shown, marker);

    let block = Block::default()
        .title(Span::styled(title, Style::default().add_modifier(title_mod)))
        .borders(Borders::ALL)
        .border_style(border_style);

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

    let vp_h = inner.height as usize;
    let line_count = buf.line_count();
    let mut lines: Vec<Line> = Vec::with_capacity(vp_h);

    // Ordered selection range (start ≤ end) for highlighting.
    let sel: Option<((usize, usize), (usize, usize))> = pane.selection_anchor.map(|a| {
        let c = (pane.cursor_row, pane.cursor_col);
        if a <= c { (a, c) } else { (c, a) }
    });
    let [sr, sg, sb] = app.tuning.selection_bg;
    let [hr, hg, hb] = app.tuning.search_match_bg;
    let sel_style = Style::default().bg(Color::Rgb(sr, sg, sb));
    let search_style = Style::default().bg(Color::Rgb(hr, hg, hb));
    // Teleport labels: high-contrast chip (accent bg, dark fg, bold).
    let label_style = Style::default()
        .bg(rgb(app.tuning.theme_accent_bright))
        .fg(rgb(app.tuning.theme_chip_fg))
        .add_modifier(Modifier::BOLD);

    let numbers = app.tuning.line_numbers;
    for row_off in 0..vp_h {
        let row = pane.scroll_row + row_off;
        if row >= line_count {
            // Blank gutter beyond end-of-buffer.
            let blank = " ".repeat(gutter_width(&app.tuning) as usize);
            lines.push(Line::from(Span::styled(blank, Style::default().fg(Color::DarkGray))));
        } else {
            let content = buf.line_str(row);
            let on_cursor = focused && row == pane.cursor_row;
            let mut spans = Vec::new();
            if numbers {
                let num_style = if on_cursor {
                    Style::default().fg(rgb(app.tuning.theme_accent_bright)).add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::DarkGray)
                };
                spans.push(Span::styled(format!("{:>4}", row + 1), num_style));
            } else {
                // Slim pointer gutter: a marker on the cursor line, else blank.
                let (glyph, style) = if on_cursor {
                    ("", Style::default().fg(rgb(app.tuning.theme_accent)).add_modifier(Modifier::BOLD))
                } else {
                    ("  ", Style::default())
                };
                spans.push(Span::styled(glyph, style));
            }
            let chars: Vec<char> = content.chars().collect();

            // Per-char highlight map: 0 none, 1 selection, 2 isearch match.
            let mut hl: Vec<u8> = vec![0; chars.len()];
            if let Some(((sr, sc), (er, ec))) = sel {
                if row >= sr && row <= er {
                    let start = (if row == sr { sc } else { 0 }).min(chars.len());
                    let end = (if row == er { ec } else { chars.len() }).min(chars.len());
                    for h in hl.iter_mut().take(end).skip(start) { *h = 1; }
                }
            }
            let mut label_ch: Vec<Option<char>> = vec![None; chars.len()];
            if focused {
                for &(hr, hc, hlen) in &app.search_hl {
                    if hr == row {
                        let end = (hc + hlen).min(chars.len());
                        for h in hl.iter_mut().take(end).skip(hc.min(chars.len())) { *h = 2; }
                    }
                }
                // Teleport labels (kind 3) overwrite the first cell of each match.
                if app.search_pick {
                    for &(lr, lc, ch) in &app.search_labels {
                        if lr == row && lc < chars.len() {
                            hl[lc] = 3;
                            label_ch[lc] = Some(ch);
                        }
                    }
                }
            }

            if hl.iter().all(|&h| h == 0) {
                spans.push(Span::raw(content));
            } else {
                let mut i = 0;
                while i < chars.len() {
                    let kind = hl[i];
                    if kind == 3 {
                        let ch = label_ch[i].unwrap_or(chars[i]);
                        spans.push(Span::styled(ch.to_string(), label_style));
                        i += 1;
                        continue;
                    }
                    let mut j = i;
                    while j < chars.len() && hl[j] == kind && hl[j] != 3 { j += 1; }
                    let text: String = chars[i..j].iter().collect();
                    spans.push(match kind {
                        1 => Span::styled(text, sel_style),
                        2 => Span::styled(text, search_style),
                        _ => Span::raw(text),
                    });
                    i = j;
                }
            }
            lines.push(Line::from(spans));
        }
    }

    frame.render_widget(Paragraph::new(Text::from(lines)), inner);

    if focused {
        let sy = inner.y + (pane.cursor_row.saturating_sub(pane.scroll_row)) as u16;
        let sx = inner.x + gutter_width(&app.tuning) + pane.cursor_col as u16;
        if sy < inner.y + inner.height && sx < inner.x + inner.width {
            return Some((sx, sy));
        }
    }
    None
}

// ── Splash (day-0 banner) ─────────────────────────────────────────────────────

/// Parse a truecolor-ANSI line (`\x1b[38;2;r;g;bm` fg + `\x1b[0m` reset) into a
/// ratatui `Line`, also returning its *visible* width (escapes excluded).
fn ansi_to_line(raw: &str) -> (Line<'static>, u16) {
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut style = Style::default();
    let mut buf = String::new();
    let mut width: u16 = 0;
    let mut chars = raw.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            if !buf.is_empty() {
                spans.push(Span::styled(std::mem::take(&mut buf), style));
            }
            if chars.peek() == Some(&'[') {
                chars.next();
            }
            let mut code = String::new();
            for nc in chars.by_ref() {
                if nc == 'm' {
                    break;
                }
                code.push(nc);
            }
            if code == "0" || code.is_empty() {
                style = Style::default();
            } else if let Some(rest) = code.strip_prefix("38;2;") {
                let p: Vec<u8> = rest.split(';').filter_map(|x| x.parse().ok()).collect();
                if p.len() == 3 {
                    style = Style::default().fg(Color::Rgb(p[0], p[1], p[2]));
                }
            }
        } else {
            buf.push(c);
            width += 1;
        }
    }
    if !buf.is_empty() {
        spans.push(Span::styled(buf, style));
    }
    (Line::from(spans), width)
}

fn render_splash(frame: &mut Frame, app: &App, inner: Rect) {
    let t = &app.tuning;
    // Overlay: wipe whatever's underneath (terminal shell or empty editor).
    frame.render_widget(Clear, inner);

    // Parse the rich ANSI banner; fall back to a plain wordmark when narrow.
    let parsed: Vec<(Line, u16)> = crate::banner::BANNER_LINES
        .iter()
        .map(|l| ansi_to_line(l))
        .collect();
    let banner_w = parsed.iter().map(|(_, w)| *w).max().unwrap_or(0);
    let big = inner.width >= banner_w && inner.height >= (parsed.len() as u16 + 7);

    let mut lines: Vec<Line> = Vec::new();
    if big {
        // Uniform left pad so the art's internal spacing stays aligned.
        let pad = (inner.width.saturating_sub(banner_w) / 2) as usize;
        for (line, _) in parsed {
            let mut spans = vec![Span::raw(" ".repeat(pad))];
            spans.extend(line.spans);
            lines.push(Line::from(spans));
        }
        lines.push(Line::raw(""));
    } else {
        lines.push(Line::from(Span::styled(
            "M A R S",
            Style::default().fg(rgb(t.theme_accent)).add_modifier(Modifier::BOLD),
        )).centered());
        lines.push(Line::from(Span::styled(
            "mission control for your terminal",
            Style::default().fg(rgb(t.theme_accent_bright)).add_modifier(Modifier::ITALIC),
        )).centered());
        lines.push(Line::raw(""));
    }

    // Key commands — rendered as one aligned block (keys right-justified into a
    // column, descriptions left-aligned), the whole block centered. Per-line
    // centering made these look ragged; a single left pad keeps the columns true.
    let cmds: &[(&str, &str)] = &[
        ("C-Space", "mission control — search actions · ! shell · ? ask the agent"),
        ("C-x C-f", "navigator — browse & jump to any project file"),
        ("C-t",     "space warp — tabs, panes, splits, open terminal"),
        ("C-u",     "time-travel — scrub back through undo history"),
        ("C-x C-d", "detach — work keeps running while you're gone"),
        ("C-g",     "cancel anything"),
    ];
    let keyw = cmds.iter().map(|(k, _)| k.chars().count()).max().unwrap_or(0);
    let block_w = cmds
        .iter()
        .map(|(_, d)| keyw + 3 + d.chars().count())
        .max()
        .unwrap_or(0) as u16;
    let lpad = " ".repeat((inner.width.saturating_sub(block_w) / 2) as usize);
    let key_style = Style::default().fg(rgb(t.theme_accent_bright)).add_modifier(Modifier::BOLD);
    let desc_style = Style::default().fg(Color::Gray);
    for (k, d) in cmds {
        lines.push(Line::from(vec![
            Span::raw(lpad.clone()),
            Span::styled(format!("{k:>keyw$}"), key_style),
            Span::raw("   "),
            Span::styled(d.to_string(), desc_style),
        ]));
    }
    lines.push(Line::raw(""));
    lines.push(Line::from(Span::styled(
        "or just start typing",
        Style::default().fg(Color::Gray).add_modifier(Modifier::ITALIC),
    )).centered());

    // Vertically center the banner block.
    let block_h = lines.len() as u16;
    let top_pad = inner.height.saturating_sub(block_h) / 2;
    let area = Rect {
        x: inner.x,
        y: inner.y + top_pad,
        width: inner.width,
        height: block_h.min(inner.height),
    };
    frame.render_widget(Paragraph::new(Text::from(lines)), area);
}

fn render_terminal_pane(
    frame: &mut Frame,
    app: &App,
    pane_id: PaneId,
    rect: Rect,
    focused: bool,
) -> Option<(u16, u16)> {
    let pane = app.panes.get(&pane_id)?;
    let term_id = match pane.content {
        PaneContent::Terminal(id) => id,
        _ => return None,
    };

    let exited = app.terms.get(&term_id).map(|t| t.exited).unwrap_or(true);
    let offset = app.terms.get(&term_id).map(|t| t.view_offset()).unwrap_or(0);
    let border_style = if exited {
        Style::default().fg(rgb(app.tuning.theme_accent_dark))
    } else if focused {
        Style::default().fg(rgb(app.tuning.theme_terminal))
    } else {
        Style::default().fg(Color::DarkGray)
    };
    let base = pane.title.as_deref().unwrap_or("terminal");
    let title = if exited {
        format!(" {base} · exited ")
    } else if offset > 0 {
        format!(" {base}{offset} ")
    } else {
        format!(" {base} ")
    };
    let block = Block::default()
        .title(Span::styled(
            title,
            Style::default().add_modifier(if focused { Modifier::BOLD } else { Modifier::empty() }),
        ))
        .borders(Borders::ALL)
        .border_style(border_style);
    let inner = block.inner(rect);
    frame.render_widget(block, rect);

    let term = match app.terms.get(&term_id) {
        Some(t) => t,
        None => {
            frame.render_widget(
                Paragraph::new(Span::styled(
                    "(terminal closed)",
                    Style::default().fg(Color::DarkGray),
                )),
                inner,
            );
            return None;
        }
    };

    // Render the vt100 screen grid into the pane.
    let screen = term.screen();
    let (rows, cols) = screen.size();
    let vh = inner.height.min(rows);
    let vw = inner.width.min(cols);

    // A live mouse selection in THIS terminal → highlight its cells.
    let sel = app.term_sel.filter(|s| s.tid == term_id).map(|s| {
        let (mut a, mut b) = (s.anchor, s.end);
        if b < a { std::mem::swap(&mut a, &mut b); }
        (a, b, s.vw.saturating_sub(1))
    });
    let [sr, sg, sb] = app.tuning.selection_bg;
    let sel_bg = Color::Rgb(sr, sg, sb);

    let mut lines: Vec<Line> = Vec::with_capacity(vh as usize);
    for row in 0..vh {
        let mut spans: Vec<Span> = Vec::with_capacity(vw as usize);
        for col in 0..vw {
            if let Some(cell) = screen.cell(row, col) {
                let contents = cell.contents();
                let ch = if contents.is_empty() { " ".to_string() } else { contents };
                let mut style = Style::default()
                    .fg(conv_color(cell.fgcolor()))
                    .bg(conv_color(cell.bgcolor()));
                if cell.bold()      { style = style.add_modifier(Modifier::BOLD); }
                if cell.italic()    { style = style.add_modifier(Modifier::ITALIC); }
                if cell.underline() { style = style.add_modifier(Modifier::UNDERLINED); }
                if cell.inverse()   { style = style.add_modifier(Modifier::REVERSED); }
                if let Some((a, b, last)) = sel {
                    let c0 = if row == a.0 { a.1 } else { 0 };
                    let c1 = if row == b.0 { b.1 } else { last };
                    if row >= a.0 && row <= b.0 && col >= c0 && col <= c1 {
                        style = style.bg(sel_bg);
                    }
                }
                spans.push(Span::styled(ch, style));
            } else {
                spans.push(Span::raw(" "));
            }
        }
        lines.push(Line::from(spans));
    }
    frame.render_widget(Paragraph::new(Text::from(lines)), inner);

    // Dead shell: overlay the dismissal hint on the bottom row.
    if exited && inner.height > 0 {
        let notice = Rect { x: inner.x, y: inner.y + inner.height - 1, width: inner.width, height: 1 };
        frame.render_widget(
            Paragraph::new(Span::styled(
                " process exited — Enter closes this pane ",
                Style::default()
                    .fg(rgb(app.tuning.theme_chip_fg))
                    .bg(rgb(app.tuning.theme_accent_dark))
                    .add_modifier(Modifier::BOLD),
            )),
            notice,
        );
        return None;
    }

    // Report the terminal's own cursor position when focused.
    if focused && !screen.hide_cursor() {
        let (cr, cc) = screen.cursor_position();
        let cx = inner.x + cc.min(vw.saturating_sub(1));
        let cy = inner.y + cr.min(vh.saturating_sub(1));
        return Some((cx, cy));
    }
    None
}

/// Map a vt100 cell color to a ratatui color.
fn conv_color(c: vt100::Color) -> Color {
    match c {
        vt100::Color::Default    => Color::Reset,
        vt100::Color::Idx(i)     => Color::Indexed(i),
        vt100::Color::Rgb(r, g, b) => Color::Rgb(r, g, b),
    }
}

// ── Status bar ───────────────────────────────────────────────────────────────

/// Hint pairs for the status bar. Edit-mode hints are derived live from the
/// keymap so they stay honest after a remap; other modes are fixed UI keys.
fn status_hints(app: &App) -> Vec<(String, String)> {
    if matches!(app.mode, Mode::Edit) {
        let mut v = vec![(bar_open_keys(app), "⌕ commands".to_string())];
        for (action, label) in [
            (Action::Save, "save"),
            (Action::ToggleFileTree, "open"),
            (Action::Search, "search"),
        ] {
            if let Some(b) = app.keys.binding_for(&action) {
                v.push((b, label.to_string()));
            }
        }
        v.push(("C-g".to_string(), "cancel".to_string()));
        v
    } else if matches!(app.mode, Mode::Terminal) {
        // Live-derived like Edit: the bar-open chord is remappable, and C-g here
        // means "leave the terminal for the editor" — NOT session detach (which
        // is C-x C-d). Naming it "detach" scared tmux refugees.
        vec![
            (bar_open_keys(app), "commands".to_string()),
            ("C-g".to_string(), "to editor".to_string()),
            ("type".to_string(), "to shell".to_string()),
        ]
    } else {
        app.mode
            .hints()
            .iter()
            .map(|(k, a)| (k.to_string(), a.to_string()))
            .collect()
    }
}

/// The chords that open the command bar, rendered (e.g. "C-Spc / M-x").
fn bar_open_keys(app: &App) -> String {
    app.keys
        .bar_open
        .iter()
        .map(|c| crate::config::render_chords(std::slice::from_ref(c)))
        .collect::<Vec<_>>()
        .join(" / ")
}

fn render_status(frame: &mut Frame, app: &App, area: Rect) {
    let accent = rgb(app.tuning.theme_accent);
    let sand   = rgb(app.tuning.theme_accent_bright);
    let chipfg = rgb(app.tuning.theme_chip_fg);
    // Brand lives in chrome; green stays semantic (a live shell process).
    let (mode_fg, mode_bg, key_bg, key_fg) = match &app.mode {
        Mode::Edit     => (chipfg, accent,       accent, chipfg),
        Mode::Prompt   => (chipfg, sand,         sand,   chipfg),
        Mode::Tab      => (chipfg, accent,       accent, chipfg),
        Mode::Bar      => (chipfg, accent,       accent, chipfg),
        Mode::Tree     => (chipfg, accent,       accent, chipfg),
        Mode::Undo     => (chipfg, sand,         sand,   chipfg),
        Mode::Terminal => {
            let teal = rgb(app.tuning.theme_terminal);
            (Color::White, teal, teal, Color::White)
        }
    };

    // Left side: mode label + hints
    let mut spans: Vec<Span> = vec![
        Span::styled(
            format!(" {} ", app.mode.label()),
            Style::default()
                .fg(mode_fg)
                .bg(mode_bg)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("  ", Style::default()),
    ];

    // Recording indicator: when LLM debug logging is on, an unmistakable red chip
    // (+ the active memory variant) so a full day of eval capture is never silently
    // lost. Derived live from llm_log::enabled().
    if crate::llm_log::enabled() {
        let mem = crate::retrieval::MemoryMode::from_env();
        let label = if matches!(mem, crate::retrieval::MemoryMode::None) {
            " ● REC ".to_string()
        } else {
            format!(" ● REC mem:{} ", mem.as_str())
        };
        spans.push(Span::styled(
            label,
            Style::default().fg(Color::White).bg(Color::Red).add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled("  ", Style::default()));
    }

    for (key, action) in status_hints(app) {
        spans.push(Span::styled(
            format!(" {} ", key),
            Style::default()
                .fg(key_fg)
                .bg(key_bg)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(
            format!(":{} ", action),
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled("  ", Style::default()));
    }

    // Transient info (pending prefix / status message) trails the hints on the
    // left, so the position readout on the right is never displaced.
    if !app.pending_prefix.is_empty() {
        spans.push(Span::styled(
            format!(" {}- ", crate::config::render_chords(&app.pending_prefix)),
            Style::default().fg(rgb(app.tuning.theme_accent_bright)).add_modifier(Modifier::BOLD),
        ));
    } else if let Some(msg) = &app.status_msg {
        spans.push(Span::styled(
            format!(" {msg} "),
            Style::default().fg(rgb(app.tuning.theme_accent_bright)),
        ));
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), area);

    // Position readout — ALWAYS right-aligned on top, so it can't be truncated
    // by the left hints or hidden by a status message. Ln/Col for editor panes.
    let pane = app.focused_pane();
    let session = app.session_name.as_ref().map(|s| format!("{s}")).unwrap_or_default();
    let readout = match pane.content {
        PaneContent::Editor(buf_id) => {
            let name = app
                .buffers
                .get(&buf_id)
                .map(|b| format!("{}{}", b.name, if b.modified { "" } else { "" }))
                .unwrap_or_default();
            format!("{name}   Ln {}, Col {}{session} ", pane.cursor_row + 1, pane.cursor_col + 1)
        }
        PaneContent::Terminal(_) => format!("terminal{session} "),
    };
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            readout,
            Style::default().fg(rgb(app.tuning.theme_accent_bright)).add_modifier(Modifier::BOLD),
        )))
        .alignment(Alignment::Right),
        area,
    );
}

// ── Control bar (bottom row, always visible) ──────────────────────────────────

fn render_control_bar(frame: &mut Frame, app: &App, area: Rect) {
    match &app.mode {
        Mode::Bar => {
            // Show current query with mode prefix
            let palette = match app.palette.as_ref() {
                Some(p) => p,
                None => return,
            };
            let mode_label = match palette.bar_mode {
                BarMode::Command => "CMD",
                BarMode::Ask     => "ASK",
                BarMode::Shell   => "SH !",
            };
            let prompt = format!("[{}] › {}", mode_label, palette.query);
            let style = Style::default()
                .fg(rgb(app.tuning.theme_accent))
                .add_modifier(Modifier::BOLD);
            // In-bar quick keys, taught right where they work — only while the
            // query is empty, because that's the only time they fire.
            let legend = if palette.bar_mode == BarMode::Command && palette.query.is_empty() {
                let keys: Vec<String> = crate::palette::bar_quick_legend()
                    .iter()
                    .map(|(k, what)| format!("{k} {what}"))
                    .collect();
                format!("   {}", keys.join(" · "))
            } else {
                String::new()
            };
            frame.render_widget(
                Paragraph::new(Line::from(vec![
                    Span::styled(prompt.clone(), style),
                    Span::styled(legend, Style::default().fg(Color::DarkGray)),
                ])),
                area,
            );
            // Set cursor at end of prompt
            let cx = area.x + prompt.chars().count() as u16 - 1; // before the ▎
            if cx < area.x + area.width {
                frame.set_cursor_position((cx, area.y));
            }
        }
        Mode::Prompt => {
            if let Some(p) = app.prompt.as_ref() {
                // Live search shows an `n/m` match counter (and a Tab hint).
                let extra = if p.kind == crate::app::PromptKind::Search {
                    match app.isearch_status() {
                        Some((cur, total)) if total > 0 => {
                            let pick = if total >= 2 { "  ⇥ jump" } else { "" };
                            format!("  {cur}/{total}{pick}")
                        }
                        _ if !p.input.is_empty() => "  (no match)".to_string(),
                        _ => String::new(),
                    }
                } else {
                    String::new()
                };
                let text = format!("{}{}{}", p.label, p.input, extra);
                frame.render_widget(
                    Paragraph::new(Span::styled(
                        text.clone(),
                        Style::default().fg(Color::White).add_modifier(Modifier::BOLD),
                    )),
                    area,
                );
                // Cursor sits after the query itself, before the counter suffix.
                let cx = area.x + (p.label.chars().count() + p.input.chars().count()) as u16;
                if cx < area.x + area.width {
                    frame.set_cursor_position((cx, area.y));
                }
            }
        }
        _ => {
            // Idle hint — derived from the live keymap, never hardcoded.
            let open = app.keys.binding_for(&Action::ToggleFileTree).unwrap_or_default();
            let search = app.keys.binding_for(&Action::Search).unwrap_or_default();
            let hint = format!(
                "  {}  commands    {}  open    {}  search    C-g  cancel",
                bar_open_keys(app), open, search
            );
            frame.render_widget(
                Paragraph::new(Span::styled(hint, Style::default().fg(Color::DarkGray))),
                area,
            );
        }
    }
}

// ── Bar dropdown (grows upward from control bar) ──────────────────────────────

/// Returns the rect it drew (None when nothing rendered) so the cursor-anchored
/// shell overlay can yield to it instead of drawing on top.
fn render_bar_dropdown(
    frame: &mut Frame,
    app: &App,
    pane_area: Rect,
    bar_area: Rect,
) -> Option<Rect> {
    let palette = app.palette.as_ref()?;

    let items = palette.visible_items(&app.frecency);
    if items.is_empty() {
        return None;
    }

    let max_height = ((pane_area.height * app.tuning.panel_max_height_pct / 100) as usize)
        .min(app.tuning.dropdown_max_rows as usize) as u16;
    let drop_h = (items.len() as u16 + 1).min(max_height); // +1 for potential title line
    let drop_w = bar_area.width;

    // Position: just above the control bar
    let drop_y = bar_area.y.saturating_sub(drop_h);
    let drop_rect = Rect {
        x: bar_area.x,
        y: drop_y,
        width: drop_w,
        height: drop_h,
    };

    frame.render_widget(Clear, drop_rect);

    let block = Block::default()
        .borders(Borders::TOP | Borders::LEFT | Borders::RIGHT)
        .border_style(Style::default().fg(rgb(app.tuning.theme_accent)));

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

    let max_show = inner.height as usize;

    // Scroll offset so the selected item is visible
    let scroll = if palette.selected >= max_show {
        palette.selected + 1 - max_show
    } else {
        0
    };

    let mut lines: Vec<Line> = Vec::new();
    for (idx, row) in items.iter().enumerate().skip(scroll).take(max_show) {
        // Typing pre-selects the top match (registry-first Enter); with an
        // empty query no row is highlighted until the user arrows in, and an
        // unhighlighted Enter never fires a row.
        let selected = palette.navigated && idx == palette.selected;
        let item_bg  = if selected { Color::DarkGray } else { Color::Reset };
        let has_sub  = matches!(row.kind, ItemKind::Submenu(_));

        // Two teaching columns: the IN-BAR quick key first and chip-styled —
        // it works right here, one keypress away — then the global chord,
        // looked up live (§5.3: show the key on every menu row).
        let quick = match &row.kind {
            ItemKind::Run(a) => crate::palette::bar_quick_key(a),
            ItemKind::Submenu(_) => None,
        };
        let binding = match &row.kind {
            ItemKind::Run(a) => app.keys.binding_for(a).unwrap_or_default(),
            ItemKind::Submenu(_) => String::new(),
        };

        let desc = if row.description.is_empty() {
            String::new()
        } else {
            format!("{}", row.description)
        };
        let type_mark = if has_sub { "" } else { "" };

        let quick_span = match quick {
            Some(q) => Span::styled(
                format!(" {q} "),
                Style::default()
                    .fg(rgb(app.tuning.theme_chip_fg))
                    .bg(rgb(app.tuning.theme_accent))
                    .add_modifier(Modifier::BOLD),
            ),
            None => Span::styled("   ", Style::default().bg(item_bg)),
        };
        let line = Line::from(vec![
            quick_span,
            Span::styled(
                format!(" {:<w$}", binding, w = app.tuning.binding_badge_width),
                Style::default()
                    .fg(rgb(app.tuning.theme_accent_bright))
                    .bg(item_bg)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("  ", Style::default().bg(item_bg)),
            Span::styled(
                format!("{}{}", row.label, type_mark),
                if selected {
                    Style::default()
                        .fg(rgb(app.tuning.theme_accent))
                        .bg(item_bg)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::White).bg(item_bg)
                },
            ),
            Span::styled(
                desc,
                Style::default().fg(Color::DarkGray).bg(item_bg),
            ),
        ]);
        lines.push(line);
    }

    frame.render_widget(Paragraph::new(Text::from(lines)), inner);
    Some(drop_rect)
}

// ── Proactive notice line (W6 watch verdicts) ────────────────────────────────

fn render_notice(frame: &mut Frame, app: &App, pane_area: Rect) {
    let Some(n) = app.notices.first() else { return };
    if pane_area.height == 0 {
        return;
    }
    let row = Rect { x: pane_area.x, y: pane_area.bottom() - 1, width: pane_area.width, height: 1 };
    let (glyph, fg) = match n.kind {
        crate::app::NoticeKind::Failure => ("", rgb(app.tuning.theme_accent_bright)),
        crate::app::NoticeKind::Info => ("", rgb(app.tuning.theme_terminal)),
    };
    let more = if app.notices.len() > 1 { format!("  (+{} more)", app.notices.len() - 1) } else { String::new() };
    let text = format!(" {glyph} {}{more}   Esc dismiss ", n.text);
    frame.render_widget(Clear, row);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            text,
            Style::default().fg(Color::Black).bg(fg).add_modifier(Modifier::BOLD),
        ))),
        row,
    );
}

// ── Left file-tree sidebar (@ / C-x d) ───────────────────────────────────────

fn render_file_tree(frame: &mut Frame, app: &App, area: Rect) {
    let accent = rgb(app.tuning.theme_accent);
    let focused = matches!(app.mode, Mode::Tree);
    let border = if focused { rgb(app.tuning.theme_accent_bright) } else { Color::DarkGray };

    frame.render_widget(Clear, area);
    // Header: the filter query (⌕) while filtering, else the root folder name.
    let (root_name, filter) = app
        .file_tree
        .as_ref()
        .map(|t| {
            let name = t
                .root
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| t.root.to_string_lossy().to_string());
            (name, t.filter.clone())
        })
        .unwrap_or_default();
    let title = if filter.is_empty() {
        format!(" Navigator · {root_name}/ ")
    } else {
        format!(" Navigator · ⌕ {filter} ")
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(border))
        .title(Span::styled(
            title,
            Style::default().fg(accent).add_modifier(Modifier::BOLD),
        ));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let selected = app.file_tree.as_ref().map(|t| t.selected).unwrap_or(0);
    let max_show = inner.height as usize;
    if max_show == 0 {
        return;
    }
    let scroll = if selected >= max_show { selected + 1 - max_show } else { 0 };

    let width = inner.width as usize;
    let mut lines: Vec<Line> = Vec::new();
    for (idx, row) in app.tree_rows.iter().enumerate().skip(scroll).take(max_show) {
        let is_sel = idx == selected && focused;
        // Selected row: a full-width accent band (unmistakable), like a chip.
        let bg = if is_sel { accent } else { Color::Reset };
        let indent = "  ".repeat(row.depth);
        let glyph = if row.updir {
            ""
        } else if row.is_dir {
            if row.expanded { "" } else { "" }
        } else {
            "  "
        };
        let label = if row.is_dir && !row.updir {
            format!("{}/", row.label)
        } else {
            row.label.clone()
        };
        // Foreground: readable on the band when selected; folders bold+accent,
        // files white, `../` dim — otherwise.
        let chip = rgb(app.tuning.theme_chip_fg);
        let name_fg = if is_sel {
            chip
        } else if row.updir {
            rgb(app.tuning.theme_accent_bright) // visible "go up" affordance
        } else if row.is_dir {
            accent
        } else {
            Color::White
        };
        let glyph_fg = if is_sel { chip } else { accent };
        let mut modifier = Modifier::empty();
        if row.is_dir && !row.updir {
            modifier |= Modifier::BOLD;
        }
        // Pad to the full inner width so the selection band spans the row.
        let used = indent.chars().count() + glyph.chars().count() + label.chars().count();
        let pad = " ".repeat(width.saturating_sub(used));
        lines.push(Line::from(vec![
            Span::styled(format!("{indent}{glyph}"), Style::default().fg(glyph_fg).bg(bg)),
            Span::styled(label, Style::default().fg(name_fg).bg(bg).add_modifier(modifier)),
            Span::styled(pad, Style::default().bg(bg)),
        ]));
    }
    frame.render_widget(Paragraph::new(Text::from(lines)), inner);
}

// ── Shell-translate overlay (W3, anchored at the cursor — no eye-jump) ─────────

fn render_shell_overlay(frame: &mut Frame, app: &App, pane_area: Rect, avoid: Option<Rect>) {
    let query = app.palette.as_ref().map(|p| p.query.as_str()).unwrap_or("");
    let chipfg = rgb(app.tuning.theme_chip_fg);
    let accent = rgb(app.tuning.theme_accent);

    // The input line begins EXACTLY where the cursor was (no label prefix), so
    // it reads as typing in place. A tiny chip sits just left of it: `!` for the
    // pure-shell mode, `›` for the unified composer (shell OR a picked command).
    let shell_mode = app
        .palette
        .as_ref()
        .map(|p| matches!(p.bar_mode, BarMode::Shell))
        .unwrap_or(true);
    let navigated = app.palette.as_ref().map(|p| p.navigated).unwrap_or(false);
    // Empty query: show a placeholder so the composer is unmistakably present.
    let input = if query.is_empty() {
        format!("{} run a command… ", if shell_mode { "!" } else { "" })
    } else {
        format!("{} {query} ", if shell_mode { "!" } else { "" })
    };
    let configured = crate::agent::AgentConfig::from_env().is_configured();
    let err = app.agent_answer.as_deref().filter(|a| a.starts_with(''));
    let hint = if app.agent_pending {
        let frames = ["", "", "", "", "", "", "", "", "", ""];
        let sp = frames[(app.frame_tick / app.tuning.spinner_speed_ticks % 10) as usize];
        format!(" {sp} translating…")
    } else if app.shell_ready {
        " ✓ Enter runs · edit to change · Esc cancel".to_string()
    } else if let Some(e) = err {
        format!(" {e} · Enter runs literally · Esc")
    } else if !configured {
        " Enter runs (set GEMINI_API_KEY to type English) · Esc".to_string()
    } else if shell_mode {
        " type English, Enter translates → command · Esc".to_string()
    } else if navigated {
        " Enter runs the highlighted command · no match → shell · Esc".to_string()
    } else {
        " type a command (English ok) · ! pure shell · Esc".to_string()
    };

    let width = ((input.chars().count().max(hint.chars().count())) as u16)
        .min(pane_area.width.max(4));

    // Anchor the INPUT row on the cursor row; hint goes below (or above at the
    // bottom edge). Clamp inside the pane.
    let (cx, cy) = app.cursor_screen.unwrap_or((pane_area.x, pane_area.y));
    let max_x = pane_area.x + pane_area.width.saturating_sub(width);
    let x = cx.min(max_x).max(pane_area.x);
    let hint_below = cy + 1 < pane_area.y + pane_area.height;
    let (input_y, hint_y) = if hint_below { (cy, cy + 1) } else { (cy, cy.saturating_sub(1)) };

    let input_rect = Rect { x, y: input_y, width, height: 1 };
    let hint_rect = Rect { x, y: hint_y, width, height: 1 };
    // The dropdown outranks the anchored composer: when they'd collide (cursor
    // near the bottom), skip the overlay entirely so the menu stays readable.
    if let Some(d) = avoid {
        if input_rect.intersects(d) || hint_rect.intersects(d) {
            return;
        }
    }
    frame.render_widget(Clear, input_rect);
    frame.render_widget(Clear, hint_rect);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            input,
            Style::default().fg(chipfg).bg(accent).add_modifier(Modifier::BOLD),
        ))),
        input_rect,
    );
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            hint,
            Style::default().fg(Color::DarkGray).bg(rgb(app.tuning.selection_bg)),
        ))),
        hint_rect,
    );
    // Text cursor sits right after the query (input is "! {query} ").
    let curx = x + 2 + query.chars().count() as u16;
    if curx < x + width {
        frame.set_cursor_position((curx, input_y));
    }
}

// ── Ask panel (LLM answer, grows upward from control bar) ─────────────────────

fn render_ask_panel(frame: &mut Frame, app: &App, pane_area: Rect, bar_area: Rect) {
    let width = bar_area.width.saturating_sub(2).max(10) as usize;
    let sand = rgb(app.tuning.theme_accent_bright);
    let mut lines: Vec<Line> = Vec::new();

    // The conversation transcript.
    for (role, text) in &app.agent_history {
        let (tag, tag_style) = if role == "user" {
            ("you  › ", Style::default().fg(sand).add_modifier(Modifier::BOLD))
        } else {
            ("mars › ", Style::default().fg(rgb(app.tuning.theme_accent)).add_modifier(Modifier::BOLD))
        };
        for (i, wrapped) in wrap_text(text, width.saturating_sub(7)).into_iter().enumerate() {
            let prefix = if i == 0 { tag } else { "       " };
            lines.push(Line::from(vec![
                Span::styled(prefix, tag_style),
                Span::styled(wrapped, Style::default().fg(Color::White)),
            ]));
        }
    }
    // The streamed reply-in-progress renders as a live assistant turn; the
    // final Answer replaces it (directive stripped, pushed into history).
    if let Some(partial) = app.agent_partial.as_ref().filter(|p| !p.is_empty()) {
        let tag_style =
            Style::default().fg(rgb(app.tuning.theme_accent)).add_modifier(Modifier::BOLD);
        for (i, wrapped) in wrap_text(partial, width.saturating_sub(7)).into_iter().enumerate() {
            let prefix = if i == 0 { "mars › " } else { "       " };
            lines.push(Line::from(vec![
                Span::styled(prefix, tag_style),
                Span::styled(wrapped, Style::default().fg(Color::White)),
            ]));
        }
    }
    if app.agent_pending {
        let frames = ["", "", "", "", "", "", "", "", "", ""];
        let speed = app.tuning.spinner_speed_ticks;
        let sp = frames[(app.frame_tick / speed % frames.len() as u64) as usize];
        lines.push(Line::from(Span::styled(
            format!(" {} thinking…", sp),
            Style::default().fg(sand).add_modifier(Modifier::BOLD),
        )));
    }
    if let Some(notice) = &app.agent_answer {
        for wrapped in wrap_text(notice, width) {
            lines.push(Line::from(Span::styled(
                wrapped,
                Style::default().fg(rgb(app.tuning.theme_accent_dark)),
            )));
        }
    }
    // A pending selection-refactor takes the confirm slot (Enter replaces the
    // selection — or inserts at the cursor when nothing was selected — reversibly).
    if app.refactor_replacement.is_some() {
        let n = app.refactor_replacement.as_deref().map(|c| c.lines().count()).unwrap_or(0);
        let verb = match app.refactor_target {
            Some((_, s, e)) if s == e => "insert at the cursor",
            _ => "replace the selection",
        };
        lines.push(Line::from(Span::raw("")));
        lines.push(Line::from(Span::styled(
            format!(" ▶ Enter to {verb} ({n} lines) · C-l cancel "),
            Style::default().fg(Color::Black).bg(Color::Green).add_modifier(Modifier::BOLD),
        )));
    } else if let Some(d) = &app.agent_directive {
        let label = match d {
            crate::agent::AgentDirective::Run(name) => format!(" ▶ Enter to run: {name} "),
            crate::agent::AgentDirective::Type(cmd) => {
                format!(" ▶ Enter to type into terminal: {cmd} ")
            }
            crate::agent::AgentDirective::Open(loc) => format!(" ▶ Enter to open: {loc} "),
            crate::agent::AgentDirective::Need(_) => String::new(), // auto-satisfied, never shown
        };
        lines.push(Line::from(Span::raw("")));
        lines.push(Line::from(Span::styled(
            label,
            Style::default()
                .fg(Color::Black)
                .bg(Color::Green)
                .add_modifier(Modifier::BOLD),
        )));
    }
    if lines.is_empty() {
        lines.push(Line::from(Span::styled(
            " Ask about what's on your screen — Enter sends · C-l new chat",
            Style::default().fg(Color::DarkGray),
        )));
    }

    // Adaptive height: grow to the content, cap at ask_panel_max_pct — the
    // chat hugs the bottom of the screen and never buries the workspace;
    // older turns are one scroll (Up / wheel) away, not more panel.
    let max_h = ((pane_area.height as u32 * app.tuning.ask_panel_max_pct as u32 / 100)
        as u16)
        .max(3);
    let content_h = lines.len() as u16 + 1; // +1 for top border
    let panel_h = content_h.clamp(2, max_h);
    let visible = panel_h.saturating_sub(1) as usize;

    // Scroll: pin to the bottom, offset by ask_scroll (lines up from the end).
    let total = lines.len();
    if total > visible {
        let max_scroll = total - visible;
        let scroll = app.ask_scroll.min(max_scroll);
        let start = max_scroll - scroll;
        let mut view: Vec<Line> = lines.drain(start..start + visible).collect();
        if scroll > 0 {
            // Replace the last line with a "more below" marker.
            if let Some(last) = view.last_mut() {
                *last = Line::from(Span::styled(
                    format!("{} more (Down to scroll) ", scroll),
                    Style::default().fg(Color::DarkGray),
                ));
            }
        }
        if start > 0 {
            if let Some(first) = view.first_mut() {
                *first = Line::from(Span::styled(
                    format!("{} more (Up to scroll) ", start),
                    Style::default().fg(Color::DarkGray),
                ));
            }
        }
        lines = view;
    }

    let panel_y = bar_area.y.saturating_sub(panel_h);
    let rect = Rect {
        x: bar_area.x,
        y: panel_y,
        width: bar_area.width,
        height: panel_h,
    };

    frame.render_widget(Clear, rect);
    let provider = crate::agent::AgentConfig::from_env().provider;
    let title = if provider == "none" {
        " ✦ ask ".to_string()
    } else {
        format!(" ✦ ask · {} ", provider)
    };
    let block = Block::default()
        .title(Span::styled(
            title,
            Style::default()
                .fg(rgb(app.tuning.theme_accent))
                .add_modifier(Modifier::BOLD),
        ))
        .borders(Borders::TOP | Borders::LEFT | Borders::RIGHT)
        .border_style(Style::default().fg(rgb(app.tuning.theme_accent)));
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    frame.render_widget(Paragraph::new(Text::from(lines)), inner);
}

/// Word-wrap `text` to `width` columns, preserving explicit newlines.
fn wrap_text(text: &str, width: usize) -> Vec<String> {
    let mut out = Vec::new();
    for para in text.split('\n') {
        if para.trim().is_empty() {
            out.push(String::new());
            continue;
        }
        let mut line = String::new();
        for word in para.split_whitespace() {
            if line.is_empty() {
                line = word.to_string();
            } else if line.chars().count() + 1 + word.chars().count() <= width {
                line.push(' ');
                line.push_str(word);
            } else {
                out.push(std::mem::take(&mut line));
                line = word.to_string();
            }
        }
        if !line.is_empty() {
            out.push(line);
        }
    }
    out
}