cctakt 0.1.1

TUI orchestrator for multiple Claude Code agents using Git Worktree
Documentation
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
//! TUI rendering functions

use crate::agent::{Agent, AgentMode, AgentStatus, WorkState};
use crate::app::{App, AppMode, FocusedPane, InputMode, ReviewFocus};
use cctakt::{available_themes, current_theme_id, issue_picker::centered_rect, theme};
use ratatui::{
    layout::{Constraint, Direction, Layout},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
    Frame,
};

/// Main UI rendering function
pub fn ui(f: &mut Frame, app: &mut App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Header with tabs
            Constraint::Min(0),    // Main area
            Constraint::Length(2), // Footer with status and keymaps
        ])
        .split(f.area());

    // Header with tabs
    render_header(f, app, chunks[0]);

    // Footer with status
    render_footer(f, app, chunks[2]);

    // Main area
    if app.agent_manager.is_empty() {
        render_no_agent_menu(f, chunks[1]);
    } else {
        render_split_pane_main_area(f, app, chunks[1]);
    }

    // Render overlays based on mode
    match app.mode {
        AppMode::IssuePicker => {
            let popup_area = centered_rect(80, 70, f.area());
            app.issue_picker.render(f, popup_area);
        }
        AppMode::ThemePicker => {
            render_theme_picker(f, app, f.area());
        }
        AppMode::ReviewMerge | AppMode::Normal => {}
    }

    // Render notifications at the bottom
    if !app.notifications.is_empty() {
        render_notifications(f, app, f.area());
    }
}

/// Render notifications at the bottom of the screen
pub fn render_notifications(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let notification_count = app.notifications.len().min(3); // Show max 3 notifications
    if notification_count == 0 {
        return;
    }

    let height = notification_count as u16 + 2; // +2 for borders
    let notification_area = ratatui::layout::Rect {
        x: area.x + 2,
        y: area.height.saturating_sub(height + 1),
        width: area.width.saturating_sub(4).min(60),
        height,
    };

    let t = theme();
    let lines: Vec<Line> = app
        .notifications
        .iter()
        .rev()
        .take(3)
        .map(|n| {
            let (prefix, style) = match n.level {
                cctakt::plan::NotifyLevel::Info => ("", t.style_info()),
                cctakt::plan::NotifyLevel::Warning => ("", t.style_warning()),
                cctakt::plan::NotifyLevel::Error => ("", t.style_error()),
                cctakt::plan::NotifyLevel::Success => ("", t.style_success()),
            };
            Line::from(vec![
                Span::styled(format!(" {prefix} "), style),
                Span::raw(&n.message),
            ])
        })
        .collect();

    let notification_widget = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(t.style_border_muted()),
    );

    f.render_widget(Clear, notification_area);
    f.render_widget(notification_widget, notification_area);
}

