workmux 0.1.170

An opinionated workflow tool that orchestrates git worktrees and tmux
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
//! Help overlay rendering.

use ratatui::{
    Frame,
    layout::{Constraint, Rect},
    style::{Modifier, Style},
    text::{Line, Span, Text},
    widgets::{Block, Cell, Clear, Paragraph, Row, Table},
};

use super::super::app::{App, DashboardTab, ViewMode};
use super::super::keymap::{Context, help_rows};

/// Determine the current keymap context for help display.
fn get_help_context(app: &App) -> Context {
    match &app.view_mode {
        ViewMode::Dashboard => match app.active_tab {
            DashboardTab::Agents => {
                if app.filter_active {
                    Context::DashboardFilter
                } else if app.input_mode {
                    Context::DashboardInput
                } else {
                    Context::DashboardNormal
                }
            }
            DashboardTab::Worktrees => {
                if app.worktree_filter_active {
                    Context::WorktreeFilter
                } else {
                    Context::WorktreeNormal
                }
            }
        },
        ViewMode::Diff(diff) => {
            if diff.patch_mode {
                if diff.comment_input.is_some() {
                    Context::Comment
                } else {
                    Context::Patch
                }
            } else {
                Context::DiffNormal
            }
        }
    }
}

/// Get the title for the help overlay based on context.
fn context_title(ctx: Context) -> &'static str {
    match ctx {
        Context::DashboardNormal => "Dashboard",
        Context::DashboardInput => "Input Mode",
        Context::DashboardFilter | Context::WorktreeFilter => "Filter",
        Context::WorktreeNormal => "Worktrees",
        Context::DiffNormal => "Diff View",
        Context::Patch => "Patch Mode",
        Context::Comment => "Comment",
    }
}

/// Render the kill confirmation popup.
pub fn render_confirm_kill(f: &mut Frame, app: &App) {
    let palette = &app.palette;

    let height = 3;
    let width = 34;

    let area = f.area();
    let popup_area = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width: width.min(area.width),
        height: height.min(area.height),
    };

    let block = Block::bordered()
        .border_type(ratatui::widgets::BorderType::Rounded)
        .border_style(Style::default().fg(palette.help_border));

    let text = Line::from(vec![
        Span::styled(" Kill working agent? ", Style::default().fg(palette.text)),
        Span::styled(
            "y",
            Style::default()
                .fg(palette.text)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("es / ", Style::default().fg(palette.dimmed)),
        Span::styled(
            "n",
            Style::default()
                .fg(palette.text)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("o", Style::default().fg(palette.dimmed)),
    ]);

    let paragraph = Paragraph::new(text).block(block);

    f.render_widget(Clear, popup_area);
    f.render_widget(paragraph, popup_area);
}

/// Render the remove worktree confirmation modal.
pub fn render_confirm_remove(f: &mut Frame, app: &App) {
    let Some(ref plan) = app.pending_remove else {
        return;
    };
    let palette = &app.palette;

    let bold = |s: &str| {
        Span::styled(
            s.to_string(),
            Style::default()
                .fg(palette.text)
                .add_modifier(Modifier::BOLD),
        )
    };
    let dim = |s: &str| Span::styled(s.to_string(), Style::default().fg(palette.dimmed));

    // Build content lines
    let mut lines: Vec<Line> = Vec::new();

    // Title line + spacer
    lines.push(Line::from(vec![Span::styled(
        format!(" Remove {}?", plan.handle),
        Style::default().fg(palette.text),
    )]));
    lines.push(Line::from(""));

    // Warning lines
    if plan.is_dirty {
        lines.push(Line::from(vec![Span::styled(
            " Has uncommitted changes.",
            Style::default().fg(palette.danger),
        )]));
    }
    if plan.is_unmerged {
        lines.push(Line::from(vec![Span::styled(
            " Has unmerged commits.",
            Style::default().fg(palette.dimmed),
        )]));
    }

    // Branch outcome line
    if plan.keep_branch {
        lines.push(Line::from(vec![Span::styled(
            " Branch will be kept.",
            Style::default().fg(palette.dimmed),
        )]));
    } else {
        lines.push(Line::from(vec![Span::styled(
            " Branch will be deleted.",
            Style::default().fg(palette.dimmed),
        )]));
    }

    // Empty line before actions
    lines.push(Line::from(""));

    // Action line (context-dependent)
    let action_line = if plan.is_dirty && !plan.force_armed {
        // Dirty: must press f to arm force
        Line::from(vec![
            Span::raw(" "),
            bold("f"),
            dim(" force  "),
            bold("n"),
            dim(" cancel  "),
            bold("k"),
            if plan.keep_branch {
                dim(" delete branch")
            } else {
                dim(" keep branch")
            },
        ])
    } else if plan.is_dirty && plan.force_armed {
        // Dirty + force armed: y now available
        Line::from(vec![
            Span::raw(" "),
            bold("y"),
            dim(" confirm force  "),
            bold("n"),
            dim(" cancel  "),
            bold("k"),
            if plan.keep_branch {
                dim(" delete branch")
            } else {
                dim(" keep branch")
            },
        ])
    } else {
        // Clean or unmerged: y available
        Line::from(vec![
            Span::raw(" "),
            bold("y"),
            dim(" remove  "),
            bold("n"),
            dim(" cancel  "),
            bold("k"),
            if plan.keep_branch {
                dim(" delete branch")
            } else {
                dim(" keep branch")
            },
        ])
    };
    lines.push(action_line);

    // Calculate dimensions
    let height = lines.len() as u16 + 2; // +2 for borders
    let width = 44;

    let area = f.area();
    let popup_area = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width: width.min(area.width),
        height: height.min(area.height),
    };

    let block = Block::bordered()
        .border_type(ratatui::widgets::BorderType::Rounded)
        .border_style(Style::default().fg(palette.help_border));

    let paragraph = Paragraph::new(Text::from(lines)).block(block);

    f.render_widget(Clear, popup_area);
    f.render_widget(paragraph, popup_area);
}

