agent-core-tui 0.6.0

TUI frontend for agent-core - ratatui-based terminal interface
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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
//! Question panel widget for AskUserQuestions tool
//!
//! A reusable Ratatui panel that displays questions from the LLM
//! and collects structured responses from the user.
//!
//! # Navigation
//! - Up/Down/Ctrl-P/Ctrl-N: Move between focusable items
//! - Enter: Select choice or advance to next question
//! - Space: Toggle selection (for multi-choice)
//! - Esc: Cancel and close panel
//! - Tab: Jump to next question section
//! - Shift+Tab: Jump to previous question section
//! - For text fields: all typing goes to the TextArea
//!
//! # Submit Button
//! The Submit button is disabled (grayed out) until all required questions
//! have been answered.

use std::collections::HashSet;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::controller::{
    Answer, AskUserQuestionsRequest, AskUserQuestionsResponse, Question, TurnId,
};
use ratatui::{
    layout::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
    Frame,
};
use tui_textarea::TextArea;

use crate::themes::Theme;

/// Default configuration values for QuestionPanel
pub mod defaults {
    /// Maximum percentage of screen height the panel can use
    pub const MAX_PANEL_PERCENT: u16 = 70;
    /// Selection indicator for focused items
    pub const SELECTION_INDICATOR: &str = " \u{203A} ";
    /// Blank space for non-focused items
    pub const NO_INDICATOR: &str = "   ";
    /// Panel title
    pub const TITLE: &str = " User Input Required ";
    /// Help text for navigation mode
    pub const HELP_TEXT_NAV: &str = " Up/Down: Navigate \u{00B7} Enter/Space: Select \u{00B7} Tab: Next Section \u{00B7} Esc: Cancel";
    /// Help text for text input mode
    pub const HELP_TEXT_INPUT: &str = " Type text \u{00B7} Enter: Next \u{00B7} Tab: Next Section \u{00B7} Esc: Cancel";
    /// Question prefix icon
    pub const QUESTION_PREFIX: &str = " \u{2237} ";
    /// Radio button symbols (single choice)
    pub const RADIO_SELECTED: &str = "\u{25CF}";
    pub const RADIO_UNSELECTED: &str = "\u{25CB}";
    /// Checkbox symbols (multi choice)
    pub const CHECKBOX_SELECTED: &str = "\u{25A0}";
    pub const CHECKBOX_UNSELECTED: &str = "\u{25A1}";
}

/// Configuration for QuestionPanel widget
#[derive(Clone)]
pub struct QuestionPanelConfig {
    /// Maximum percentage of screen height the panel can use
    pub max_panel_percent: u16,
    /// Selection indicator for focused items
    pub selection_indicator: String,
    /// Blank space for non-focused items
    pub no_indicator: String,
    /// Panel title
    pub title: String,
    /// Help text for navigation mode
    pub help_text_nav: String,
    /// Help text for text input mode
    pub help_text_input: String,
    /// Question prefix icon
    pub question_prefix: String,
    /// Radio button selected symbol
    pub radio_selected: String,
    /// Radio button unselected symbol
    pub radio_unselected: String,
    /// Checkbox selected symbol
    pub checkbox_selected: String,
    /// Checkbox unselected symbol
    pub checkbox_unselected: String,
}

impl Default for QuestionPanelConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl QuestionPanelConfig {
    /// Create a new QuestionPanelConfig with default values
    pub fn new() -> Self {
        Self {
            max_panel_percent: defaults::MAX_PANEL_PERCENT,
            selection_indicator: defaults::SELECTION_INDICATOR.to_string(),
            no_indicator: defaults::NO_INDICATOR.to_string(),
            title: defaults::TITLE.to_string(),
            help_text_nav: defaults::HELP_TEXT_NAV.to_string(),
            help_text_input: defaults::HELP_TEXT_INPUT.to_string(),
            question_prefix: defaults::QUESTION_PREFIX.to_string(),
            radio_selected: defaults::RADIO_SELECTED.to_string(),
            radio_unselected: defaults::RADIO_UNSELECTED.to_string(),
            checkbox_selected: defaults::CHECKBOX_SELECTED.to_string(),
            checkbox_unselected: defaults::CHECKBOX_UNSELECTED.to_string(),
        }
    }

    /// Set the maximum panel height percentage
    pub fn with_max_panel_percent(mut self, percent: u16) -> Self {
        self.max_panel_percent = percent;
        self
    }

    /// Set the selection indicator
    pub fn with_selection_indicator(mut self, indicator: impl Into<String>) -> Self {
        self.selection_indicator = indicator.into();
        self
    }

    /// Set the panel title
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Set radio button symbols
    pub fn with_radio_symbols(mut self, selected: impl Into<String>, unselected: impl Into<String>) -> Self {
        self.radio_selected = selected.into();
        self.radio_unselected = unselected.into();
        self
    }

    /// Set checkbox symbols
    pub fn with_checkbox_symbols(mut self, selected: impl Into<String>, unselected: impl Into<String>) -> Self {
        self.checkbox_selected = selected.into();
        self.checkbox_unselected = unselected.into();
        self
    }
}

