gitlab-tracker 0.4.2

A fast terminal TUI dashboard for tracking GitLab Merge Requests across branches
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
pub mod help_popup;
pub mod inspector;
pub mod table;
pub mod theme;
pub mod tracker;

use crate::app::{
    ActivePane, App, InputMode, InspectorView, LogTimeField, SortColumn, SortOrder, TrackerView,
};
use help_popup::render_help_popup;

use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style, Stylize},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap},
    Frame,
};

/// Returns the border style to apply to a pane based on whether it is active.
///
/// Active pane gets a highlighted (cyan) border so the user knows where focus is.
fn pane_border_style(is_active: bool) -> Style {
    if is_active {
        Style::default().fg(Color::Cyan)
    } else {
        Style::default()
    }
}

pub fn render_ui(f: &mut Frame, app: &mut App) {
    // Bump the frame counter on every render so the spinner animates at full frame rate,
    // independently of the 1-second tick timer.
    app.spinner_frame = app.spinner_frame.wrapping_add(1);

    let chunks = Layout::default()
        .constraints([Constraint::Min(3), Constraint::Length(3)])
        .split(f.area());

    let main_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(65), Constraint::Percentage(35)])
        .split(chunks[0]);

    // --- Left Pane: Main Table ---
    let table = table::render_table(app, main_chunks[0]);
    f.render_stateful_widget(table, main_chunks[0], &mut app.table_state);

    // --- Right Column: split vertically when a tracker ticket is available ---
    let has_ticket = app
        .table_state
        .selected()
        .and_then(|i| app.mrs.get(i))
        .and_then(|mr| mr.linked_ticket.as_ref())
        .is_some();

    let right_chunks = if has_ticket {
        // 2/3 Inspector (top) + 1/3 Tracker (bottom)
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Percentage(67), Constraint::Percentage(33)])
            .split(main_chunks[1])
    } else {
        // Full height for Inspector only
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Percentage(100)])
            .split(main_chunks[1])
    };

    let inspector_area = right_chunks[0];
    let tracker_area = if has_ticket {
        Some(right_chunks[1])
    } else {
        None
    };

    // --- Inspector Pane (upper-right) ---
    let inspector_is_active = app.active_pane == ActivePane::Inspector;
    let inspector_title = match (inspector_is_active, app.inspector_view) {
        (true, InspectorView::MrInfo) => " MR Inspector [FOCUS] │ [P]: Pipelines ",
        (false, InspectorView::MrInfo) => " MR Inspector │ [P]: Pipelines ",
        (true, InspectorView::Pipelines) => " Pipelines [FOCUS] │ [P]: MR Info ",
        (false, InspectorView::Pipelines) => " Pipelines │ [P]: MR Info ",
    };
    let inspector_block = Block::default()
        .borders(Borders::ALL)
        .border_style(pane_border_style(inspector_is_active))
        .title(inspector_title);

    // Render the Inspector panel by borrowing the selected MR from the *filtered* list.
    //
    // Pattern: all reads from `app` (via the immutable borrow held by visible_mrs()) and
    // the rendering of Text<'static> happen inside a tight inner scope `{}`. Because
    // Text<'static> owns its content, it outlives the borrow — so once the scope ends the
    // iterator is dropped and `app` is free to be mutated (content_lines / pane_height).
    let inspector_render: Option<(ratatui::text::Text<'static>, u16)> =
        app.table_state.selected().and_then(|i| {
            let mr = app.visible_mrs().nth(i)?;
            let text = match app.inspector_view {
                InspectorView::MrInfo => inspector::render_safe_inspector_text(mr, &app.config),
                InspectorView::Pipelines => inspector::render_pipelines_text(mr),
            };
            let line_count = text.lines.len() as u16;
            Some((text, line_count))
        });

    match inspector_render {
        Some((rendered_text, line_count)) => {
            app.inspector_content_lines = line_count;
            app.inspector_pane_height = inspector_area.height.saturating_sub(2);

            let inspector_paragraph = Paragraph::new(rendered_text)
                .block(inspector_block)
                .wrap(Wrap { trim: false })
                .scroll((app.inspector_scroll, 0));
            f.render_widget(inspector_paragraph, inspector_area);
        }
        None if app.table_state.selected().is_some() => {
            f.render_widget(
                Paragraph::new("Selected metadata unavailable.").block(inspector_block),
                inspector_area,
            );
        }
        None => {
            f.render_widget(
                Paragraph::new(
                    "Select an active Merge Request row to display side inspector panels context.",
                )
                .block(inspector_block)
                .dark_gray(),
                inspector_area,
            );
        }
    }

    // --- Tracker Pane (lower-right) — only when a ticket is linked ---
    if let Some(area) = tracker_area {
        // Same borrow-scope pattern: render Text<'static> inside the closure so the
        // immutable borrow on `app` ends before we write tracker_content_lines / pane_height.
        let tracker_render: Option<(ratatui::text::Text<'static>, u16, bool)> =
            app.table_state.selected().and_then(|i| {
                let mr = app.visible_mrs().nth(i)?;
                let tracker_is_active = app.active_pane == ActivePane::Tracker;
                let text = match app.tracker_view {
                    TrackerView::TicketInfo => tracker::render_ticket_info(mr, &app.tracker_colors),
                    TrackerView::TimeLog => tracker::render_time_log(mr, &app.time_entries),
                };
                let line_count = text.lines.len() as u16;
                Some((text, line_count, tracker_is_active))
            });

        if let Some((rendered_text, line_count, tracker_is_active)) = tracker_render {
            let tracker_title = match (tracker_is_active, app.tracker_view) {
                (true, TrackerView::TicketInfo) => {
                    " Tracker [FOCUS] │ [P]: Time Log │ [L]: Log Time │ [T]: Open URL "
                }
                (false, TrackerView::TicketInfo) => " Tracker │ [T]: Focus ",
                (true, TrackerView::TimeLog) => {
                    " Time Log [FOCUS] │ [P]: Ticket Info │ [L]: Log Time "
                }
                (false, TrackerView::TimeLog) => " Time Log │ [T]: Focus ",
            };

            let tracker_block = Block::default()
                .borders(Borders::ALL)
                .border_style(pane_border_style(tracker_is_active))
                .title(tracker_title);

            app.tracker_content_lines = line_count;
            app.tracker_pane_height = area.height.saturating_sub(2);

            let tracker_paragraph = Paragraph::new(rendered_text)
                .block(tracker_block)
                .wrap(Wrap { trim: false })
                .scroll((app.tracker_scroll, 0));
            f.render_widget(tracker_paragraph, area);
        }
    }

    let sort_status = match (app.sort_column, app.sort_order) {
        (SortColumn::UpdatedAt, SortOrder::Ascending) => "Sort: Updated ▲",
        (SortColumn::UpdatedAt, SortOrder::Descending) => "Sort: Updated ▼",
        (SortColumn::Id, SortOrder::Ascending) => "Sort: ID ▲",
        (SortColumn::Id, SortOrder::Descending) => "Sort: ID ▼",
        (SortColumn::Milestone, SortOrder::Ascending) => "Sort: Milestone ▲",
        (SortColumn::Milestone, SortOrder::Descending) => "Sort: Milestone ▼",
        (SortColumn::Title, SortOrder::Ascending) => "Sort: Title ▲",
        (SortColumn::Title, SortOrder::Descending) => "Sort: Title ▼",
    };

    // --- Bottom Input Bar ---
    let pane_hint = match app.active_pane {
        ActivePane::Dashboard => "Pane: Dashboard",
        ActivePane::Inspector => "Pane: Inspector",
        ActivePane::Tracker => "Pane: Tracker",
    };
    // The input bar title and border change depending on whether the field has focus.
    let (input_title, input_border_style) = match app.input_mode {
        InputMode::Editing if !app.milestone_suggestions.is_empty() => (
            " MILESTONE │ [↑/↓ Tab]: Navigate │ [Enter]: Bulk-add MRs │ [Esc]: Close ".to_string(),
            Style::default().fg(Color::Yellow),
        ),
        InputMode::Editing => (
            " INSERT │ MR ID, branch name, or @milestone │ [Enter]: Confirm │ [Esc]: Cancel ".to_string(),
            Style::default().fg(Color::Yellow),
        ),
        InputMode::ColumnPicker => (
            " COLUMNS │ [↑/↓]: Navigate │ [Space]: Toggle │ [Esc]: Close & Save ".to_string(),
            Style::default().fg(Color::Cyan),
        ),
        InputMode::Normal if app.quit_confirm => (
            " Quit? Press [Esc] or [y] to confirm, any other key to cancel ".to_string(),
            Style::default().fg(Color::Red),
        ),
        InputMode::Normal => (
            format!(
                " [i] or [/]: Insert mode │ [Tab]: {} │ [S/s]: {} │ [F]: Filter │ [Space]: Flag │ [C]: Columns │ [▲/▼]: Scroll │ [O]: Open │ [R]: Refresh │ [Del]: Delete │ [?]: Help │ [Esc]: Quit ",
                pane_hint, sort_status
            ),
            Style::default(),
        ),
        InputMode::FilterPicker => (
            " FILTER │ [↑/↓]: Navigate │ [Enter]: Apply │ [Esc]: Cancel ".to_string(),
            Style::default().fg(Color::Green),
        ),
        // The Log Time popup handles its own rendering — the input bar is hidden behind it.
        // We still need to cover this arm to satisfy exhaustiveness.
        InputMode::LogTime => (
            " LOG TIME │ [Tab]: Next field │ [Enter]: Submit │ [Esc]: Cancel ".to_string(),
            Style::default().fg(Color::Magenta),
        ),
        // The Help popup covers the full screen — the input bar is hidden behind it.
        InputMode::Help => (
            " HELP │ [any key]: Close ".to_string(),
            Style::default().fg(Color::Cyan),
        ),
    };

    let input_box = Paragraph::new(app.input.as_str()).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(input_border_style)
            .title(input_title),
    );
    f.render_widget(input_box, chunks[1]);

    // Render the column-picker popup on top of the UI when active.
    if app.input_mode == InputMode::ColumnPicker {
        render_column_picker(f, app, f.area());
    }

    // Render the filter picker popup on top of the UI when active.
    if app.input_mode == InputMode::FilterPicker {
        render_filter_picker(f, app, f.area());
    }

    // Render the milestone autocomplete dropdown above the input bar when suggestions exist.
    if app.input_mode == InputMode::Editing && !app.milestone_suggestions.is_empty() {
        render_milestone_autocomplete(f, app, chunks[1]);
    }

    // Render the Log Time popup on top of everything when active.
    if app.input_mode == InputMode::LogTime {
        render_log_time_popup(f, app, f.area());
    }

    // Render the help popup on top of everything when active.
    if app.input_mode == InputMode::Help {
        render_help_popup(f, app);
    }
}