/// Render the help overlay.
pub fn render_help(f: &mut Frame, app: &App) {
    let ctx = get_help_context(app);
    let title = context_title(ctx);
    let keybindings = help_rows(ctx);

    // Calculate dimensions based on content
    let row_count = keybindings.len() as u16;
    let height = row_count + 5; // +5 for borders, padding, and empty line at top
    let width = 44;

    // Center the popup
    let area = f.area();
    let popup_area = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width: width.min(area.width),
        height: height.min(area.height),
    };

    let palette = &app.palette;

    // Create styled block with rounded corners
    let block = Block::bordered()
        .border_type(ratatui::widgets::BorderType::Rounded)
        .border_style(Style::default().fg(palette.help_border))
        .title(Line::from(vec![
            Span::styled(" ", Style::default()),
            Span::styled(
                title,
                Style::default()
                    .fg(palette.header)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" ", Style::default()),
        ]))
        .title_bottom(Line::from(vec![
            Span::styled(" ", Style::default()),
            Span::styled("any key", Style::default().fg(palette.dimmed)),
            Span::styled(" to close ", Style::default().fg(palette.help_muted)),
        ]));

    // Build styled rows with empty line at top for padding
    let mut rows: Vec<Row> = vec![Row::new(vec![Cell::from(""), Cell::from("")])];
    rows.extend(keybindings.into_iter().map(|(key, desc)| {
        Row::new(vec![
            Cell::from(Line::from(vec![
                Span::styled(" ", Style::default()),
                Span::styled(
                    format!("{:>8}", key),
                    Style::default()
                        .fg(palette.dimmed)
                        .add_modifier(Modifier::BOLD),
                ),
            ])),
            Cell::from(Line::from(vec![
                Span::styled(" · ", Style::default().fg(palette.help_muted)),
                Span::styled(desc, Style::default().fg(palette.text)),
            ])),
        ])
    }));

    let table = Table::new(rows, [Constraint::Length(10), Constraint::Min(25)])
        .block(block)
        .column_spacing(0);

    f.render_widget(Clear, popup_area);
    f.render_widget(table, popup_area);
}