/// Represents a focusable item in the panel
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FocusItem {
    /// A choice option within a question
    Choice {
        question_idx: usize,
        choice_idx: usize,
    },
    /// The "Other" option for a choice question
    OtherOption { question_idx: usize },
    /// Text input for "Other" in a choice question
    OtherText { question_idx: usize },
    /// Free text input field
    TextInput { question_idx: usize },
    /// Submit button
    Submit,
    /// Cancel button
    Cancel,
}

/// Answer state for a single question
pub enum AnswerState {
    /// Single choice answer
    SingleChoice {
        selected: Option<String>,
        other_text: TextArea<'static>,
    },
    /// Multiple choice answer
    MultiChoice {
        selected: HashSet<String>,
        other_text: TextArea<'static>,
    },
    /// Free text answer
    FreeText { textarea: TextArea<'static> },
}

impl AnswerState {
    /// Create answer state from a question
    pub fn from_question(question: &Question) -> Self {
        match question {
            Question::SingleChoice { .. } => {
                let other_text = TextArea::default();
                AnswerState::SingleChoice {
                    selected: None,
                    other_text,
                }
            }
            Question::MultiChoice { .. } => {
                let other_text = TextArea::default();
                AnswerState::MultiChoice {
                    selected: HashSet::new(),
                    other_text,
                }
            }
            Question::FreeText { default_value, .. } => {
                let mut textarea = TextArea::default();
                if let Some(default) = default_value {
                    textarea.insert_str(default);
                }
                AnswerState::FreeText { textarea }
            }
        }
    }

    /// Convert to Answer for response
    pub fn to_answer(&self, question_text: &str) -> Answer {
        match self {
            AnswerState::SingleChoice {
                selected,
                other_text,
            } => {
                let other = other_text.lines().join("\n");
                // If user typed a custom answer, use that; otherwise use selected choice
                let answer_values = if !other.is_empty() {
                    vec![other]
                } else {
                    selected.iter().cloned().collect()
                };
                Answer {
                    question: question_text.to_string(),
                    answer: answer_values,
                }
            }
            AnswerState::MultiChoice {
                selected,
                other_text,
            } => {
                let other = other_text.lines().join("\n");
                let mut answer_values: Vec<String> = selected.iter().cloned().collect();
                // Add custom answer if provided
                if !other.is_empty() {
                    answer_values.push(other);
                }
                Answer {
                    question: question_text.to_string(),
                    answer: answer_values,
                }
            }
            AnswerState::FreeText { textarea } => Answer {
                question: question_text.to_string(),
                answer: vec![textarea.lines().join("\n")],
            },
        }
    }

    /// Check if a choice is selected
    pub fn is_selected(&self, choice_id: &str) -> bool {
        match self {
            AnswerState::SingleChoice { selected, .. } => {
                selected.as_ref().map(|s| s == choice_id).unwrap_or(false)
            }
            AnswerState::MultiChoice { selected, .. } => selected.contains(choice_id),
            AnswerState::FreeText { .. } => false,
        }
    }

    /// Toggle/select a choice
    pub fn select_choice(&mut self, choice_id: &str) {
        match self {
            AnswerState::SingleChoice { selected, .. } => {
                *selected = Some(choice_id.to_string());
            }
            AnswerState::MultiChoice { selected, .. } => {
                if selected.contains(choice_id) {
                    selected.remove(choice_id);
                } else {
                    selected.insert(choice_id.to_string());
                }
            }
            AnswerState::FreeText { .. } => {}
        }
    }

    /// Get the textarea for this answer (if applicable)
    pub fn textarea_mut(&mut self) -> Option<&mut TextArea<'static>> {
        match self {
            AnswerState::SingleChoice { other_text, .. }
            | AnswerState::MultiChoice { other_text, .. } => Some(other_text),
            AnswerState::FreeText { textarea } => Some(textarea),
        }
    }

    /// Check if "Other" has text
    pub fn has_other_text(&self) -> bool {
        match self {
            AnswerState::SingleChoice { other_text, .. }
            | AnswerState::MultiChoice { other_text, .. } => {
                !other_text.lines().join("").is_empty()
            }
            AnswerState::FreeText { .. } => false,
        }
    }

    /// Check if this answer has a valid response (selected choice or text entered)
    pub fn has_answer(&self) -> bool {
        match self {
            AnswerState::SingleChoice { selected, other_text } => {
                selected.is_some() || !other_text.lines().join("").trim().is_empty()
            }
            AnswerState::MultiChoice { selected, other_text } => {
                !selected.is_empty() || !other_text.lines().join("").trim().is_empty()
            }
            AnswerState::FreeText { textarea } => {
                !textarea.lines().join("").trim().is_empty()
            }
        }
    }
}

/// Result of pressing Enter
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnterAction {
    None,
    Selected,
    Submit,
    Cancel,
}

/// Result of handling a key event
#[derive(Debug, Clone)]
pub enum KeyAction {
    /// No action taken, key was handled internally
    Handled,
    /// Key was not handled (pass to parent)
    NotHandled,
    /// User submitted answers (includes tool_use_id and response)
    Submitted(String, AskUserQuestionsResponse),
    /// User cancelled
    Cancelled(String),
}