/// Renders the Log Time popup centred over the terminal.
///
/// The popup is a modal overlay using [`Clear`] so it erases whatever is beneath.
/// Layout (top→bottom):
///   1. Duration text field
///   2. Activity selector list (scrollable)
///   3. Comment text field
///   4. Error line (when present) + shortcut hint
fn render_log_time_popup(f: &mut Frame, app: &App, area: Rect) {
    use ratatui::widgets::List;

    // Ticket context for the popup title.
    let ticket_label = app
        .table_state
        .selected()
        .and_then(|i| app.visible_mrs().nth(i))
        .and_then(|mr| mr.linked_ticket.as_ref())
        .map(|t| format!(" ⏱  Log Time — #{} ", t.id))
        .unwrap_or_else(|| " ⏱  Log Time ".to_string());

    // Fixed popup dimensions.
    let popup_width: u16 = 60;
    // Base height: title(1) + duration(3) + activity list (up to 6 visible) + comment(3) +
    // error/hint(2) + borders(2) = 17 rows max
    let activity_rows = (app.activities.len() as u16).clamp(2, 6);
    let popup_height: u16 = 3 + activity_rows + 3 + 2 + 2;

    let popup_x = area.x + area.width.saturating_sub(popup_width) / 2;
    let popup_y = area.y + area.height.saturating_sub(popup_height) / 2;
    let popup_area = Rect::new(popup_x, popup_y, popup_width, popup_height);

    f.render_widget(Clear, popup_area);

    // Outer border block.
    let outer_block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Magenta))
        .title(Span::styled(
            ticket_label,
            Style::default()
                .fg(Color::Magenta)
                .add_modifier(Modifier::BOLD),
        ));
    f.render_widget(outer_block, popup_area);

    // Inner layout: split vertically into 4 zones inside the border.
    let inner = Rect::new(
        popup_area.x + 1,
        popup_area.y + 1,
        popup_area.width.saturating_sub(2),
        popup_area.height.saturating_sub(2),
    );

    let zones = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),             // Duration field
            Constraint::Length(activity_rows), // Activity selector
            Constraint::Length(3),             // Comment field
            Constraint::Min(1),                // Error / hint line
        ])
        .split(inner);

    // Helper: border colour based on whether the field is focused.
    let field_style = |focused: bool| -> Style {
        if focused {
            Style::default().fg(Color::Yellow)
        } else {
            Style::default().fg(theme::MUTED_HINT)
        }
    };

    // ── Duration field ────────────────────────────────────────────────────────
    let duration_focused = app.log_time_form.focused_field == LogTimeField::Duration;
    let duration_block = Block::default()
        .borders(Borders::ALL)
        .border_style(field_style(duration_focused))
        .title(Span::styled(
            " Duration (e.g. 1h30, 90m, 1.5h) ",
            Style::default().fg(Color::White),
        ));
    let duration_widget = Paragraph::new(app.log_time_form.duration_input.as_str())
        .block(duration_block)
        .style(Style::default().fg(Color::White));
    f.render_widget(duration_widget, zones[0]);

    // ── Activity selector ─────────────────────────────────────────────────────
    let activity_focused = app.log_time_form.focused_field == LogTimeField::Activity;
    let activity_block = Block::default()
        .borders(Borders::ALL)
        .border_style(field_style(activity_focused))
        .title(Span::styled(
            " Activity [↑/↓] ",
            Style::default().fg(Color::White),
        ));

    if app.activities.is_empty() {
        let loading = Paragraph::new("Loading activities…")
            .block(activity_block)
            .style(Style::default().fg(Color::DarkGray));
        f.render_widget(loading, zones[1]);
    } else {
        let cursor = app.log_time_form.selected_activity_idx;
        let visible = activity_rows as usize;
        let scroll_offset = if cursor >= visible {
            cursor + 1 - visible
        } else {
            0
        };

        let items: Vec<ListItem> = app
            .activities
            .iter()
            .enumerate()
            .skip(scroll_offset)
            .take(visible)
            .map(|(i, act)| {
                let selected = i == cursor;
                let style = if selected {
                    Style::default()
                        .fg(Color::Black)
                        .bg(Color::Magenta)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::White)
                };
                ListItem::new(Line::from(Span::styled(format!("  {} ", act.name), style)))
            })
            .collect();

        let list = List::new(items).block(activity_block);
        let mut list_state = ratatui::widgets::ListState::default();
        list_state.select(Some(cursor.saturating_sub(scroll_offset)));
        f.render_stateful_widget(list, zones[1], &mut list_state);
    }

    // ── Comment field ─────────────────────────────────────────────────────────
    let comment_focused = app.log_time_form.focused_field == LogTimeField::Comment;
    let comment_block = Block::default()
        .borders(Borders::ALL)
        .border_style(field_style(comment_focused))
        .title(Span::styled(
            " Comment (optional) ",
            Style::default().fg(Color::White),
        ));
    let comment_widget = Paragraph::new(app.log_time_form.comment_input.as_str())
        .block(comment_block)
        .style(Style::default().fg(Color::White));
    f.render_widget(comment_widget, zones[2]);

    // ── Error / hint line ─────────────────────────────────────────────────────
    let bottom_line = if let Some(err) = &app.log_time_form.error {
        Line::from(vec![
            Span::styled(
                "",
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            ),
            Span::styled(err.clone(), Style::default().fg(Color::Red)),
        ])
    } else if app.log_time_form.submitting {
        Line::from(vec![Span::styled(
            " ⟳ Submitting…",
            Style::default().fg(Color::Yellow),
        )])
    } else {
        Line::from(vec![
            Span::styled(" [Tab] ", Style::default().fg(theme::MUTED_HINT)),
            Span::styled("Next field  ", Style::default().fg(theme::MUTED_HINT)),
            Span::styled("[Enter] ", Style::default().fg(theme::MUTED_HINT)),
            Span::styled("Submit  ", Style::default().fg(theme::MUTED_HINT)),
            Span::styled("[Esc] ", Style::default().fg(theme::MUTED_HINT)),
            Span::styled("Cancel", Style::default().fg(theme::MUTED_HINT)),
        ])
    };
    f.render_widget(Paragraph::new(bottom_line), zones[3]);
}