/// Render the sweep cleanup modal.
pub fn render_sweep(f: &mut Frame, app: &App) {
    let Some(ref sweep) = app.pending_sweep else {
        return;
    };
    let palette = &app.palette;

    let bold = |s: &str| {
        Span::styled(
            s.to_string(),
            Style::default()
                .fg(palette.text)
                .add_modifier(Modifier::BOLD),
        )
    };
    let dim = |s: &str| Span::styled(s.to_string(), Style::default().fg(palette.dimmed));

    // Empty state
    if sweep.candidates.is_empty() {
        let lines = vec![
            Line::from(""),
            Line::from(vec![Span::styled(
                " No merged or gone worktrees found.",
                Style::default().fg(palette.dimmed),
            )]),
            Line::from(""),
        ];

        let height = lines.len() as u16 + 2;
        let width = 38;
        let area = f.area();
        let popup_area = Rect {
            x: area.width.saturating_sub(width) / 2,
            y: area.height.saturating_sub(height) / 2,
            width: width.min(area.width),
            height: height.min(area.height),
        };

        let block = Block::bordered()
            .border_type(ratatui::widgets::BorderType::Rounded)
            .border_style(Style::default().fg(palette.help_border))
            .title(Line::from(vec![
                Span::styled(" ", Style::default()),
                Span::styled(
                    "Sweep",
                    Style::default()
                        .fg(palette.header)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(" ", Style::default()),
            ]));

        let paragraph = Paragraph::new(Text::from(lines)).block(block);
        f.render_widget(Clear, popup_area);
        f.render_widget(paragraph, popup_area);
        return;
    }

    let selected_count = sweep.candidates.iter().filter(|c| c.selected).count();

    // Build content lines
    let mut lines: Vec<Line> = Vec::new();
    lines.push(Line::from(""));

    for (i, candidate) in sweep.candidates.iter().enumerate() {
        let cursor = if i == sweep.cursor { "> " } else { "  " };
        let cursor_style = Style::default().fg(palette.text);

        if candidate.is_dirty {
            // Dirty: greyed out, not selectable
            lines.push(Line::from(vec![
                Span::styled(cursor, cursor_style),
                dim(&format!(
                    "[ ] {} ({}, dirty)",
                    candidate.handle,
                    candidate.reason.label()
                )),
            ]));
        } else {
            let checkbox = if candidate.selected { "[x]" } else { "[ ]" };
            let style = Style::default().fg(palette.text);
            lines.push(Line::from(vec![
                Span::styled(cursor, cursor_style),
                Span::styled(format!("{} {} ", checkbox, candidate.handle), style),
                dim(&format!("({})", candidate.reason.label())),
            ]));
        }
    }

    lines.push(Line::from(""));

    // Action line
    let remove_label = if selected_count > 0 {
        format!(" remove ({})", selected_count)
    } else {
        " remove".to_string()
    };
    lines.push(Line::from(vec![
        Span::raw(" "),
        bold("Space"),
        dim(" toggle  "),
        bold("Enter"),
        dim(&remove_label),
        dim("  "),
        bold("Esc"),
        dim(" cancel"),
    ]));

    // Calculate dimensions
    let height = lines.len() as u16 + 2; // +2 for borders
    let content_width = sweep
        .candidates
        .iter()
        .map(|c| {
            // cursor + checkbox + handle + reason
            2 + 4 + c.handle.len() + c.reason.label().len() + 10
        })
        .max()
        .unwrap_or(30);
    let width = (content_width as u16 + 4).max(44); // +4 for border+padding

    let area = f.area();
    let popup_area = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width: width.min(area.width),
        height: height.min(area.height),
    };

    let block = Block::bordered()
        .border_type(ratatui::widgets::BorderType::Rounded)
        .border_style(Style::default().fg(palette.help_border))
        .title(Line::from(vec![
            Span::styled(" ", Style::default()),
            Span::styled(
                "Sweep",
                Style::default()
                    .fg(palette.header)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" ", Style::default()),
        ]));

    let paragraph = Paragraph::new(Text::from(lines)).block(block);

    f.render_widget(Clear, popup_area);
    f.render_widget(paragraph, popup_area);
}