/// State for the question panel overlay
pub struct QuestionPanel {
    /// Whether the panel is active
    active: bool,
    /// Tool use ID for this interaction
    tool_use_id: String,
    /// Session ID
    session_id: i64,
    /// The questions
    request: AskUserQuestionsRequest,
    /// Turn ID
    turn_id: Option<TurnId>,
    /// Answers for each question
    answers: Vec<AnswerState>,
    /// All focusable items in order
    focus_items: Vec<FocusItem>,
    /// Current focus index
    focus_idx: usize,
    /// Configuration for display customization
    config: QuestionPanelConfig,
}

impl QuestionPanel {
    /// Create a new inactive question panel
    pub fn new() -> Self {
        Self::with_config(QuestionPanelConfig::new())
    }

    /// Create a new inactive question panel with custom configuration
    pub fn with_config(config: QuestionPanelConfig) -> Self {
        Self {
            active: false,
            tool_use_id: String::new(),
            session_id: 0,
            request: AskUserQuestionsRequest {
                questions: Vec::new(),
            },
            turn_id: None,
            answers: Vec::new(),
            focus_items: Vec::new(),
            focus_idx: 0,
            config,
        }
    }

    /// Get the current configuration
    pub fn config(&self) -> &QuestionPanelConfig {
        &self.config
    }

    /// Set a new configuration
    pub fn set_config(&mut self, config: QuestionPanelConfig) {
        self.config = config;
    }

    /// Activate the panel with questions
    pub fn activate(
        &mut self,
        tool_use_id: String,
        session_id: i64,
        request: AskUserQuestionsRequest,
        turn_id: Option<TurnId>,
    ) {
        self.active = true;
        self.tool_use_id = tool_use_id;
        self.session_id = session_id;

        // Initialize answers
        self.answers = request
            .questions
            .iter()
            .map(AnswerState::from_question)
            .collect();

        // Build focus items list
        self.focus_items = Self::build_focus_items(&request.questions);
        self.focus_idx = 0;

        self.request = request;
        self.turn_id = turn_id;
    }

    /// Build the list of focusable items from questions
    fn build_focus_items(questions: &[Question]) -> Vec<FocusItem> {
        let mut items = Vec::new();

        for (q_idx, question) in questions.iter().enumerate() {
            match question {
                Question::SingleChoice { choices, .. } | Question::MultiChoice { choices, .. } => {
                    // Each choice is focusable
                    for c_idx in 0..choices.len() {
                        items.push(FocusItem::Choice {
                            question_idx: q_idx,
                            choice_idx: c_idx,
                        });
                    }
                    // "Type Something" option - always available for custom answers
                    items.push(FocusItem::OtherOption { question_idx: q_idx });
                }
                Question::FreeText { .. } => {
                    items.push(FocusItem::TextInput { question_idx: q_idx });
                }
            }
        }

        // Add buttons
        items.push(FocusItem::Submit);
        items.push(FocusItem::Cancel);

        items
    }

    /// Deactivate the panel
    pub fn deactivate(&mut self) {
        self.active = false;
        self.tool_use_id.clear();
        self.request.questions.clear();
        self.answers.clear();
        self.focus_items.clear();
        self.focus_idx = 0;
    }

    /// Check if the panel is active
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Get the current tool use ID
    pub fn tool_use_id(&self) -> &str {
        &self.tool_use_id
    }

    /// Get the session ID
    pub fn session_id(&self) -> i64 {
        self.session_id
    }

    /// Get the current request
    pub fn request(&self) -> &AskUserQuestionsRequest {
        &self.request
    }

    /// Get the turn ID
    pub fn turn_id(&self) -> Option<&TurnId> {
        self.turn_id.as_ref()
    }

    /// Build the response from current answers
    pub fn build_response(&self) -> AskUserQuestionsResponse {
        let answers = self
            .request
            .questions
            .iter()
            .zip(self.answers.iter())
            .map(|(q, a)| a.to_answer(q.text()))
            .collect();
        AskUserQuestionsResponse { answers }
    }

    /// Get current focus item
    pub fn current_focus(&self) -> Option<&FocusItem> {
        self.focus_items.get(self.focus_idx)
    }

    /// Move focus to next item
    pub fn focus_next(&mut self) {
        if !self.focus_items.is_empty() {
            self.focus_idx = (self.focus_idx + 1) % self.focus_items.len();
        }
    }

    /// Move focus to previous item
    pub fn focus_prev(&mut self) {
        if !self.focus_items.is_empty() {
            if self.focus_idx == 0 {
                self.focus_idx = self.focus_items.len() - 1;
            } else {
                self.focus_idx -= 1;
            }
        }
    }

    /// Jump to submit button
    pub fn focus_submit(&mut self) {
        if let Some(idx) = self.focus_items.iter().position(|f| *f == FocusItem::Submit) {
            self.focus_idx = idx;
        }
    }