/// Renders the milestone autocomplete dropdown just above the input bar.
///
/// The popup lists all matching milestone suggestions and highlights the currently
/// selected one. It is anchored to the left edge of the input bar and grows upward
/// so it never overlaps the input field itself.
fn render_milestone_autocomplete(f: &mut Frame, app: &App, input_area: Rect) {
    let suggestions = &app.milestone_suggestions;
    if suggestions.is_empty() {
        return;
    }

    // Cap visible rows to avoid overflowing the screen.
    let max_visible: u16 = 8;
    let visible_count = (suggestions.len() as u16).min(max_visible);
    // +2 for top/bottom borders.
    let popup_height = visible_count + 2;
    let popup_width = (input_area.width / 2).max(40);

    // Anchor to the left of the input bar and grow upward.
    let popup_x = input_area.x;
    let popup_y = input_area.y.saturating_sub(popup_height);
    let popup_area = Rect::new(popup_x, popup_y, popup_width, popup_height);

    f.render_widget(Clear, popup_area);

    // Determine the scroll offset so the selected item is always visible.
    let cursor = app.milestone_suggestion_cursor;
    let scroll_offset = if cursor >= max_visible as usize {
        cursor + 1 - max_visible as usize
    } else {
        0
    };

    let items: Vec<ListItem> = suggestions
        .iter()
        .enumerate()
        .skip(scroll_offset)
        .take(max_visible as usize)
        .map(|(i, title)| {
            let is_selected = i == cursor;
            let style = if is_selected {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Yellow)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            ListItem::new(Line::from(Span::styled(format!("  {} ", title), style)))
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Yellow))
            .title(" Milestones │ [↑/↓ Tab]: Navigate │ [Enter]: Select "),
    );

    let mut list_state = ListState::default();
    list_state.select(Some(cursor.saturating_sub(scroll_offset)));
    f.render_stateful_widget(list, popup_area, &mut list_state);
}