/// Render theme picker modal
pub fn render_theme_picker(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let t = theme();
    let themes = available_themes();
    let current_theme_id_str = current_theme_id().id();

    // Calculate popup size
    let popup_width = 40u16;
    let popup_height = (themes.len() as u16) + 6; // title + items + footer + borders

    // Center the popup
    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 = ratatui::layout::Rect {
        x: popup_x,
        y: popup_y,
        width: popup_width.min(area.width),
        height: popup_height.min(area.height),
    };

    // Clear the popup area
    f.render_widget(Clear, popup_area);

    // Build theme list
    let mut lines: Vec<Line> = vec![Line::from("")];

    for (i, (id, name, description)) in themes.iter().enumerate() {
        let is_selected = i == app.theme_picker_index;
        let is_current = *id == current_theme_id_str;

        let prefix = if is_selected { " > " } else { "   " };
        let suffix = if is_current { "" } else { "" };

        let style = if is_selected {
            Style::default()
                .fg(t.neon_cyan())
                .add_modifier(Modifier::BOLD)
        } else if is_current {
            Style::default().fg(t.neon_green())
        } else {
            t.style_text()
        };

        lines.push(Line::from(vec![
            Span::styled(prefix, style),
            Span::styled(*name, style),
            Span::styled(suffix, Style::default().fg(t.neon_green())),
        ]));

        // Show description for selected item
        if is_selected {
            lines.push(Line::from(vec![
                Span::raw("     "),
                Span::styled(*description, t.style_text_muted()),
            ]));
        }
    }

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

    // Footer
    lines.push(Line::from(vec![
        Span::styled(" Enter", t.style_key()),
        Span::styled(": Select  ", t.style_key_desc()),
        Span::styled("Esc", t.style_key()),
        Span::styled(": Cancel", t.style_key_desc()),
    ]));

    let block = Block::default()
        .title(Span::styled(
            " テーマを選択 ",
            Style::default()
                .fg(t.neon_cyan())
                .add_modifier(Modifier::BOLD),
        ))
        .borders(Borders::ALL)
        .border_style(t.style_dialog_border())
        .style(t.style_dialog_bg());

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

/// Render review merge screen with split panes (summary on top, diff on bottom)
pub fn render_review_merge(f: &mut Frame, app: &mut App, area: ratatui::layout::Rect) {
    let Some(ref mut state) = app.review_state else {
        return;
    };

    let t = theme();

    // Clear the area first
    f.render_widget(Clear, area);

    // Layout: summary (top) + diff (bottom) + footer
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(35), // Summary pane (commit log/stats)
            Constraint::Percentage(65), // Diff pane
            Constraint::Length(1),      // Footer with help
        ])
        .split(area);

    // Determine focus colors
    let summary_focused = state.focus == ReviewFocus::Summary;
    let diff_focused = state.focus == ReviewFocus::Diff;

    let summary_border_color = if summary_focused {
        t.neon_cyan()
    } else {
        t.border_secondary()
    };
    let diff_border_color = if diff_focused {
        t.neon_cyan()
    } else {
        t.border_secondary()
    };

    // === Summary pane (top) ===
    render_summary_pane(f, state, chunks[0], summary_border_color);

    // === Diff pane (bottom) ===
    let diff_block = Block::default()
        .title(format!(" Diff: {} → main ", state.branch))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(diff_border_color));
    state.diff_view.render_with_block(f, chunks[1], diff_block);

    // Footer with help
    let footer = Paragraph::new(Line::from(vec![
        Span::styled("[i/Enter]", t.style_key()),
        Span::styled(" Focus  ", t.style_text_muted()),
        Span::styled("[j/k]", t.style_key()),
        Span::styled(" Scroll  ", t.style_text_muted()),
        Span::styled("[M]", t.style_success()),
        Span::styled(" Merge  ", t.style_text_muted()),
        Span::styled("[Q/C]", t.style_error()),
        Span::styled(" Cancel", t.style_text_muted()),
    ]));
    f.render_widget(footer, chunks[2]);
}