    /// Check if current focus is on a text input (or OtherOption which also accepts typing)
    pub fn is_text_focused(&self) -> bool {
        matches!(
            self.current_focus(),
            Some(FocusItem::TextInput { .. } | FocusItem::OtherText { .. } | FocusItem::OtherOption { .. })
        )
    }

    /// Handle Enter key - select choice or advance
    fn handle_enter(&mut self) -> EnterAction {
        match self.current_focus().cloned() {
            Some(FocusItem::Choice {
                question_idx,
                choice_idx,
            }) => {
                // Select this choice
                if let (Some(question), Some(answer)) = (
                    self.request.questions.get(question_idx),
                    self.answers.get_mut(question_idx),
                ) {
                    let choice_text = match question {
                        Question::SingleChoice { choices, .. }
                        | Question::MultiChoice { choices, .. } => {
                            choices.get(choice_idx).cloned()
                        }
                        _ => None,
                    };
                    if let Some(text) = choice_text {
                        answer.select_choice(&text);
                    }
                }
                // For single choice, advance to next question
                if matches!(
                    self.request.questions.get(question_idx),
                    Some(Question::SingleChoice { .. })
                ) {
                    self.advance_to_next_question(question_idx);
                }
                EnterAction::Selected
            }
            Some(FocusItem::OtherOption { question_idx: _ }) => {
                // Move to the Other text input
                self.focus_next();
                EnterAction::Selected
            }
            Some(FocusItem::OtherText { question_idx }) => {
                // Advance to next question
                self.advance_to_next_question(question_idx);
                EnterAction::Selected
            }
            Some(FocusItem::TextInput { question_idx }) => {
                // Advance to next question
                self.advance_to_next_question(question_idx);
                EnterAction::Selected
            }
            Some(FocusItem::Submit) => {
                if self.can_submit() {
                    EnterAction::Submit
                } else {
                    EnterAction::None // Can't submit yet, required fields missing
                }
            }
            Some(FocusItem::Cancel) => EnterAction::Cancel,
            None => EnterAction::None,
        }
    }

    /// Advance focus to the first item of the next question (or Submit)
    fn advance_to_next_question(&mut self, current_question_idx: usize) {
        let next_question_idx = current_question_idx + 1;

        // Find the first focus item for the next question
        if let Some(idx) = self.focus_items.iter().position(|f| match f {
            FocusItem::Choice { question_idx, .. }
            | FocusItem::OtherOption { question_idx }
            | FocusItem::OtherText { question_idx }
            | FocusItem::TextInput { question_idx } => *question_idx == next_question_idx,
            FocusItem::Submit | FocusItem::Cancel => false,
        }) {
            self.focus_idx = idx;
        } else {
            // No more questions, go to Submit
            self.focus_submit();
        }
    }

    /// Get the question index for the current focus item
    fn current_question_idx(&self) -> Option<usize> {
        match self.current_focus() {
            Some(FocusItem::Choice { question_idx, .. })
            | Some(FocusItem::OtherOption { question_idx })
            | Some(FocusItem::OtherText { question_idx })
            | Some(FocusItem::TextInput { question_idx }) => Some(*question_idx),
            _ => None,
        }
    }

    /// Focus the next question section (Tab behavior)
    /// Moves to the first item (or selected item) of the next question
    fn focus_next_section(&mut self) {
        let current_q = self.current_question_idx();
        let next_q = current_q.map(|q| q + 1).unwrap_or(0);

        // Find first focus item for next question, or Submit if no more questions
        if let Some(idx) = self.focus_items.iter().position(|f| match f {
            FocusItem::Choice { question_idx, .. }
            | FocusItem::OtherOption { question_idx }
            | FocusItem::OtherText { question_idx }
            | FocusItem::TextInput { question_idx } => *question_idx == next_q,
            FocusItem::Submit | FocusItem::Cancel => false,
        }) {
            self.focus_idx = idx;
        } else {
            // No more questions, go to Submit
            self.focus_submit();
        }
    }

    /// Focus the previous question section (Shift+Tab behavior)
    fn focus_prev_section(&mut self) {
        let current_q = self.current_question_idx();

        // If on Submit/Cancel or question 0, go to first question
        let prev_q = match current_q {
            Some(q) if q > 0 => q - 1,
            _ => {
                // Already on first question or on buttons, find last question
                let last_q = self.request.questions.len().saturating_sub(1);
                if current_q == Some(0) {
                    // On first question, wrap to Submit
                    self.focus_submit();
                    return;
                }
                last_q
            }
        };

        // Find first focus item for previous question
        if let Some(idx) = self.focus_items.iter().position(|f| match f {
            FocusItem::Choice { question_idx, .. }
            | FocusItem::OtherOption { question_idx }
            | FocusItem::OtherText { question_idx }
            | FocusItem::TextInput { question_idx } => *question_idx == prev_q,
            FocusItem::Submit | FocusItem::Cancel => false,
        }) {
            self.focus_idx = idx;
        }
    }

    /// Check if all required questions have been answered
    pub fn can_submit(&self) -> bool {
        for (question, answer) in self.request.questions.iter().zip(self.answers.iter()) {
            if question.is_required() && !answer.has_answer() {
                return false;
            }
        }
        true
    }