/// Render the base branch picker modal.
pub fn render_base_picker(f: &mut Frame, app: &App) {
    let Some(ref picker) = app.pending_base_picker else {
        return;
    };
    let palette = &app.palette;

    let bold = |s: &str| {
        Span::styled(
            s.to_string(),
            Style::default()
                .fg(palette.text)
                .add_modifier(Modifier::BOLD),
        )
    };
    let dim = |s: &str| Span::styled(s.to_string(), Style::default().fg(palette.dimmed));

    let filtered = picker.filtered();

    let content_width = picker
        .branches
        .iter()
        .map(|b| 2 + b.len())
        .max()
        .unwrap_or(20);
    let width = (content_width as u16 + 4).clamp(44, 60);
    // Fixed height: ~40% of terminal, matching add-worktree modal
    let area = f.area();
    let height = (area.height * 2 / 5).clamp(10, 25);
    // 1 filter + 1 blank + visible items + 1 blank + 1 footer + 2 borders
    let max_visible: usize = height.saturating_sub(6) as usize;

    let mut lines: Vec<Line> = Vec::new();

    // Filter input line (always present to keep layout stable)
    if picker.filter.is_empty() {
        lines.push(Line::from(vec![
            Span::styled(" /", Style::default().fg(palette.dimmed)),
            Span::styled("_", Style::default().fg(palette.dimmed)),
        ]));
    } else {
        lines.push(Line::from(vec![
            Span::styled(" /", Style::default().fg(palette.dimmed)),
            Span::styled(picker.filter.clone(), Style::default().fg(palette.text)),
            Span::styled("_", Style::default().fg(palette.text)),
        ]));
    }

    lines.push(Line::from(""));

    if filtered.is_empty() {
        lines.push(Line::from(vec![Span::styled(
            " No matching branches.",
            Style::default().fg(palette.dimmed),
        )]));
        // Fill remaining slots so height stays fixed
        for _ in 1..max_visible {
            lines.push(Line::from(""));
        }
    } else {
        // Compute a window of items around the cursor
        let total = filtered.len();
        let start = if total <= max_visible || picker.cursor < max_visible / 2 {
            0
        } else if picker.cursor + max_visible / 2 >= total {
            total.saturating_sub(max_visible)
        } else {
            picker.cursor - max_visible / 2
        };
        let end = (start + max_visible).min(total);

        for (fi, &idx) in filtered.iter().enumerate().take(end).skip(start) {
            let branch = &picker.branches[idx];
            let cursor = if fi == picker.cursor { "> " } else { "  " };

            let is_current = picker.current_base.as_ref().is_some_and(|b| b == branch);

            let name_style = if is_current {
                Style::default().fg(palette.accent)
            } else {
                Style::default().fg(palette.text)
            };

            lines.push(Line::from(vec![
                Span::styled(cursor, Style::default().fg(palette.text)),
                Span::styled(branch.clone(), name_style),
            ]));
        }

        // Fill remaining slots so height stays fixed
        for _ in (end - start)..max_visible {
            lines.push(Line::from(""));
        }
    }

    lines.push(Line::from(""));

    // Footer
    lines.push(Line::from(vec![
        Span::raw(" "),
        bold("Enter"),
        dim(" set base  "),
        bold("Esc"),
        dim(" cancel"),
    ]));

    let popup_area = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width: width.min(area.width),
        height: height.min(area.height),
    };

    let block = Block::bordered()
        .border_type(ratatui::widgets::BorderType::Rounded)
        .border_style(Style::default().fg(palette.help_border))
        .title(Line::from(vec![
            Span::styled(" ", Style::default()),
            Span::styled(
                "Set Base Branch",
                Style::default()
                    .fg(palette.header)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" ", Style::default()),
        ]));

    let paragraph = Paragraph::new(Text::from(lines)).block(block);

    f.render_widget(Clear, popup_area);
    f.render_widget(paragraph, popup_area);
}