/// Render the summary pane showing commit log and stats
fn render_summary_pane(
    f: &mut Frame,
    state: &crate::app::types::ReviewState,
    area: ratatui::layout::Rect,
    border_color: Color,
) {
    let t = theme();

    // Build summary lines
    let mut lines: Vec<Line> = vec![];

    // Title line
    lines.push(Line::from(vec![
        Span::styled(
            " Review Merge: ",
            Style::default()
                .fg(t.neon_cyan())
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(&state.branch, Style::default().fg(t.neon_yellow())),
        Span::raw(""),
        Span::styled("main", Style::default().fg(t.success())),
    ]));

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

    // Stats line
    lines.push(Line::from(vec![
        Span::raw(" Stats: "),
        Span::styled(format!("{} files", state.files_changed), t.style_text()),
        Span::raw(", "),
        Span::styled(
            format!("+{}", state.insertions),
            Style::default().fg(t.success()),
        ),
        Span::raw(" / "),
        Span::styled(
            format!("-{}", state.deletions),
            Style::default().fg(t.error()),
        ),
    ]));

    // Show conflicts warning if any
    if !state.conflicts.is_empty() {
        lines.push(Line::from(vec![
            Span::styled(" ⚠ Potential conflicts: ", t.style_warning()),
            Span::styled(state.conflicts.join(", "), t.style_warning()),
        ]));
    }

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

    // Commit log header
    lines.push(Line::from(vec![Span::styled(
        " Commits:",
        Style::default()
            .fg(t.neon_cyan())
            .add_modifier(Modifier::BOLD),
    )]));

    // Add commit log lines (scrollable)
    let content_height = area.height.saturating_sub(2) as usize; // -2 for borders
    let log_lines: Vec<&str> = state.commit_log.lines().collect();
    let start = state.summary_scroll as usize;
    let visible_log_lines = log_lines
        .iter()
        .skip(start)
        .take(content_height.saturating_sub(lines.len()));

    for log_line in visible_log_lines {
        // Format commit lines with colors
        let styled_line = if log_line.starts_with("  ") {
            // Commit message (indented)
            Line::from(Span::styled(
                log_line.to_string(),
                t.style_text_secondary(),
            ))
        } else if log_line.contains(' ') {
            // Commit hash and title
            let parts: Vec<&str> = log_line.splitn(2, ' ').collect();
            if parts.len() == 2 {
                Line::from(vec![
                    Span::styled(
                        format!(" {} ", parts[0]),
                        Style::default().fg(t.neon_yellow()),
                    ),
                    Span::styled(parts[1].to_string(), t.style_text()),
                ])
            } else {
                Line::from(Span::styled(format!(" {log_line}"), t.style_text()))
            }
        } else {
            Line::from(Span::styled(format!(" {log_line}"), t.style_text()))
        };
        lines.push(styled_line);
    }

    let summary_block = Block::default()
        .title(" Summary ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(border_color));

    let summary_widget = Paragraph::new(lines).block(summary_block);
    f.render_widget(summary_widget, area);
}

/// Render header with tabs
pub fn render_header(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let t = theme();
    let mut spans: Vec<Span> = vec![
        Span::styled(
            " cctakt ",
            Style::default()
                .fg(t.tab_active_fg())
                .bg(t.neon_pink())
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            concat!("v", env!("CARGO_PKG_VERSION"), " "),
            t.style_text_muted(),
        ),
    ];

    let agents = app.agent_manager.list();
    let active_index = app.agent_manager.active_index();

    for (i, agent) in agents.iter().enumerate() {
        let is_active = i == active_index;
        let is_ended = agent.status == AgentStatus::Ended;

        let tab_content = format!(" [{}:{}] ", i + 1, agent.name);

        let style = if is_active {
            t.style_tab_active()
        } else if is_ended {
            Style::default().fg(t.status_ended())
        } else {
            t.style_tab_inactive()
        };

        spans.push(Span::styled(tab_content, style));
    }

    let header = Paragraph::new(Line::from(spans));
    f.render_widget(header, area);
}

/// Render footer with agent status and key bindings
pub fn render_footer(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let t = theme();

    // Count agents by work state
    let agents = app.agent_manager.list();
    let mut running_count = 0;
    let mut idle_count = 0;
    let mut completed_count = 0;

    for agent in agents {
        match agent.work_state {
            WorkState::Starting | WorkState::Working => running_count += 1,
            WorkState::Idle => idle_count += 1,
            WorkState::Completed => completed_count += 1,
        }
    }

    let total_agents = agents.len();

    // Build left side: agent status
    let mut left_spans: Vec<Span> = vec![];

    if total_agents > 0 {
        left_spans.push(Span::styled(
            format!(" Agents: {total_agents} "),
            t.style_text_muted(),
        ));
        left_spans.push(Span::styled(
            format!("Running: {running_count}"),
            if running_count > 0 {
                t.style_warning()
            } else {
                t.style_text_muted()
            },
        ));
        left_spans.push(Span::styled(" | ", t.style_text_muted()));
        left_spans.push(Span::styled(
            format!("Idle: {idle_count}"),
            if idle_count > 0 {
                t.style_info()
            } else {
                t.style_text_muted()
            },
        ));
        left_spans.push(Span::styled(" | ", t.style_text_muted()));
        left_spans.push(Span::styled(
            format!("Completed: {completed_count}"),
            if completed_count > 0 {
                t.style_success()
            } else {
                t.style_text_muted()
            },
        ));

        // Calculate total cost and turns from non-interactive agents
        let (total_cost, total_turns) = agents
            .iter()
            .filter(|a| a.mode == AgentMode::NonInteractive)
            .fold((0.0, 0u32), |(cost, turns), agent| {
                (
                    cost + agent.cost_usd.unwrap_or(0.0),
                    turns + agent.num_turns.unwrap_or(0),
                )
            });

        // Display usage info if there's any cost or turns
        if total_cost > 0.0 || total_turns > 0 {
            left_spans.push(Span::styled(" | ", t.style_text_muted()));
            left_spans.push(Span::styled(
                if total_cost < 0.01 {
                    "<$0.01".to_string()
                } else {
                    format!("${:.2}", total_cost)
                },
                Style::default().fg(t.neon_yellow()),
            ));
            if total_turns > 0 {
                left_spans.push(Span::styled(
                    format!(" ({} turns)", total_turns),
                    t.style_text_muted(),
                ));
            }
        }
    }

    // Add input mode indicator
    left_spans.push(Span::styled(" | ", t.style_text_muted()));
    let (mode_text, mode_style) = match app.input_mode {
        InputMode::Navigation => ("NAV(i:入力 ::cmd)", t.style_warning()),
        InputMode::Input => ("INS(Esc:移動)", t.style_success()),
        InputMode::Command => {
            // Show command buffer
            let cmd_display = format!(":{}", app.command_buffer);
            left_spans.push(Span::styled(cmd_display, t.style_success()));
            ("", t.style_text_muted()) // Empty since we already added the command
        }
    };
    if !mode_text.is_empty() {
        left_spans.push(Span::styled(mode_text, mode_style));
    }

    // Add focused pane indicator
    let pane_text = match app.focused_pane {
        FocusedPane::Left => " [←]",
        FocusedPane::Right => " [→]",
    };
    left_spans.push(Span::styled(pane_text, t.style_text_muted()));

    // Build right side: plan status (if any)
    let mut right_spans: Vec<Span> = vec![];

    // Plan status
    if let Some(ref plan) = app.current_plan {
        let (pending, running, completed, failed) = plan.count_by_status();
        let total = plan.tasks.len();
        let plan_style = if failed > 0 {
            t.style_error()
        } else if running > 0 {
            t.style_warning()
        } else {
            t.style_success()
        };
        right_spans.push(Span::styled(
            format!("Plan: {completed}/{total} "),
            plan_style,
        ));
        // Mark pending as unused to suppress warning
        let _ = pending;
    }

    // Calculate widths for left/right alignment (line 1: status)
    let left_text: String = left_spans.iter().map(|s| s.content.as_ref()).collect();
    let right_text: String = right_spans.iter().map(|s| s.content.as_ref()).collect();
    let left_width = left_text.len();
    let right_width = right_text.len();
    let available_width = area.width as usize;

    // Build line 1 (status) with padding
    let mut line1_spans = left_spans;
    let padding = available_width.saturating_sub(left_width + right_width);
    if padding > 0 {
        line1_spans.push(Span::raw(" ".repeat(padding)));
    }
    line1_spans.extend(right_spans);
    let line1 = Line::from(line1_spans);

    // Build line 2 (keymaps)
    let keymap_spans = vec![Span::styled(
        " [^T:new ^I:issue ^W:close ^N/^P:switch ^Q:quit]",
        t.style_text_muted(),
    )];
    let line2 = Line::from(keymap_spans);

    let footer = Paragraph::new(vec![line1, line2]).style(Style::default().bg(t.bg_surface()));
    f.render_widget(footer, area);
}

/// Render menu when no agents exist
/// Render the main area with split panes for Interactive (left) and NonInteractive (right) agents
pub fn render_split_pane_main_area(f: &mut Frame, app: &mut App, area: ratatui::layout::Rect) {
    let interactive = app.agent_manager.get_interactive();
    let active_worker = app.agent_manager.get_active_non_interactive();
    let is_review_mode = app.mode == AppMode::ReviewMerge;

    match (interactive, active_worker, is_review_mode) {
        // ReviewMerge mode with orchestrator: show orchestrator on left, review UI on right
        (Some(orchestrator), _, true) => {
            let t = theme();

            // Split horizontally: left 50% for orchestrator, 1 column for border, right 50% for review
            let main_chunks = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([
                    Constraint::Percentage(50),
                    Constraint::Length(1), // vertical separator
                    Constraint::Percentage(50),
                ])
                .split(area);

            // Left pane: Interactive (orchestrator) - no focus color in review mode
            if orchestrator.status == AgentStatus::Ended {
                render_ended_agent(f, orchestrator, main_chunks[0], None);
            } else {
                render_agent_screen(f, orchestrator, main_chunks[0], None);
            }

            // Vertical separator
            let separator_lines: Vec<Line> = (0..main_chunks[1].height)
                .map(|_| Line::from(""))
                .collect();
            let separator =
                Paragraph::new(separator_lines).style(Style::default().fg(t.border_secondary()));
            f.render_widget(separator, main_chunks[1]);

            // Right pane: Review UI
            render_review_merge(f, app, main_chunks[2]);
        }
        // ReviewMerge mode without orchestrator: full width for review UI
        (None, _, true) => {
            render_review_merge(f, app, area);
        }
        // Both Interactive and NonInteractive agents exist: split pane layout
        (Some(orchestrator), Some(worker), false) => {
            let t = theme();
            let left_focused = app.focused_pane == FocusedPane::Left;
            let right_focused = app.focused_pane == FocusedPane::Right;

            // Determine focus colors
            let left_focus_color = if left_focused {
                Some(t.neon_cyan())
            } else {
                None
            };
            let right_focus_color = if right_focused {
                Some(t.neon_pink())
            } else {
                None
            };

            // Split horizontally: left 50% for orchestrator, 1 column for border, right 50% for worker
            let main_chunks = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([
                    Constraint::Percentage(50),
                    Constraint::Length(1), // vertical separator
                    Constraint::Percentage(50),
                ])
                .split(area);

            // Left pane: Interactive (orchestrator)
            if orchestrator.status == AgentStatus::Ended {
                render_ended_agent(f, orchestrator, main_chunks[0], left_focus_color);
            } else {
                render_agent_screen(f, orchestrator, main_chunks[0], left_focus_color);
            }

            // Vertical separator - highlight based on focus
            let separator_color = if left_focused || right_focused {
                if left_focused {
                    t.neon_cyan()
                } else {
                    t.neon_pink()
                }
            } else {
                t.border_secondary()
            };
            let separator_lines: Vec<Line> = (0..main_chunks[1].height)
                .map(|_| Line::from(""))
                .collect();
            let separator =
                Paragraph::new(separator_lines).style(Style::default().fg(separator_color));
            f.render_widget(separator, main_chunks[1]);

            // Right pane: NonInteractive (worker)
            if worker.status == AgentStatus::Ended {
                render_ended_agent(f, worker, main_chunks[2], right_focus_color);
            } else {
                render_agent_screen(f, worker, main_chunks[2], right_focus_color);
            }
        }
        // Only Interactive agent: full width for orchestrator (always highlighted as single pane)
        (Some(orchestrator), None, false) => {
            let t = theme();
            let focus_color = Some(t.neon_cyan());
            if orchestrator.status == AgentStatus::Ended {
                render_ended_agent(f, orchestrator, area, focus_color);
            } else {
                render_agent_screen(f, orchestrator, area, focus_color);
            }
        }
        // Only NonInteractive agents: full width for worker (always highlighted as single pane)
        (None, Some(worker), false) => {
            let t = theme();
            let focus_color = Some(t.neon_pink());
            if worker.status == AgentStatus::Ended {
                render_ended_agent(f, worker, area, focus_color);
            } else {
                render_agent_screen(f, worker, area, focus_color);
            }
        }
        // No agents (shouldn't happen, but handle gracefully)
        (None, None, false) => {
            render_no_agent_menu(f, area);
        }
    }
}

pub fn render_no_agent_menu(f: &mut Frame, area: ratatui::layout::Rect) {
    let t = theme();
    let menu = Paragraph::new(vec![
        Line::from(""),
        Line::from("  No active agents."),
        Line::from(""),
        Line::from(vec![
            Span::styled("  [N]", t.style_success()),
            Span::raw(" New agent"),
        ]),
        Line::from(vec![
            Span::styled("  [I/F2]", t.style_info()),
            Span::raw(" New agent from GitHub issue"),
        ]),
        Line::from(vec![
            Span::styled("  [Q]", t.style_error()),
            Span::raw(" Quit cctakt"),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "  Press N, I, or Q...",
            t.style_text_muted(),
        )),
    ])
    .block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(t.style_border_muted()),
    );
    f.render_widget(menu, area);
}

/// Render ended agent menu
/// `focus_color`: Some(Color) to highlight border with that color, None for muted border
pub fn render_ended_agent(
    f: &mut Frame,
    agent: &Agent,
    area: ratatui::layout::Rect,
    focus_color: Option<Color>,
) {
    let t = theme();
    let border_style = match focus_color {
        Some(color) => Style::default().fg(color),
        None => t.style_border_muted(),
    };
    let ended_message = if let Some(ref branch) = agent.branch {
        format!("  Agent '{}' session ended. ({})", agent.name, branch)
    } else {
        format!("  Agent '{}' session ended.", agent.name)
    };
    let menu = Paragraph::new(vec![
        Line::from(""),
        Line::from(ended_message),
        Line::from(""),
        Line::from(vec![
            Span::styled("  [Ctrl+W]", t.style_warning()),
            Span::raw(" Close this tab"),
        ]),
        Line::from(vec![
            Span::styled("  [Ctrl+N/P]", Style::default().fg(t.neon_blue())),
            Span::raw(" Switch to another tab"),
        ]),
        Line::from(vec![
            Span::styled("  [Ctrl+Q]", t.style_error()),
            Span::raw(" Quit"),
        ]),
        Line::from(""),
    ])
    .block(
        Block::default()
            .borders(Borders::ALL)
            .title(format!(" {} (ended) ", agent.name))
            .border_style(border_style),
    );
    f.render_widget(menu, area);
}

/// Render active agent's screen (handles both interactive and non-interactive modes)
/// `focus_color`: Some(Color) to highlight border with that color, None for muted border
pub fn render_agent_screen(
    f: &mut Frame,
    agent: &Agent,
    area: ratatui::layout::Rect,
    focus_color: Option<Color>,
) {
    match agent.mode {
        AgentMode::Interactive => {
            render_agent_screen_interactive(f, agent, area, focus_color);
        }
        AgentMode::NonInteractive => {
            render_agent_screen_non_interactive(f, agent, area, focus_color);
        }
    }
}

/// Render interactive (PTY) agent screen with vt100 colors
/// `focus_color`: Some(Color) to highlight border with that color, None for muted border
pub fn render_agent_screen_interactive(
    f: &mut Frame,
    agent: &Agent,
    area: ratatui::layout::Rect,
    focus_color: Option<Color>,
) {
    let t = theme();
    let border_style = match focus_color {
        Some(color) => Style::default().fg(color),
        None => t.style_border_muted(),
    };
    let Some(parser_arc) = agent.get_parser() else {
        // Fallback if no parser
        let widget = Paragraph::new("No parser available").block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(border_style),
        );
        f.render_widget(widget, area);
        return;
    };

    let parser = parser_arc.lock().unwrap();
    let screen = parser.screen();

    let content_height = area.height.saturating_sub(2) as usize;
    let content_width = area.width.saturating_sub(2) as usize;

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

    for row in 0..content_height {
        let mut spans: Vec<Span> = Vec::new();
        let mut current_text = String::new();
        let mut current_style = Style::default();

        for col in 0..content_width {
            let cell = screen.cell(row as u16, col as u16);
            if let Some(cell) = cell {
                let cell_style = cell_to_style(cell);

                if cell_style != current_style {
                    if !current_text.is_empty() {
                        spans.push(Span::styled(current_text.clone(), current_style));
                        current_text.clear();
                    }
                    current_style = cell_style;
                }

                current_text.push_str(&cell.contents());
            }
        }

        if !current_text.is_empty() {
            spans.push(Span::styled(current_text, current_style));
        }

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

    let terminal_widget = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(border_style),
    );
    f.render_widget(terminal_widget, area);
}