/// Renders the filter picker popup centred over the terminal area.
///
/// Iterates `app.filter_defs` (collected via `inventory` at startup) — no hardcoded
/// index mapping needed. Plugin filters (e.g. Redmine's "Has linked ticket") appear
/// automatically when their crate is linked.
fn render_filter_picker(f: &mut Frame, app: &App, area: Rect) {
    let cursor = app.filter_picker.cursor;
    let needs_text_input = app
        .filter_defs
        .get(cursor)
        .map(|d| d.needs_text_input)
        .unwrap_or(false);

    let list_height = app.filter_defs.len() as u16;
    let input_extra: u16 = if needs_text_input { 3 } else { 0 };
    let popup_height = list_height + 2 + input_extra;
    let popup_width: u16 = 48;

    let popup_x = area.x + area.width.saturating_sub(popup_width) / 2;
    let popup_y = area.y + area.height.saturating_sub(popup_height) / 2;
    let popup_area = Rect::new(popup_x, popup_y, popup_width, popup_height);

    f.render_widget(Clear, popup_area);

    let outer_block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Green))
        .title(Span::styled(
            " Filter ",
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        ));
    f.render_widget(outer_block, popup_area);

    let inner = Rect::new(
        popup_area.x + 1,
        popup_area.y + 1,
        popup_area.width.saturating_sub(2),
        popup_area.height.saturating_sub(2),
    );

    let zones = if needs_text_input {
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(1), Constraint::Length(3)])
            .split(inner)
    } else {
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(1)])
            .split(inner)
    };

    // Pre-compute applicability hints for context-dependent filters.
    let has_any_linked_ticket = app.mrs.iter().any(|mr| mr.linked_ticket.is_some());
    let has_any_pipeline = app.mrs.iter().any(|mr| !mr.pipelines.is_empty());

    let items: Vec<ListItem> = app
        .filter_defs
        .iter()
        .enumerate()
        .map(|(i, def)| {
            let is_active = i == cursor;
            let is_current = i == app.active_filter.index;

            // Dim context-dependent filters when they are not applicable.
            let is_na = match def.id {
                "has_linked_ticket" => !has_any_linked_ticket,
                "ci_failing" => !has_any_pipeline,
                _ => false,
            };

            let prefix = if is_current { "" } else { "  " };
            let display_label = if is_na {
                format!("{}{}  (n/a)", prefix, def.label)
            } else {
                format!("{}{}", prefix, def.label)
            };

            let style = if is_na {
                Style::default().fg(Color::Rgb(90, 90, 90))
            } else if is_active {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Green)
                    .add_modifier(Modifier::BOLD)
            } else if is_current {
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            ListItem::new(Line::from(Span::styled(display_label, style)))
        })
        .collect();

    let list = List::new(items);
    let mut list_state = ListState::default();
    list_state.select(Some(cursor));
    f.render_stateful_widget(list, zones[0], &mut list_state);

    // Text input field for parametric filters (Milestone, Assignee, …).
    if needs_text_input {
        let field_label = app
            .filter_defs
            .get(cursor)
            .map(|d| d.active_label)
            .unwrap_or("Query");
        let input_block = Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Yellow))
            .title(Span::styled(
                format!(" {} ", field_label),
                Style::default().fg(Color::White),
            ));
        let input_widget = Paragraph::new(app.filter_picker.input.as_str())
            .block(input_block)
            .style(Style::default().fg(Color::White));
        f.render_widget(input_widget, zones[1]);
    }
}