    /// Handle key input for text areas
    fn handle_text_input(&mut self, key: KeyEvent) {
        let focus = self.current_focus().cloned();
        match focus {
            Some(FocusItem::TextInput { question_idx }) => {
                // FreeText question - forward to its textarea
                if let Some(answer) = self.answers.get_mut(question_idx) {
                    if let Some(textarea) = answer.textarea_mut() {
                        textarea.input(key);
                    }
                }
            }
            Some(FocusItem::OtherText { question_idx })
            | Some(FocusItem::OtherOption { question_idx }) => {
                // OtherOption also accepts typing - forward to the textarea
                if let Some(answer) = self.answers.get_mut(question_idx) {
                    if let Some(textarea) = answer.textarea_mut() {
                        textarea.input(key);
                    }
                    // For single choice, clear the selected option when typing in "Other"
                    if let AnswerState::SingleChoice { selected, .. } = answer {
                        *selected = None;
                    }
                }
            }
            _ => {}
        }
    }

    /// Toggle selection with Space
    fn handle_space(&mut self) {
        match self.current_focus().cloned() {
            Some(FocusItem::Choice {
                question_idx,
                choice_idx,
            }) => {
                if let (Some(question), Some(answer)) = (
                    self.request.questions.get(question_idx),
                    self.answers.get_mut(question_idx),
                ) {
                    let choice_text = match question {
                        Question::SingleChoice { choices, .. }
                        | Question::MultiChoice { choices, .. } => {
                            choices.get(choice_idx).cloned()
                        }
                        _ => None,
                    };
                    if let Some(text) = choice_text {
                        answer.select_choice(&text);
                    }
                }
            }
            Some(FocusItem::OtherOption { .. }) => {
                // Space on Other option moves to text input
                self.focus_next();
            }
            _ => {}
        }
    }

    /// Handle a key event
    ///
    /// Returns the action that should be taken based on the key press.
    pub fn process_key(&mut self, key: KeyEvent) -> KeyAction {
        if !self.active {
            return KeyAction::NotHandled;
        }

        // Check if we're in a text input mode
        let is_text_mode = self.is_text_focused();

        match key.code {
            // Navigation (always available)
            KeyCode::Up => {
                if !is_text_mode {
                    self.focus_prev();
                    return KeyAction::Handled;
                }
            }
            KeyCode::Down => {
                if !is_text_mode {
                    self.focus_next();
                    return KeyAction::Handled;
                }
            }
            KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.focus_prev();
                return KeyAction::Handled;
            }
            KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.focus_next();
                return KeyAction::Handled;
            }
            KeyCode::Char('k') if !is_text_mode => {
                self.focus_prev();
                return KeyAction::Handled;
            }
            KeyCode::Char('j') if !is_text_mode => {
                self.focus_next();
                return KeyAction::Handled;
            }

            // Tab to move to next question section
            KeyCode::Tab => {
                self.focus_next_section();
                return KeyAction::Handled;
            }

            // Shift+Tab to move to previous question section
            KeyCode::BackTab => {
                self.focus_prev_section();
                return KeyAction::Handled;
            }

            // Cancel
            KeyCode::Esc => {
                let tool_use_id = self.tool_use_id.clone();
                // Note: don't deactivate here - let the caller do it after processing
                return KeyAction::Cancelled(tool_use_id);
            }

            // Enter - select or submit
            KeyCode::Enter => {
                match self.handle_enter() {
                    EnterAction::Submit => {
                        let tool_use_id = self.tool_use_id.clone();
                        let response = self.build_response();
                        // Note: don't deactivate here - let the caller do it after processing
                        return KeyAction::Submitted(tool_use_id, response);
                    }
                    EnterAction::Cancel => {
                        let tool_use_id = self.tool_use_id.clone();
                        // Note: don't deactivate here - let the caller do it after processing
                        return KeyAction::Cancelled(tool_use_id);
                    }
                    EnterAction::Selected | EnterAction::None => {
                        return KeyAction::Handled;
                    }
                }
            }

            // Space - toggle selection (when not in text mode)
            KeyCode::Char(' ') if !is_text_mode => {
                self.handle_space();
                return KeyAction::Handled;
            }

            // Text input
            _ if is_text_mode => {
                self.handle_text_input(key);
                return KeyAction::Handled;
            }