/// Render non-interactive agent screen (JSON stream output)
/// `focus_color`: Some(Color) to highlight border with that color, None for muted border
pub fn render_agent_screen_non_interactive(
    f: &mut Frame,
    agent: &Agent,
    area: ratatui::layout::Rect,
    focus_color: Option<Color>,
) {
    let t = theme();
    let border_style = match focus_color {
        Some(color) => Style::default().fg(color),
        None => t.style_border_muted(),
    };
    let content_height = area.height.saturating_sub(2) as usize;
    let output = agent.screen_text();

    // Parse and filter JSON events (skip uninteresting ones)
    let all_lines: Vec<Line> = output
        .lines()
        .filter_map(|line| {
            // Parse JSON for prettier display
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(line) {
                format_json_event(&json)
            } else if !line.trim().is_empty() {
                Some(Line::from(Span::raw(line.to_string())))
            } else {
                None
            }
        })
        .collect();

    // Get the last N lines to fit in the viewport
    let start = all_lines.len().saturating_sub(content_height);
    let visible_lines: Vec<Line> = all_lines[start..].to_vec();

    // Show status indicator
    let status_style = match agent.work_state {
        WorkState::Working => Style::default().fg(Color::Yellow),
        WorkState::Completed => {
            if agent.error.is_some() {
                Style::default().fg(Color::Red)
            } else {
                Style::default().fg(Color::Green)
            }
        }
        _ => Style::default().fg(Color::Gray),
    };

    let status_text = match agent.work_state {
        WorkState::Starting => "Starting...",
        WorkState::Working => "Working...",
        WorkState::Idle => "Idle",
        WorkState::Completed => {
            if agent.error.is_some() {
                "Error"
            } else {
                "Completed"
            }
        }
    };

    let terminal_widget = Paragraph::new(visible_lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(border_style)
            .title(Span::styled(format!(" {status_text} "), status_style)),
    );
    f.render_widget(terminal_widget, area);
}