/// Renders the column-picker popup centred over the terminal area.
///
/// Iterates `app.column_defs` (collected via `inventory` at startup) — no hardcoded
/// index mapping needed. Plugin columns (e.g. Redmine's "Tracker") appear automatically
/// when their crate is linked and the runtime condition (`requires_feature`) is met.
fn render_column_picker(f: &mut Frame, app: &App, area: Rect) {
    let has_tracker = app.tracker.is_some();

    // Build the visible entry list from registered ColumnDef, filtering out
    // feature-gated columns whose runtime condition is not satisfied.
    let entries: Vec<(&str, bool)> = app
        .column_defs
        .iter()
        .filter(|c| {
            c.requires_feature
                .map(|f| f == "tracker" && has_tracker)
                .unwrap_or(true)
        })
        .map(|c| (c.label, app.config.visible_columns.is_visible(c.id)))
        .collect();

    let popup_width: u16 = 36;
    let popup_height: u16 = entries.len() as u16 + 2;

    let popup_x = area.x + area.width.saturating_sub(popup_width) / 2;
    let popup_y = area.y + area.height.saturating_sub(popup_height) / 2;
    let popup_area = Rect::new(popup_x, popup_y, popup_width, popup_height);

    f.render_widget(Clear, popup_area);

    let items: Vec<ListItem> = entries
        .iter()
        .enumerate()
        .map(|(i, (label, enabled))| {
            let checkbox = if *enabled { "" } else { "" };
            let is_selected = i == app.column_picker_cursor;
            let style = if is_selected {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Cyan)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            ListItem::new(Line::from(vec![
                Span::styled(format!("  {} ", checkbox), style),
                Span::styled(label.to_string(), style),
            ]))
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Cyan))
            .title(" Columns "),
    );

    let mut list_state = ListState::default();
    list_state.select(Some(app.column_picker_cursor));
    f.render_stateful_widget(list, popup_area, &mut list_state);
}