            _ => {}
        }

        KeyAction::NotHandled
    }

    /// Calculate the panel height based on content
    pub fn panel_height(&self, max_height: u16) -> u16 {
        // Calculate height needed for content
        let mut lines = 0u16;

        for question in &self.request.questions {
            lines += 1; // Question text
            match question {
                Question::SingleChoice { choices, .. } | Question::MultiChoice { choices, .. } => {
                    lines += choices.len() as u16;
                    lines += 1; // "Type Something:" - always shown for custom answers
                }
                Question::FreeText { .. } => {
                    lines += 1; // Text input line
                }
            }
        }

        // Add: help text(1) + help blank(1) + spacing between questions + blank before buttons(1) + buttons(1) + borders(2)
        let num_questions = self.request.questions.len() as u16;
        let spacing = if num_questions > 1 { num_questions - 1 } else { 0 };
        let total = lines + spacing + 7;

        // Cap at percentage of available height, leaving room for chat and input
        let max_from_percent = (max_height * self.config.max_panel_percent) / 100;
        total.min(max_from_percent).min(max_height.saturating_sub(6))
    }

    /// Render the question panel
    ///
    /// # Arguments
    /// * `frame` - The Ratatui frame to render into
    /// * `area` - The area to render the panel in
    /// * `theme` - Theme implementation for styling
    pub fn render_panel(&self, frame: &mut Frame, area: Rect, theme: &Theme) {
        if !self.active {
            return;
        }

        // Clear the area
        frame.render_widget(Clear, area);

        // Render panel content
        self.render_panel_content(frame, area, theme);
    }

    /// Render panel content as a single unified panel with vertical question list
    fn render_panel_content(&self, frame: &mut Frame, area: Rect, theme: &Theme) {
        let inner_width = area.width.saturating_sub(4) as usize;
        let mut lines: Vec<Line> = Vec::new();

        // Help text at top
        let help_text = if self.is_text_focused() {
            &self.config.help_text_input
        } else {
            &self.config.help_text_nav
        };
        lines.push(Line::from(Span::styled(help_text.clone(), theme.help_text())));
        lines.push(Line::from("")); // blank line after help

        // Render each question vertically
        for (q_idx, (question, answer)) in self
            .request
            .questions
            .iter()
            .zip(self.answers.iter())
            .enumerate()
        {
            // Add blank line before each question (except first)
            if q_idx > 0 {
                lines.push(Line::from(""));
            }

            // Question text with arrow prefix and required marker
            let required = if question.is_required() { "*" } else { "" };
            let q_text = format!("{}{}{}", self.config.question_prefix, question.text(), required);
            lines.push(Line::from(Span::styled(
                truncate_text(&q_text, inner_width),
                Style::default().add_modifier(Modifier::BOLD),
            )));

            match question {
                Question::SingleChoice { choices, .. } => {
                    self.render_choices(&mut lines, q_idx, choices, answer, false, inner_width, theme);
                }
                Question::MultiChoice { choices, .. } => {
                    self.render_choices(&mut lines, q_idx, choices, answer, true, inner_width, theme);
                }
                Question::FreeText { .. } => {
                    self.render_text_input(&mut lines, q_idx, answer, inner_width, theme);
                }
            }
        }

        // Add blank line before buttons
        lines.push(Line::from(""));

        // Add buttons - Submit and Cancel side by side
        let submit_focused = self.current_focus() == Some(&FocusItem::Submit);
        let cancel_focused = self.current_focus() == Some(&FocusItem::Cancel);
        let submit_enabled = self.can_submit();

        let submit_style = if !submit_enabled {
            theme.muted_text()
        } else if submit_focused {
            theme.button_confirm_focused()
        } else {
            theme.button_confirm()
        };
        let cancel_style = if cancel_focused {
            theme.button_cancel_focused()
        } else {
            theme.button_cancel()
        };

        let mut button_spans = vec![Span::raw("  ")];

        // Submit with indicator if focused (only if enabled)
        if submit_focused && submit_enabled {
            button_spans.push(Span::styled("\u{203A} ", theme.focus_indicator()));
        }
        button_spans.push(Span::styled("Submit", submit_style));
        button_spans.push(Span::raw("   "));

        // Cancel with indicator if focused
        if cancel_focused {
            button_spans.push(Span::styled("\u{203A} ", theme.focus_indicator()));
        }
        button_spans.push(Span::styled("Cancel", cancel_style));

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

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(theme.warning())
            .title(Span::styled(
                self.config.title.clone(),
                theme.warning().add_modifier(Modifier::BOLD),
            ));

        let paragraph = Paragraph::new(lines).block(block);
        frame.render_widget(paragraph, area);
    }

    /// Render choice options inline
    fn render_choices(
        &self,
        lines: &mut Vec<Line>,
        question_idx: usize,
        choices: &[String],
        answer: &AnswerState,
        is_multi: bool,
        inner_width: usize,
        theme: &Theme,
    ) {
        for (c_idx, choice_text) in choices.iter().enumerate() {
            let is_focused = self.current_focus()
                == Some(&FocusItem::Choice {
                    question_idx,
                    choice_idx: c_idx,
                });
            let is_selected = answer.is_selected(choice_text);

            let symbol = if is_multi {
                if is_selected { &self.config.checkbox_selected } else { &self.config.checkbox_unselected }
            } else {
                if is_selected { &self.config.radio_selected } else { &self.config.radio_unselected }
            };

            let prefix = if is_focused { &self.config.selection_indicator } else { &self.config.no_indicator };
            let display_text = truncate_text(choice_text, inner_width - 8);

            if is_focused {
                lines.push(Line::from(vec![
                    Span::styled(prefix.clone(), theme.focus_indicator()),
                    Span::styled(format!("{} {}", symbol, display_text), theme.focused_text()),
                ]));
            } else {
                lines.push(Line::from(Span::styled(
                    format!("{}{} {}", prefix, symbol, display_text),
                    theme.muted_text(),
                )));
            }
        }

        // "Type Something:" option - always available for custom answers
        let other_focused = self.current_focus() == Some(&FocusItem::OtherOption { question_idx });
        let other_text_focused = self.current_focus() == Some(&FocusItem::OtherText { question_idx });
        let is_this_focused = other_focused || other_text_focused;
        let has_other = answer.has_other_text();

        // For single choice, "Type Something" is selected if:
        // - no other choice is selected AND (has text OR is currently focused)
        // For multi choice, it's selected if there's text
        let is_other_selected = match answer {
            AnswerState::SingleChoice { selected, .. } => selected.is_none() && (has_other || is_this_focused),
            AnswerState::MultiChoice { .. } => has_other,
            _ => false,
        };

        let symbol = if is_multi {
            if is_other_selected { &self.config.checkbox_selected } else { &self.config.checkbox_unselected }
        } else {
            if is_other_selected { &self.config.radio_selected } else { &self.config.radio_unselected }
        };

        let prefix = if is_this_focused { &self.config.selection_indicator } else { &self.config.no_indicator };

        // Get the text input content and cursor position
        let (other_text, cursor_col) = match answer {
            AnswerState::SingleChoice { other_text, .. }
            | AnswerState::MultiChoice { other_text, .. } => {
                let text = other_text.lines().first().cloned().unwrap_or_default();
                let col = other_text.cursor().1;
                (text, col)
            }
            _ => (String::new(), 0),
        };

        // Build the text display with cursor shown as inverse character
        if is_this_focused {
            let chars: Vec<char> = other_text.chars().collect();
            let cursor_pos = cursor_col.min(chars.len());
            let before: String = chars[..cursor_pos].iter().collect();
            let cursor_char = chars.get(cursor_pos).copied().unwrap_or(' ');
            let after: String = chars.get(cursor_pos + 1..).map(|s| s.iter().collect()).unwrap_or_default();

            lines.push(Line::from(vec![
                Span::styled(prefix.clone(), theme.focus_indicator()),
                Span::styled(format!("{} Type Something: ", symbol), theme.focused_text()),
                Span::styled(before, theme.focused_text()),
                Span::styled(cursor_char.to_string(), theme.cursor()),
                Span::styled(after, theme.focused_text()),
            ]));
        } else {
            let truncated_display = truncate_text(&other_text, inner_width - 24);
            lines.push(Line::from(Span::styled(
                format!("{}{} Type Something: {}", prefix, symbol, truncated_display),
                theme.muted_text(),
            )));
        }
    }

    /// Render free text input inline
    fn render_text_input(
        &self,
        lines: &mut Vec<Line>,
        question_idx: usize,
        answer: &AnswerState,
        inner_width: usize,
        theme: &Theme,
    ) {
        let is_focused = self.current_focus() == Some(&FocusItem::TextInput { question_idx });

        let (text, cursor_col) = match answer {
            AnswerState::FreeText { textarea } => {
                let t = textarea.lines().first().cloned().unwrap_or_default();
                let col = textarea.cursor().1;
                (t, col)
            }
            _ => (String::new(), 0),
        };

        let prefix = if is_focused { &self.config.selection_indicator } else { &self.config.no_indicator };

        if is_focused {
            // Show cursor as inverse character
            let chars: Vec<char> = text.chars().collect();
            let cursor_pos = cursor_col.min(chars.len());
            let before: String = chars[..cursor_pos].iter().collect();
            let cursor_char = chars.get(cursor_pos).copied().unwrap_or(' ');
            let after: String = chars.get(cursor_pos + 1..).map(|s| s.iter().collect()).unwrap_or_default();

            lines.push(Line::from(vec![
                Span::styled(prefix.clone(), theme.focus_indicator()),
                Span::styled("Type Something: ", theme.focused_text()),
                Span::styled(before, theme.focused_text()),
                Span::styled(cursor_char.to_string(), theme.cursor()),
                Span::styled(after, theme.focused_text()),
            ]));
        } else {
            let display = if text.is_empty() {
                "Type Something:".to_string()
            } else {
                format!("Type Something: {}", text)
            };
            let truncated = truncate_text(&display, inner_width - 4);
            lines.push(Line::from(Span::styled(
                format!("{}{}", prefix, truncated),
                theme.muted_text(),
            )));
        }
    }
}