/// Convert vt100 cell attributes to ratatui Style
fn cell_to_style(cell: &vt100::Cell) -> Style {
    let mut style = Style::default();

    // Foreground color
    let fg = cell.fgcolor();
    if !matches!(fg, vt100::Color::Default) {
        style = style.fg(vt100_color_to_ratatui(fg));
    }

    // Background color
    let bg = cell.bgcolor();
    if !matches!(bg, vt100::Color::Default) {
        style = style.bg(vt100_color_to_ratatui(bg));
    }

    // Attributes
    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);
    }

    style
}

/// Convert vt100 color to ratatui color
fn vt100_color_to_ratatui(color: vt100::Color) -> Color {
    match color {
        vt100::Color::Default => Color::Reset,
        vt100::Color::Idx(0) => Color::Black,
        vt100::Color::Idx(1) => Color::Red,
        vt100::Color::Idx(2) => Color::Green,
        vt100::Color::Idx(3) => Color::Yellow,
        vt100::Color::Idx(4) => Color::Blue,
        vt100::Color::Idx(5) => Color::Magenta,
        vt100::Color::Idx(6) => Color::Cyan,
        vt100::Color::Idx(7) => Color::Gray,
        vt100::Color::Idx(8) => Color::DarkGray,
        vt100::Color::Idx(9) => Color::LightRed,
        vt100::Color::Idx(10) => Color::LightGreen,
        vt100::Color::Idx(11) => Color::LightYellow,
        vt100::Color::Idx(12) => Color::LightBlue,
        vt100::Color::Idx(13) => Color::LightMagenta,
        vt100::Color::Idx(14) => Color::LightCyan,
        vt100::Color::Idx(15) => Color::White,
        vt100::Color::Idx(idx) => Color::Indexed(idx),
        vt100::Color::Rgb(r, g, b) => Color::Rgb(r, g, b),
    }
}