/// Render the project picker modal.
pub fn render_project_picker(f: &mut Frame, app: &App) {
    let Some(ref picker) = app.pending_project_picker else {
        return;
    };
    let palette = &app.palette;

    let bold = |s: &str| {
        Span::styled(
            s.to_string(),
            Style::default()
                .fg(palette.text)
                .add_modifier(Modifier::BOLD),
        )
    };
    let dim = |s: &str| Span::styled(s.to_string(), Style::default().fg(palette.dimmed));

    let filtered = picker.filtered();

    let mut lines: Vec<Line> = Vec::new();

    // Filter input line (shown when typing)
    if !picker.filter.is_empty() {
        lines.push(Line::from(vec![
            Span::styled(" /", Style::default().fg(palette.dimmed)),
            Span::styled(picker.filter.clone(), Style::default().fg(palette.text)),
            Span::styled("_", Style::default().fg(palette.text)),
        ]));
    }

    lines.push(Line::from(""));

    if filtered.is_empty() {
        lines.push(Line::from(vec![Span::styled(
            " No matching projects.",
            Style::default().fg(palette.dimmed),
        )]));
    } else {
        for (fi, &idx) in filtered.iter().enumerate() {
            let project = &picker.projects[idx];
            let cursor = if fi == picker.cursor { "> " } else { "  " };

            let is_current = picker
                .current_name
                .as_ref()
                .is_some_and(|n| *n == project.name);

            let name_style = if is_current {
                Style::default().fg(palette.accent)
            } else {
                Style::default().fg(palette.text)
            };

            lines.push(Line::from(vec![
                Span::styled(cursor, Style::default().fg(palette.text)),
                Span::styled(project.name.clone(), name_style),
            ]));
        }
    }

    lines.push(Line::from(""));

    // Footer
    lines.push(Line::from(vec![
        Span::raw(" "),
        bold("Enter"),
        dim(" switch  "),
        bold("Esc"),
        dim(" cancel"),
    ]));

    // Calculate dimensions
    let height = lines.len() as u16 + 2;
    let content_width = picker
        .projects
        .iter()
        .map(|p| 2 + p.name.len())
        .max()
        .unwrap_or(20);
    let width = (content_width as u16 + 4).clamp(36, 60);

    let area = f.area();
    let popup_area = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width: width.min(area.width),
        height: height.min(area.height),
    };

    let block = Block::bordered()
        .border_type(ratatui::widgets::BorderType::Rounded)
        .border_style(Style::default().fg(palette.help_border))
        .title(Line::from(vec![
            Span::styled(" ", Style::default()),
            Span::styled(
                "Switch Project",
                Style::default()
                    .fg(palette.header)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" ", Style::default()),
        ]));

    let paragraph = Paragraph::new(Text::from(lines)).block(block);

    f.render_widget(Clear, popup_area);
    f.render_widget(paragraph, popup_area);
}