impl Default for QuestionPanel {
    fn default() -> Self {
        Self::new()
    }
}

// --- Widget trait implementation ---

use std::any::Any;
use super::{widget_ids, Widget, WidgetAction, WidgetKeyContext, WidgetKeyResult};

impl Widget for QuestionPanel {
    fn id(&self) -> &'static str {
        widget_ids::QUESTION_PANEL
    }

    fn priority(&self) -> u8 {
        200 // High priority - modal panel
    }

    fn is_active(&self) -> bool {
        self.active
    }

    fn handle_key(&mut self, key: KeyEvent, ctx: &WidgetKeyContext) -> WidgetKeyResult {
        if !self.active {
            return WidgetKeyResult::NotHandled;
        }

        let is_text_mode = self.is_text_focused();

        // Use NavigationHelper for navigation keys (when not in text mode)
        if !is_text_mode {
            if ctx.nav.is_move_up(&key) {
                self.focus_prev();
                return WidgetKeyResult::Handled;
            }
            if ctx.nav.is_move_down(&key) {
                self.focus_next();
                return WidgetKeyResult::Handled;
            }
        }

        // Ctrl+P/N always work for navigation (even in text mode)
        if key.code == KeyCode::Char('p') && key.modifiers.contains(KeyModifiers::CONTROL) {
            self.focus_prev();
            return WidgetKeyResult::Handled;
        }
        if key.code == KeyCode::Char('n') && key.modifiers.contains(KeyModifiers::CONTROL) {
            self.focus_next();
            return WidgetKeyResult::Handled;
        }

        // Cancel using nav helper
        if ctx.nav.is_cancel(&key) {
            let tool_use_id = self.tool_use_id.clone();
            return WidgetKeyResult::Action(WidgetAction::CancelQuestion { tool_use_id });
        }

        // Handle other keys via process_key for backward compatibility
        match self.process_key(key) {
            KeyAction::Submitted(tool_use_id, response) => {
                WidgetKeyResult::Action(WidgetAction::SubmitQuestion {
                    tool_use_id,
                    response,
                })
            }
            KeyAction::Cancelled(tool_use_id) => {
                WidgetKeyResult::Action(WidgetAction::CancelQuestion { tool_use_id })
            }
            KeyAction::Handled | KeyAction::NotHandled => WidgetKeyResult::Handled,
        }
    }

    fn render(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) {
        self.render_panel(frame, area, theme);
    }

    fn required_height(&self, max_height: u16) -> u16 {
        if self.active {
            self.panel_height(max_height)
        } else {
            0
        }
    }

    fn blocks_input(&self) -> bool {
        self.active
    }

    fn is_overlay(&self) -> bool {
        false
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

/// Truncate text to fit width
fn truncate_text(text: &str, max_width: usize) -> String {
    if text.chars().count() <= max_width {
        text.to_string()
    } else {
        let truncated: String = text.chars().take(max_width.saturating_sub(3)).collect();
        format!("{}...", truncated)
    }
}

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

    fn create_test_request() -> AskUserQuestionsRequest {
        AskUserQuestionsRequest {
            questions: vec![
                Question::SingleChoice {
                    text: "Choose one".to_string(),
                    choices: vec!["Option A".to_string(), "Option B".to_string()],
                    required: true,
                },
            ],
        }
    }

    #[test]
    fn test_panel_activation() {
        let mut panel = QuestionPanel::new();
        assert!(!panel.is_active());

        let request = create_test_request();
        panel.activate("tool_123".to_string(), 1, request, None);

        assert!(panel.is_active());
        assert_eq!(panel.tool_use_id(), "tool_123");
        assert_eq!(panel.session_id(), 1);

        panel.deactivate();
        assert!(!panel.is_active());
    }

    #[test]
    fn test_navigation() {
        let mut panel = QuestionPanel::new();
        let request = create_test_request();
        panel.activate("tool_1".to_string(), 1, request, None);

        // Default focus is first choice
        assert_eq!(
            panel.current_focus(),
            Some(&FocusItem::Choice {
                question_idx: 0,
                choice_idx: 0
            })
        );

        // Move to next
        panel.focus_next();
        assert_eq!(
            panel.current_focus(),
            Some(&FocusItem::Choice {
                question_idx: 0,
                choice_idx: 1
            })
        );

        // Jump to submit
        panel.focus_submit();
        assert_eq!(panel.current_focus(), Some(&FocusItem::Submit));
    }

    #[test]
    fn test_handle_key_cancel() {
        let mut panel = QuestionPanel::new();
        let request = create_test_request();
        panel.activate("tool_1".to_string(), 1, request, None);

        let action = panel.process_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
        match action {
            KeyAction::Cancelled(tool_use_id) => {
                assert_eq!(tool_use_id, "tool_1");
            }
            _ => panic!("Expected Cancelled action"),
        }
        // Panel doesn't deactivate itself - caller must do it
        panel.deactivate();
        assert!(!panel.is_active());
    }

    #[test]
    fn test_answer_state_single_choice() {
        let mut state = AnswerState::SingleChoice {
            selected: None,
            other_text: TextArea::default(),
        };

        assert!(!state.is_selected("Option A"));
        state.select_choice("Option A");
        assert!(state.is_selected("Option A"));

        // Selecting another clears the first
        state.select_choice("Option B");
        assert!(!state.is_selected("Option A"));
        assert!(state.is_selected("Option B"));
    }

    #[test]
    fn test_answer_state_multi_choice() {
        let mut state = AnswerState::MultiChoice {
            selected: HashSet::new(),
            other_text: TextArea::default(),
        };

        state.select_choice("Option A");
        state.select_choice("Option B");
        assert!(state.is_selected("Option A"));
        assert!(state.is_selected("Option B"));

        // Toggle off
        state.select_choice("Option A");
        assert!(!state.is_selected("Option A"));
        assert!(state.is_selected("Option B"));
    }
}