/// Format a JSON stream event for display
/// Returns None if the event should be skipped
fn format_json_event(json: &serde_json::Value) -> Option<Line<'static>> {
    let event_type = json.get("type").and_then(|v| v.as_str()).unwrap_or("unknown");

    match event_type {
        "system" => {
            let subtype = json.get("subtype").and_then(|v| v.as_str()).unwrap_or("");
            Some(Line::from(vec![
                Span::styled("[SYS] ", Style::default().fg(Color::Blue)),
                Span::raw(subtype.to_string()),
            ]))
        }
        "user" => {
            // Skip user events (echo of input, not useful to display)
            None
        }
        "assistant" => {
            // Extract only text content (skip tool_use which is not informative)
            let text: String = json
                .get("message")
                .and_then(|m| m.get("content"))
                .and_then(|c| c.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|block| {
                            if block.get("type").and_then(|t| t.as_str()) == Some("text") {
                                block.get("text").and_then(|t| t.as_str())
                            } else {
                                None // Skip tool_use, tool_result, etc.
                            }
                        })
                        .collect::<Vec<_>>()
                        .join(" ")
                })
                .unwrap_or_default();

            // Skip if no text content (only tool calls)
            if text.trim().is_empty() {
                return None;
            }

            // Truncate long text (char-safe for UTF-8)
            let display_text: String = if text.chars().count() > 80 {
                format!("{}...", text.chars().take(80).collect::<String>())
            } else {
                text
            };

            Some(Line::from(vec![
                Span::styled("[AI] ", Style::default().fg(Color::Cyan)),
                Span::raw(display_text),
            ]))
        }
        "result" => {
            let subtype = json.get("subtype").and_then(|v| v.as_str()).unwrap_or("");
            let style = if subtype == "success" {
                Style::default().fg(Color::Green)
            } else {
                Style::default().fg(Color::Red)
            };
            Some(Line::from(vec![
                Span::styled("[DONE] ", style),
                Span::raw(subtype.to_string()),
            ]))
        }
        _ => None, // Skip unknown event types
    }
}