/// Render the add-worktree modal.
pub fn render_add_worktree(f: &mut Frame, app: &App) {
    use super::super::app::{AddWorktreeMode, PrListState};

    let Some(ref state) = app.pending_add_worktree else {
        return;
    };
    let palette = &app.palette;

    let bold = |s: &str| {
        Span::styled(
            s.to_string(),
            Style::default()
                .fg(palette.text)
                .add_modifier(Modifier::BOLD),
        )
    };
    let dim = |s: &str| Span::styled(s.to_string(), Style::default().fg(palette.dimmed));

    let is_pr_mode = state.mode == AddWorktreeMode::Pr;

    let area = f.area();
    let width = (area.width * 3 / 5).clamp(44, 80);

    let area = f.area();
    let height = (area.height * 2 / 5).clamp(10, 25);
    // overhead: filter + blank + action_row + blank + footer + blank_after_footer + borders(2)
    let has_action_row = !is_pr_mode && !state.filter.trim().is_empty();
    let overhead: u16 = 7 + if has_action_row { 1 } else { 0 };
    let max_visible: usize = height.saturating_sub(overhead) as usize;

    let mut lines: Vec<Line> = Vec::new();

    // Filter input line
    if state.filter.is_empty() {
        lines.push(Line::from(vec![
            Span::styled(" /", Style::default().fg(palette.dimmed)),
            Span::styled("_", Style::default().fg(palette.dimmed)),
        ]));
    } else {
        lines.push(Line::from(vec![
            Span::styled(" /", Style::default().fg(palette.dimmed)),
            Span::styled(state.filter.clone(), Style::default().fg(palette.text)),
            Span::styled("_", Style::default().fg(palette.text)),
        ]));
    }

    lines.push(Line::from(""));

    if is_pr_mode {
        // PR mode: show PR list
        match &state.pr_list {
            Some(PrListState::Loading) => {
                lines.push(Line::from(vec![Span::styled(
                    " Loading PRs...",
                    Style::default().fg(palette.dimmed),
                )]));
                for _ in 1..max_visible {
                    lines.push(Line::from(""));
                }
            }
            Some(PrListState::Loaded { prs, .. }) => {
                let filtered = state.filtered_prs();
                if filtered.is_empty() {
                    lines.push(Line::from(vec![Span::styled(
                        if state.filter.is_empty() {
                            " No open PRs."
                        } else {
                            " No matching PRs."
                        },
                        Style::default().fg(palette.dimmed),
                    )]));
                    for _ in 1..max_visible {
                        lines.push(Line::from(""));
                    }
                } else {
                    let total = filtered.len();
                    let start = if total <= max_visible || state.cursor < max_visible / 2 {
                        0
                    } else if state.cursor + max_visible / 2 >= total {
                        total.saturating_sub(max_visible)
                    } else {
                        state.cursor - max_visible / 2
                    };
                    let end = (start + max_visible).min(total);

                    for (fi, &idx) in filtered.iter().enumerate().take(end).skip(start) {
                        let pr = &prs[idx];
                        let is_selected = fi == state.cursor;
                        let cursor_str = if is_selected { "> " } else { "  " };

                        let title_style = if is_selected {
                            Style::default().fg(palette.accent)
                        } else {
                            Style::default().fg(palette.text)
                        };

                        let mut spans = vec![
                            Span::styled(cursor_str, Style::default().fg(palette.text)),
                            Span::styled(
                                format!("#{} ", pr.number),
                                Style::default().fg(palette.dimmed),
                            ),
                            Span::styled(pr.title.clone(), title_style),
                        ];
                        if pr.is_draft {
                            spans.push(dim(" [draft]"));
                        }

                        lines.push(Line::from(spans));
                    }

                    for _ in (end - start)..max_visible {
                        lines.push(Line::from(""));
                    }
                }
            }
            Some(PrListState::Error { message }) => {
                lines.push(Line::from(vec![Span::styled(
                    format!(" {}", message),
                    Style::default().fg(palette.danger),
                )]));
                for _ in 1..max_visible {
                    lines.push(Line::from(""));
                }
            }
            None => {
                for _ in 0..max_visible {
                    lines.push(Line::from(""));
                }
            }
        }
    } else {
        // Branch mode
        let filtered = state.filtered();

        // Action row: "Create" or "Checkout PR #N"
        if !state.filter.trim().is_empty() {
            let cursor_str = if state.cursor == 0 { "> " } else { "  " };
            let action_style = if state.cursor == 0 {
                Style::default()
                    .fg(palette.accent)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(palette.text)
            };

            let label = if let Some(pr_num) = state.detected_pr_number() {
                format!("+ Checkout PR #{}", pr_num)
            } else {
                format!("+ Create \"{}\"", state.filter.trim())
            };

            lines.push(Line::from(vec![
                Span::styled(cursor_str, Style::default().fg(palette.text)),
                Span::styled(label, action_style),
            ]));
        }

        // Branch rows
        if filtered.is_empty() && state.filter.trim().is_empty() {
            lines.push(Line::from(vec![Span::styled(
                " Type to search or create...",
                Style::default().fg(palette.dimmed),
            )]));
            for _ in 1..max_visible {
                lines.push(Line::from(""));
            }
        } else if filtered.is_empty() {
            for _ in 0..max_visible {
                lines.push(Line::from(""));
            }
        } else {
            let has_create_row = !state.filter.trim().is_empty();
            let branch_cursor = if has_create_row {
                state.cursor.checked_sub(1)
            } else {
                Some(state.cursor)
            };

            let total = filtered.len();
            let effective_cursor = branch_cursor.unwrap_or(0);
            let start = if total <= max_visible || effective_cursor < max_visible / 2 {
                0
            } else if effective_cursor + max_visible / 2 >= total {
                total.saturating_sub(max_visible)
            } else {
                effective_cursor - max_visible / 2
            };
            let end = (start + max_visible).min(total);

            for (fi, &idx) in filtered.iter().enumerate().take(end).skip(start) {
                let branch = &state.branches[idx];
                let is_selected = branch_cursor == Some(fi);
                let cursor_str = if is_selected { "> " } else { "  " };
                let is_occupied = state.occupied_branches.contains(branch);

                let branch_style = if is_occupied {
                    Style::default().fg(palette.dimmed)
                } else if is_selected {
                    Style::default().fg(palette.accent)
                } else {
                    Style::default().fg(palette.text)
                };

                let mut spans = vec![
                    Span::styled(cursor_str, Style::default().fg(palette.text)),
                    Span::styled(branch.clone(), branch_style),
                ];
                if is_occupied {
                    spans.push(dim(" (in use)"));
                }

                lines.push(Line::from(spans));
            }

            for _ in (end - start)..max_visible {
                lines.push(Line::from(""));
            }
        }
    }

    // Contextual hint based on current selection
    if !is_pr_mode {
        let has_create_row = !state.filter.trim().is_empty();
        let hint = if has_create_row && state.cursor == 0 {
            if state.detected_pr_number().is_some() {
                None // PR checkout is self-explanatory
            } else {
                Some(format!("New branch from {}", state.base_branch))
            }
        } else {
            // Existing branch selected
            let branch_cursor = if has_create_row {
                state.cursor.checked_sub(1)
            } else {
                Some(state.cursor)
            };
            let filtered = state.filtered();
            branch_cursor
                .and_then(|bc| filtered.get(bc))
                .map(|&idx| format!("Worktree for existing branch '{}'", state.branches[idx]))
        };
        if let Some(hint) = hint {
            lines.push(Line::from(vec![Span::styled(
                format!(" {}", hint),
                Style::default().fg(palette.dimmed),
            )]));
        } else {
            lines.push(Line::from(""));
        }
    } else {
        lines.push(Line::from(""));
    }

    // Footer (mode-dependent)
    if is_pr_mode {
        lines.push(Line::from(vec![
            Span::raw(" "),
            bold("Enter"),
            dim(" checkout  "),
            bold("^p"),
            dim(" branches  "),
            bold("Esc"),
            dim(" cancel"),
        ]));
    } else {
        lines.push(Line::from(vec![
            Span::raw(" "),
            bold("Enter"),
            dim(" select  "),
            bold("^b"),
            dim(" base  "),
            bold("^p"),
            dim(" PRs  "),
            bold("Esc"),
            dim(" cancel"),
        ]));
    }
    lines.push(Line::from(""));

    let popup_area = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width: width.min(area.width),
        height: height.min(area.height),
    };

    // Title and bottom border
    let title_text = if is_pr_mode {
        "Checkout PR"
    } else {
        "Add Worktree"
    };

    let mut block = Block::bordered()
        .border_type(ratatui::widgets::BorderType::Rounded)
        .border_style(Style::default().fg(palette.help_border))
        .title(Line::from(vec![
            Span::styled(" ", Style::default()),
            Span::styled(
                title_text,
                Style::default()
                    .fg(palette.header)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" ", Style::default()),
        ]));

    // Show base branch on bottom border only in branch mode
    if !is_pr_mode {
        let base_title = if state.editing_base {
            Line::from(vec![
                Span::styled(" Base: ", Style::default().fg(palette.dimmed)),
                Span::styled(
                    state.base_filter.clone(),
                    Style::default().fg(palette.accent),
                ),
                Span::styled("_ ", Style::default().fg(palette.accent)),
            ])
        } else {
            Line::from(vec![
                Span::styled(" Base: ", Style::default().fg(palette.dimmed)),
                Span::styled(
                    format!("{} ", state.base_branch),
                    Style::default().fg(palette.text),
                ),
            ])
        };
        block = block.title_bottom(base_title);
    }

    let paragraph = Paragraph::new(Text::from(lines)).block(block);

    f.render_widget(Clear, popup_area);
    f.render_widget(paragraph, popup_area);
}