Skip to main content

devbook_tui/
app.rs

1#![allow(dead_code)]
2
3use std::path::PathBuf;
4
5use anyhow::Result;
6use arboard::Clipboard;
7use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
8use crate::input::{InputAction, TextInput};
9
10use crate::api::ApiClient;
11use crate::checklist::{
12    append_to_prompt, parse_checklist_items, toggle_checklist_item_by_index, ChecklistItem,
13};
14use crate::config::{get_preset_hosts, Config};
15use crate::models::{Project, ProjectInput, Prompt, PromptDetail, PromptInput, Stats};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Pane {
19    Sidebar,
20    Prompts,
21    Detail,
22}
23
24impl Pane {
25    pub fn next(self) -> Self {
26        match self {
27            Pane::Sidebar => Pane::Prompts,
28            Pane::Prompts => Pane::Detail,
29            Pane::Detail => Pane::Sidebar,
30        }
31    }
32
33    pub fn prev(self) -> Self {
34        match self {
35            Pane::Sidebar => Pane::Detail,
36            Pane::Prompts => Pane::Sidebar,
37            Pane::Detail => Pane::Prompts,
38        }
39    }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum ViewMode {
44    Preview,
45    Raw,
46}
47
48impl ViewMode {
49    pub fn toggle(self) -> Self {
50        match self {
51            ViewMode::Preview => ViewMode::Raw,
52            ViewMode::Raw => ViewMode::Preview,
53        }
54    }
55
56    pub fn label(self) -> &'static str {
57        match self {
58            ViewMode::Preview => "Preview",
59            ViewMode::Raw => "Raw",
60        }
61    }
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum ScopeItem {
66    All,
67    Pinned,
68    Standalone,
69    Project(Project),
70    PinnedPrompt(Prompt),
71}
72
73#[derive(Debug, Clone)]
74pub enum DeleteTarget {
75    Project(Project),
76    Prompt(Prompt),
77    Attachment {
78        prompt_id: u64,
79        attachment_id: u64,
80        filename: String,
81    },
82}
83
84#[derive(Debug, Clone)]
85pub enum Modal {
86    HostSwitcher {
87        cursor: usize,
88        custom_input: TextInput,
89        entering_custom: bool,
90    },
91    Search {
92        input: TextInput,
93    },
94    QuickAppendPrompt {
95        content_input: TextInput,
96        section_input: TextInput,
97        as_task: bool,
98        focus_field: usize, // 0: content, 1: section, 2: as_task
99    },
100    ProjectForm {
101        id: Option<u64>,
102        name_input: TextInput,
103        desc_input: TextInput,
104        focus_desc: bool,
105    },
106    PromptForm {
107        id: Option<u64>,
108        title_input: TextInput,
109        project_choice_idx: usize, // 0 = None (Standalone), 1.. = index into projects
110        pinned: bool,
111        focus_field: usize, // 0: title, 1: project, 2: pinned
112    },
113    ConfirmDelete {
114        target: DeleteTarget,
115    },
116    Attachments {
117        cursor: usize,
118        upload_input: Option<TextInput>,
119        dest_input: Option<TextInput>,
120    },
121    Help,
122}
123
124pub struct App {
125    pub config: Config,
126    pub client: ApiClient,
127    pub should_quit: bool,
128    pub pending_editor: Option<(u64, PathBuf)>, // prompt_id, temp_path
129    pub status: Option<(String, bool)>,         // (message, is_error)
130
131    // Layout & Navigation
132    pub focused_pane: Pane,
133    pub view_mode: ViewMode,
134    pub modal: Option<Modal>,
135
136    // Data
137    pub stats: Stats,
138    pub preset_hosts: Vec<String>,
139    pub projects: Vec<Project>,
140    pub pinned_prompts: Vec<Prompt>,
141    pub prompts: Vec<Prompt>,
142    pub current_prompt: Option<PromptDetail>,
143    pub checklist_items: Vec<ChecklistItem>,
144
145    // Selections
146    pub sidebar_selected: usize,
147    pub prompts_selected: usize,
148    pub detail_selected_checklist: Option<usize>,
149    pub detail_scroll: usize,
150
151    // Search query
152    pub search_query: Option<String>,
153
154    pub clipboard: Option<Clipboard>,
155}
156
157pub fn sort_prompts(prompts: &mut [Prompt]) {
158    prompts.sort_by(|a, b| {
159        b.pinned
160            .cmp(&a.pinned)
161            .then_with(|| a.title.to_lowercase().cmp(&b.title.to_lowercase()))
162            .then_with(|| a.title.cmp(&b.title))
163            .then_with(|| a.id.cmp(&b.id))
164    });
165}
166
167impl App {
168    pub fn new(config: Config) -> Self {
169        let client = ApiClient::new(&config);
170        let clipboard = Clipboard::new().ok();
171
172        let mut app = Self {
173            config,
174            client,
175            should_quit: false,
176            pending_editor: None,
177            status: None,
178
179            focused_pane: Pane::Prompts,
180            view_mode: ViewMode::Preview,
181            modal: None,
182
183            stats: Stats::default(),
184            preset_hosts: get_preset_hosts(),
185            projects: Vec::new(),
186            pinned_prompts: Vec::new(),
187            prompts: Vec::new(),
188            current_prompt: None,
189            checklist_items: Vec::new(),
190
191            sidebar_selected: 0,
192            prompts_selected: 0,
193            detail_selected_checklist: None,
194            detail_scroll: 0,
195
196            search_query: None,
197            clipboard,
198        };
199
200        app.reload_all();
201        app
202    }
203
204    pub fn set_status(&mut self, msg: impl Into<String>, is_error: bool) {
205        self.status = Some((msg.into(), is_error));
206    }
207
208    pub fn clear_status(&mut self) {
209        self.status = None;
210    }
211
212    // Host Management
213    pub fn switch_host(&mut self, new_url: &str) {
214        let normalized = crate::config::normalize_url(new_url);
215        self.config.set_url(&normalized);
216        self.client.set_base_url(&normalized);
217        self.set_status(format!("Switched host to {}", normalized), false);
218        self.reload_all();
219    }
220
221    // Data Fetching
222    pub fn reload_all(&mut self) {
223        self.load_stats();
224        self.load_projects();
225        self.load_pinned_prompts();
226        self.load_prompts();
227    }
228
229    pub fn load_stats(&mut self) {
230        match self.client.get_stats() {
231            Ok(s) => self.stats = s,
232            Err(e) => self.set_status(format!("Stats error: {}", e), true),
233        }
234    }
235
236    pub fn load_projects(&mut self) {
237        match self.client.list_projects(None) {
238            Ok(projs) => {
239                self.projects = projs;
240                if self.sidebar_selected >= self.total_sidebar_items() {
241                    self.sidebar_selected = self.total_sidebar_items().saturating_sub(1);
242                }
243            }
244            Err(e) => self.set_status(format!("Projects error: {}", e), true),
245        }
246    }
247
248    pub fn load_pinned_prompts(&mut self) {
249        match self.client.list_prompts(None, None, Some(true), None) {
250            Ok(mut prompts) => {
251                sort_prompts(&mut prompts);
252                self.pinned_prompts = prompts;
253                if self.sidebar_selected >= self.total_sidebar_items() {
254                    self.sidebar_selected = self.total_sidebar_items().saturating_sub(1);
255                }
256            }
257            Err(e) => self.set_status(format!("Pinned prompts error: {}", e), true),
258        }
259    }
260
261    pub fn total_sidebar_items(&self) -> usize {
262        3 + self.projects.len() + self.pinned_prompts.len()
263    }
264
265    pub fn get_sidebar_item(&self, idx: usize) -> ScopeItem {
266        match idx {
267            0 => ScopeItem::All,
268            1 => ScopeItem::Pinned,
269            2 => ScopeItem::Standalone,
270            n => {
271                let proj_idx = n - 3;
272                if proj_idx < self.projects.len() {
273                    ScopeItem::Project(self.projects[proj_idx].clone())
274                } else {
275                    let pinned_idx = proj_idx - self.projects.len();
276                    if let Some(prompt) = self.pinned_prompts.get(pinned_idx) {
277                        ScopeItem::PinnedPrompt(prompt.clone())
278                    } else {
279                        ScopeItem::All
280                    }
281                }
282            }
283        }
284    }
285
286    pub fn load_prompts(&mut self) {
287        let scope_item = self.get_sidebar_item(self.sidebar_selected);
288        let q = self.search_query.as_deref();
289
290        let res = match scope_item {
291            ScopeItem::All => self.client.list_prompts(None, None, None, q),
292            ScopeItem::Pinned => self.client.list_prompts(None, None, Some(true), q),
293            ScopeItem::Standalone => self.client.list_prompts(None, Some("standalone"), None, q),
294            ScopeItem::Project(p) => self.client.list_prompts(Some(p.id), None, None, q),
295            ScopeItem::PinnedPrompt(prompt) => {
296                if let Some(query) = q {
297                    let query_lower = query.to_lowercase();
298                    if prompt.title.to_lowercase().contains(&query_lower) {
299                        Ok(vec![prompt])
300                    } else {
301                        Ok(vec![])
302                    }
303                } else {
304                    Ok(vec![prompt])
305                }
306            }
307        };
308
309        match res {
310            Ok(mut list) => {
311                sort_prompts(&mut list);
312                self.prompts = list;
313                if self.prompts.is_empty() {
314                    self.prompts_selected = 0;
315                    self.current_prompt = None;
316                    self.checklist_items.clear();
317                    self.detail_selected_checklist = None;
318                    self.detail_scroll = 0;
319                } else {
320                    if self.prompts_selected >= self.prompts.len() {
321                        self.prompts_selected = self.prompts.len() - 1;
322                    }
323                    self.load_current_prompt_detail();
324                }
325            }
326            Err(e) => self.set_status(format!("Prompts error: {}", e), true),
327        }
328    }
329
330    pub fn load_current_prompt_detail(&mut self) {
331        if let Some(prompt) = self.prompts.get(self.prompts_selected) {
332            match self.client.get_prompt(prompt.id) {
333                Ok(detail) => {
334                    self.checklist_items =
335                        parse_checklist_items(detail.body.as_deref().unwrap_or(""));
336                    if self.checklist_items.is_empty() {
337                        self.detail_selected_checklist = None;
338                    } else if let Some(cur) = self.detail_selected_checklist {
339                        if cur >= self.checklist_items.len() {
340                            self.detail_selected_checklist = Some(self.checklist_items.len() - 1);
341                        }
342                    } else {
343                        self.detail_selected_checklist = Some(0);
344                    }
345                    self.detail_scroll = 0;
346                    self.current_prompt = Some(detail);
347                }
348                Err(e) => {
349                    self.set_status(format!("Detail load error: {}", e), true);
350                    self.current_prompt = None;
351                    self.checklist_items.clear();
352                }
353            }
354        } else {
355            self.current_prompt = None;
356            self.checklist_items.clear();
357            self.detail_selected_checklist = None;
358            self.detail_scroll = 0;
359        }
360    }
361
362    // Toggle Checklist Item
363    pub fn toggle_current_checklist_item(&mut self) {
364        let (detail, cur_idx) = match (&self.current_prompt, self.detail_selected_checklist) {
365            (Some(d), Some(idx)) => (d.clone(), idx),
366            _ => return,
367        };
368
369        let body = detail.body.as_deref().unwrap_or("");
370        if let Some((updated_body, item)) = toggle_checklist_item_by_index(body, cur_idx) {
371            let input = PromptInput {
372                title: detail.title.clone(),
373                body: Some(updated_body.clone()),
374                ..Default::default()
375            };
376
377            match self.client.update_prompt(detail.id, &input) {
378                Ok(new_detail) => {
379                    if let Some(list_item) = self.prompts.get_mut(self.prompts_selected) {
380                        list_item.body = new_detail.body.clone();
381                    }
382                    self.checklist_items = parse_checklist_items(&updated_body);
383                    self.current_prompt = Some(new_detail);
384                    let state_str = if item.completed { "done" } else { "pending" };
385                    self.set_status(format!("Task marked {}", state_str), false);
386                }
387                Err(e) => self.set_status(format!("Failed to update prompt: {}", e), true),
388            }
389        }
390    }
391
392    // Quick Append to Prompt
393    pub fn append_prompt_content(&mut self, text: &str, section: Option<&str>, as_task: bool) {
394        let detail = match &self.current_prompt {
395            Some(d) => d.clone(),
396            None => return,
397        };
398
399        let current_body = detail.body.as_deref().unwrap_or("");
400        let updated = append_to_prompt(current_body, text, section, as_task);
401
402        let input = PromptInput {
403            title: detail.title.clone(),
404            body: Some(updated.clone()),
405            ..Default::default()
406        };
407
408        match self.client.update_prompt(detail.id, &input) {
409            Ok(new_detail) => {
410                if let Some(list_item) = self.prompts.get_mut(self.prompts_selected) {
411                    list_item.body = new_detail.body.clone();
412                }
413                self.checklist_items = parse_checklist_items(&updated);
414                if !self.checklist_items.is_empty() && self.detail_selected_checklist.is_none() {
415                    self.detail_selected_checklist = Some(0);
416                }
417                self.current_prompt = Some(new_detail);
418                self.set_status("Appended to prompt successfully", false);
419            }
420            Err(e) => self.set_status(format!("Failed to append to prompt: {}", e), true),
421        }
422    }
423
424    // Toggle Pin on selected Prompt
425    pub fn toggle_pin_current(&mut self) {
426        if let Some(prompt) = self.prompts.get(self.prompts_selected) {
427            match self.client.toggle_pin(prompt.id) {
428                Ok(resp) => {
429                    let msg = if resp.pinned {
430                        "Pinned prompt"
431                    } else {
432                        "Unpinned prompt"
433                    };
434                    self.set_status(msg, false);
435                    self.load_stats();
436                    self.load_pinned_prompts();
437                    self.load_prompts();
438                }
439                Err(e) => self.set_status(format!("Toggle pin error: {}", e), true),
440            }
441        }
442    }
443
444    // Reorder pinned prompts up/down
445    pub fn move_pinned_current(&mut self, direction_up: bool) {
446        let is_pinned_scope =
447            matches!(self.get_sidebar_item(self.sidebar_selected), ScopeItem::Pinned);
448        if !is_pinned_scope || self.prompts.len() < 2 {
449            return;
450        }
451
452        let cur_idx = self.prompts_selected;
453        let new_idx = if direction_up {
454            if cur_idx == 0 {
455                return;
456            }
457            cur_idx - 1
458        } else {
459            if cur_idx + 1 >= self.prompts.len() {
460                return;
461            }
462            cur_idx + 1
463        };
464
465        self.prompts.swap(cur_idx, new_idx);
466        self.prompts_selected = new_idx;
467
468        let ids: Vec<u64> = self.prompts.iter().map(|p| p.id).collect();
469        if let Err(e) = self.client.reorder_pinned(&ids) {
470            self.set_status(format!("Reorder error: {}", e), true);
471        } else {
472            self.set_status("Reordered pinned prompts", false);
473        }
474    }
475
476    // Yank to clipboard
477    pub fn yank_current(&mut self, full_body: bool) {
478        let text_to_copy = if full_body {
479            self.current_prompt
480                .as_ref()
481                .and_then(|d| d.body.clone())
482                .unwrap_or_default()
483        } else if let Some(idx) = self.detail_selected_checklist {
484            self.checklist_items
485                .get(idx)
486                .map(|item| item.text.clone())
487                .unwrap_or_default()
488        } else {
489            self.current_prompt
490                .as_ref()
491                .map(|d| d.title.clone())
492                .unwrap_or_default()
493        };
494
495        if text_to_copy.is_empty() {
496            self.set_status("Nothing to copy", false);
497            return;
498        }
499
500        if let Some(cb) = &mut self.clipboard {
501            if let Err(e) = cb.set_text(text_to_copy.clone()) {
502                self.set_status(format!("Clipboard error: {}", e), true);
503            } else {
504                let first_line = text_to_copy.lines().next().unwrap_or("");
505                let preview = if first_line.chars().count() > 30 {
506                    let s: String = first_line.chars().take(30).collect();
507                    format!("{}...", s)
508                } else {
509                    first_line.to_string()
510                };
511                if full_body {
512                    self.set_status(format!("Copied Prompt: \"{}\"", preview), false);
513                } else {
514                    self.set_status(format!("Copied: \"{}\"", preview), false);
515                }
516            }
517        } else {
518            self.set_status("Clipboard unavailable", true);
519        }
520    }
521
522    // External Editor Setup
523    pub fn prepare_external_editor(&mut self) -> Result<()> {
524        let detail = match &self.current_prompt {
525            Some(d) => d.clone(),
526            None => return Ok(()),
527        };
528
529        let temp_dir = std::env::temp_dir();
530        let file_path = temp_dir.join(format!("devbook-prompt-{}.md", detail.id));
531        std::fs::write(&file_path, detail.body.as_deref().unwrap_or(""))?;
532
533        self.pending_editor = Some((detail.id, file_path));
534        Ok(())
535    }
536
537    pub fn complete_external_editor(&mut self) -> Result<()> {
538        if let Some((id, path)) = self.pending_editor.take() {
539            if path.exists() {
540                let content = std::fs::read_to_string(&path)?;
541                let _ = std::fs::remove_file(&path);
542
543                if let Some(detail) = &self.current_prompt {
544                    if detail.id == id {
545                        let input = PromptInput {
546                            title: detail.title.clone(),
547                            body: Some(content.clone()),
548                            ..Default::default()
549                        };
550                        match self.client.update_prompt(id, &input) {
551                            Ok(new_detail) => {
552                                if let Some(list_item) = self.prompts.get_mut(self.prompts_selected) {
553                                    list_item.body = new_detail.body.clone();
554                                }
555                                self.checklist_items = parse_checklist_items(&content);
556                                self.current_prompt = Some(new_detail);
557                                self.set_status("Saved prompt markdown from editor", false);
558                            }
559                            Err(e) => {
560                                self.set_status(format!("Failed to save from editor: {}", e), true)
561                            }
562                        }
563                    }
564                }
565            }
566        }
567        Ok(())
568    }
569
570    fn adjust_scroll_to_checklist_item(&mut self, item_idx: usize) {
571        if let Some(item) = self.checklist_items.get(item_idx) {
572            let target_line = item.line_number.saturating_sub(1);
573            if target_line < self.detail_scroll {
574                self.detail_scroll = target_line;
575            } else if target_line >= self.detail_scroll + 18 {
576                self.detail_scroll = target_line.saturating_sub(15);
577            }
578        }
579    }
580
581    // Keyboard Event Handling
582    pub fn handle_key(&mut self, key: KeyCode) {
583        if self.modal.is_some() {
584            self.handle_modal_key(key);
585            return;
586        }
587
588        match key {
589            KeyCode::Char('q') => self.should_quit = true,
590            KeyCode::Char('?') => self.modal = Some(Modal::Help),
591            KeyCode::Char('H') | KeyCode::Char('u') => {
592                if self.config.allow_host_switcher {
593                    self.modal = Some(Modal::HostSwitcher {
594                        cursor: 0,
595                        custom_input: TextInput::new(self.config.base_url.clone()),
596                        entering_custom: false,
597                    });
598                } else {
599                    self.set_status(
600                        "Host switching locked by DEVBOOK_REMOTE_URL (pass --allow-switch to enable)",
601                        true,
602                    );
603                }
604            }
605            KeyCode::Char('/') => {
606                self.modal = Some(Modal::Search {
607                    input: TextInput::new(self.search_query.clone().unwrap_or_default()),
608                });
609            }
610            KeyCode::Char('r') => {
611                self.reload_all();
612                self.set_status("Refreshed all data", false);
613            }
614            KeyCode::Char('v') | KeyCode::Char('m') => {
615                self.view_mode = self.view_mode.toggle();
616                self.set_status(
617                    format!("Switched to {} Markdown mode", self.view_mode.label()),
618                    false,
619                );
620            }
621
622            // Pane Navigation
623            KeyCode::Char('1') => self.focused_pane = Pane::Sidebar,
624            KeyCode::Char('2') => self.focused_pane = Pane::Prompts,
625            KeyCode::Char('3') => self.focused_pane = Pane::Detail,
626            KeyCode::Tab => self.focused_pane = self.focused_pane.next(),
627            KeyCode::BackTab => self.focused_pane = self.focused_pane.prev(),
628            KeyCode::Char('h') | KeyCode::Left => self.focused_pane = self.focused_pane.prev(),
629            KeyCode::Char('l') | KeyCode::Right => self.focused_pane = self.focused_pane.next(),
630
631            // Actions per pane
632            _ => match self.focused_pane {
633                Pane::Sidebar => self.handle_sidebar_key(key),
634                Pane::Prompts => self.handle_prompts_key(key),
635                Pane::Detail => self.handle_detail_key(key),
636            },
637        }
638    }
639
640    fn handle_sidebar_key(&mut self, key: KeyCode) {
641        match key {
642            KeyCode::Char('j') | KeyCode::Down => {
643                if self.sidebar_selected + 1 < self.total_sidebar_items() {
644                    self.sidebar_selected += 1;
645                    self.prompts_selected = 0;
646                    self.load_prompts();
647                }
648            }
649            KeyCode::Char('k') | KeyCode::Up => {
650                if self.sidebar_selected > 0 {
651                    self.sidebar_selected -= 1;
652                    self.prompts_selected = 0;
653                    self.load_prompts();
654                }
655            }
656            KeyCode::Enter => match self.get_sidebar_item(self.sidebar_selected) {
657                ScopeItem::PinnedPrompt(_) => {
658                    self.focused_pane = Pane::Detail;
659                }
660                _ => {
661                    self.focused_pane = Pane::Prompts;
662                }
663            },
664            KeyCode::Char('n') => {
665                self.modal = Some(Modal::ProjectForm {
666                    id: None,
667                    name_input: TextInput::new(String::new()),
668                    desc_input: TextInput::new(String::new()),
669                    focus_desc: false,
670                });
671            }
672            KeyCode::Char('e') => {
673                if let ScopeItem::Project(p) = self.get_sidebar_item(self.sidebar_selected) {
674                    self.modal = Some(Modal::ProjectForm {
675                        id: Some(p.id),
676                        name_input: TextInput::new(p.name),
677                        desc_input: TextInput::new(p.description.unwrap_or_default()),
678                        focus_desc: false,
679                    });
680                }
681            }
682            KeyCode::Char('d') => {
683                if let ScopeItem::Project(p) = self.get_sidebar_item(self.sidebar_selected) {
684                    self.modal = Some(Modal::ConfirmDelete {
685                        target: DeleteTarget::Project(p),
686                    });
687                }
688            }
689            _ => {}
690        }
691    }
692
693    fn handle_prompts_key(&mut self, key: KeyCode) {
694        match key {
695            KeyCode::Char('j') | KeyCode::Down => {
696                if !self.prompts.is_empty() && self.prompts_selected + 1 < self.prompts.len() {
697                    self.prompts_selected += 1;
698                    self.load_current_prompt_detail();
699                }
700            }
701            KeyCode::Char('k') | KeyCode::Up => {
702                if self.prompts_selected > 0 {
703                    self.prompts_selected -= 1;
704                    self.load_current_prompt_detail();
705                }
706            }
707            KeyCode::Enter => {
708                self.focused_pane = Pane::Detail;
709            }
710            KeyCode::Char('p') => {
711                self.toggle_pin_current();
712            }
713            KeyCode::Char('K') => {
714                self.move_pinned_current(true);
715            }
716            KeyCode::Char('J') => {
717                self.move_pinned_current(false);
718            }
719            KeyCode::Char('y') => {
720                self.yank_current(false);
721            }
722            KeyCode::Char('Y') | KeyCode::Char('c') => {
723                self.yank_current(true);
724            }
725            KeyCode::Char('E') => {
726                if let Err(e) = self.prepare_external_editor() {
727                    self.set_status(format!("Failed to open editor: {}", e), true);
728                }
729            }
730            KeyCode::Char('a') => {
731                if self.current_prompt.is_some() {
732                    self.modal = Some(Modal::QuickAppendPrompt {
733                        content_input: TextInput::new(String::new()),
734                        section_input: TextInput::new(String::new()),
735                        as_task: false,
736                        focus_field: 0,
737                    });
738                }
739            }
740            KeyCode::Char('A') => {
741                if self.current_prompt.is_some() {
742                    self.modal = Some(Modal::Attachments {
743                        cursor: 0,
744                        upload_input: None,
745                        dest_input: None,
746                    });
747                }
748            }
749            KeyCode::Char('n') => {
750                let default_proj_idx = match self.get_sidebar_item(self.sidebar_selected) {
751                    ScopeItem::Project(p) => self
752                        .projects
753                        .iter()
754                        .position(|pr| pr.id == p.id)
755                        .map(|i| i + 1)
756                        .unwrap_or(0),
757                    _ => 0,
758                };
759                self.modal = Some(Modal::PromptForm {
760                    id: None,
761                    title_input: TextInput::new(String::new()),
762                    project_choice_idx: default_proj_idx,
763                    pinned: false,
764                    focus_field: 0,
765                });
766            }
767            KeyCode::Char('e') => {
768                if let Some(detail) = &self.current_prompt {
769                    let proj_choice = detail
770                        .project_id
771                        .and_then(|pid| {
772                            self.projects
773                                .iter()
774                                .position(|p| p.id == pid)
775                                .map(|i| i + 1)
776                        })
777                        .unwrap_or(0);
778                    self.modal = Some(Modal::PromptForm {
779                        id: Some(detail.id),
780                        title_input: TextInput::new(detail.title.clone()),
781                        project_choice_idx: proj_choice,
782                        pinned: detail.pinned,
783                        focus_field: 0,
784                    });
785                }
786            }
787            KeyCode::Char('d') => {
788                if let Some(prompt) = self.prompts.get(self.prompts_selected) {
789                    self.modal = Some(Modal::ConfirmDelete {
790                        target: DeleteTarget::Prompt(prompt.clone()),
791                    });
792                }
793            }
794            _ => {}
795        }
796    }
797
798    fn handle_detail_key(&mut self, key: KeyCode) {
799        match key {
800            KeyCode::Char('j') | KeyCode::Down => {
801                if !self.checklist_items.is_empty() && self.view_mode == ViewMode::Preview {
802                    let next = match self.detail_selected_checklist {
803                        Some(i) if i + 1 < self.checklist_items.len() => i + 1,
804                        None => 0,
805                        Some(i) => {
806                            self.detail_scroll = self.detail_scroll.saturating_add(1);
807                            i
808                        }
809                    };
810                    self.detail_selected_checklist = Some(next);
811                    self.adjust_scroll_to_checklist_item(next);
812                } else {
813                    self.detail_scroll = self.detail_scroll.saturating_add(1);
814                }
815            }
816            KeyCode::Char('k') | KeyCode::Up => {
817                if !self.checklist_items.is_empty() && self.view_mode == ViewMode::Preview {
818                    let prev = match self.detail_selected_checklist {
819                        Some(i) if i > 0 => i - 1,
820                        _ => {
821                            self.detail_scroll = self.detail_scroll.saturating_sub(1);
822                            0
823                        }
824                    };
825                    self.detail_selected_checklist = Some(prev);
826                    self.adjust_scroll_to_checklist_item(prev);
827                } else {
828                    self.detail_scroll = self.detail_scroll.saturating_sub(1);
829                }
830            }
831            // Document scrolling
832            KeyCode::Char('J') => {
833                self.detail_scroll = self.detail_scroll.saturating_add(3);
834            }
835            KeyCode::Char('K') => {
836                self.detail_scroll = self.detail_scroll.saturating_sub(3);
837            }
838            KeyCode::PageDown => {
839                self.detail_scroll = self.detail_scroll.saturating_add(10);
840            }
841            KeyCode::PageUp => {
842                self.detail_scroll = self.detail_scroll.saturating_sub(10);
843            }
844            KeyCode::Char('g') => {
845                self.detail_scroll = 0;
846                if !self.checklist_items.is_empty() {
847                    self.detail_selected_checklist = Some(0);
848                }
849            }
850            KeyCode::Char('G') => {
851                let total_lines = self
852                    .current_prompt
853                    .as_ref()
854                    .and_then(|d| d.body.as_deref())
855                    .map(|b| b.lines().count())
856                    .unwrap_or(0);
857                self.detail_scroll = total_lines.saturating_sub(5);
858                if !self.checklist_items.is_empty() {
859                    self.detail_selected_checklist = Some(self.checklist_items.len() - 1);
860                }
861            }
862            // Checklist toggle
863            KeyCode::Char(' ') | KeyCode::Enter => {
864                if !self.checklist_items.is_empty() {
865                    self.toggle_current_checklist_item();
866                }
867            }
868            // Quick append to prompt
869            KeyCode::Char('a') => {
870                if self.current_prompt.is_some() {
871                    self.modal = Some(Modal::QuickAppendPrompt {
872                        content_input: TextInput::new(String::new()),
873                        section_input: TextInput::new(String::new()),
874                        as_task: false,
875                        focus_field: 0,
876                    });
877                }
878            }
879            // External editor
880            KeyCode::Char('E') => {
881                if let Err(e) = self.prepare_external_editor() {
882                    self.set_status(format!("Failed to open editor: {}", e), true);
883                }
884            }
885            // Yank
886            KeyCode::Char('y') => {
887                self.yank_current(false);
888            }
889            KeyCode::Char('Y') | KeyCode::Char('c') => {
890                self.yank_current(true);
891            }
892            // Pin toggle
893            KeyCode::Char('p') => {
894                self.toggle_pin_current();
895            }
896            // Attachments
897            KeyCode::Char('A') if self.current_prompt.is_some() => {
898                self.modal = Some(Modal::Attachments {
899                    cursor: 0,
900                    upload_input: None,
901                    dest_input: None,
902                });
903            }
904            _ => {}
905        }
906    }
907
908    fn handle_modal_key(&mut self, key: KeyCode) {
909        let modal = self.modal.clone();
910        match modal {
911            Some(Modal::HostSwitcher {
912                cursor,
913                mut custom_input,
914                entering_custom,
915            }) => match key {
916                KeyCode::Esc if !entering_custom => self.modal = None,
917                KeyCode::Up => {
918                    if !entering_custom && cursor > 0 {
919                        self.modal = Some(Modal::HostSwitcher {
920                            cursor: cursor - 1,
921                            custom_input,
922                            entering_custom: false,
923                        });
924                    }
925                }
926                KeyCode::Down => {
927                    if !entering_custom && cursor < self.preset_hosts.len() {
928                        self.modal = Some(Modal::HostSwitcher {
929                            cursor: cursor + 1,
930                            custom_input,
931                            entering_custom: false,
932                        });
933                    }
934                }
935                KeyCode::Tab => {
936                    let next_entering = !entering_custom;
937                    self.modal = Some(Modal::HostSwitcher {
938                        cursor,
939                        custom_input,
940                        entering_custom: next_entering,
941                    });
942                }
943                KeyCode::Char('c') if !entering_custom => {
944                    self.modal = Some(Modal::HostSwitcher {
945                        cursor,
946                        custom_input,
947                        entering_custom: true,
948                    });
949                }
950                _ if entering_custom => {
951                    let action = custom_input.handle_key(KeyEvent::new(key, KeyModifiers::NONE));
952                    match action {
953                        InputAction::Cancel => self.modal = None,
954                        InputAction::Submit => {
955                            self.modal = None;
956                            if !custom_input.value.trim().is_empty() {
957                                self.switch_host(&custom_input.value);
958                            }
959                        }
960                        InputAction::Consumed | InputAction::Ignored => {
961                            self.modal = Some(Modal::HostSwitcher {
962                                cursor,
963                                custom_input,
964                                entering_custom: true,
965                            });
966                        }
967                    }
968                }
969                KeyCode::Enter => {
970                    self.modal = None;
971                    if cursor == self.preset_hosts.len() {
972                        if !custom_input.value.trim().is_empty() {
973                            self.switch_host(&custom_input.value);
974                        }
975                    } else if let Some(preset) = self.preset_hosts.get(cursor).cloned() {
976                        self.switch_host(&preset);
977                    }
978                }
979                _ => {}
980            },
981
982            Some(Modal::Search { mut input }) => {
983                match input.handle_key(KeyEvent::new(key, KeyModifiers::NONE)) {
984                    InputAction::Cancel => {
985                        self.modal = None;
986                        self.search_query = None;
987                        self.load_prompts();
988                    }
989                    InputAction::Submit => {
990                        self.modal = None;
991                        self.search_query = if input.value.trim().is_empty() {
992                            None
993                        } else {
994                            Some(input.value.trim().to_string())
995                        };
996                        self.load_prompts();
997                    }
998                    InputAction::Consumed => {
999                        let q = input.value.clone();
1000                        self.modal = Some(Modal::Search { input });
1001                        self.search_query = if q.is_empty() { None } else { Some(q) };
1002                        self.load_prompts();
1003                    }
1004                    InputAction::Ignored => {}
1005                }
1006            }
1007
1008            Some(Modal::QuickAppendPrompt {
1009                mut content_input,
1010                mut section_input,
1011                mut as_task,
1012                focus_field,
1013            }) => match key {
1014                KeyCode::Esc if focus_field == 2 => self.modal = None,
1015                KeyCode::Tab => {
1016                    self.modal = Some(Modal::QuickAppendPrompt {
1017                        content_input,
1018                        section_input,
1019                        as_task,
1020                        focus_field: (focus_field + 1) % 3,
1021                    });
1022                }
1023                KeyCode::BackTab => {
1024                    self.modal = Some(Modal::QuickAppendPrompt {
1025                        content_input,
1026                        section_input,
1027                        as_task,
1028                        focus_field: (focus_field + 2) % 3,
1029                    });
1030                }
1031                KeyCode::Char(' ') if focus_field == 2 => {
1032                    as_task = !as_task;
1033                    self.modal = Some(Modal::QuickAppendPrompt {
1034                        content_input,
1035                        section_input,
1036                        as_task,
1037                        focus_field,
1038                    });
1039                }
1040                _ if focus_field == 0 || focus_field == 1 => {
1041                    let active = if focus_field == 0 {
1042                        &mut section_input
1043                    } else {
1044                        &mut content_input
1045                    };
1046                    match active.handle_key(KeyEvent::new(key, KeyModifiers::NONE)) {
1047                        InputAction::Cancel => self.modal = None,
1048                        InputAction::Submit => {
1049                            if !content_input.value.trim().is_empty() {
1050                                let sec = if section_input.value.trim().is_empty() {
1051                                    None
1052                                } else {
1053                                    Some(section_input.value.trim())
1054                                };
1055                                self.append_prompt_content(content_input.value.trim(), sec, as_task);
1056                            }
1057                            self.modal = None;
1058                        }
1059                        InputAction::Consumed | InputAction::Ignored => {
1060                            self.modal = Some(Modal::QuickAppendPrompt {
1061                                content_input,
1062                                section_input,
1063                                as_task,
1064                                focus_field,
1065                            });
1066                        }
1067                    }
1068                }
1069                KeyCode::Enter => {
1070                    if !content_input.value.trim().is_empty() {
1071                        let sec = if section_input.value.trim().is_empty() {
1072                            None
1073                        } else {
1074                            Some(section_input.value.trim())
1075                        };
1076                        self.append_prompt_content(content_input.value.trim(), sec, as_task);
1077                    }
1078                    self.modal = None;
1079                }
1080                _ => {}
1081            },
1082
1083            Some(Modal::ProjectForm {
1084                id,
1085                mut name_input,
1086                mut desc_input,
1087                focus_desc,
1088            }) => match key {
1089                KeyCode::Tab | KeyCode::BackTab => {
1090                    self.modal = Some(Modal::ProjectForm {
1091                        id,
1092                        name_input,
1093                        desc_input,
1094                        focus_desc: !focus_desc,
1095                    });
1096                }
1097                _ => {
1098                    let active = if focus_desc {
1099                        &mut desc_input
1100                    } else {
1101                        &mut name_input
1102                    };
1103                    match active.handle_key(KeyEvent::new(key, KeyModifiers::NONE)) {
1104                        InputAction::Cancel => self.modal = None,
1105                        InputAction::Submit => {
1106                            if !name_input.value.trim().is_empty() {
1107                                let input = ProjectInput {
1108                                    name: name_input.value.trim().to_string(),
1109                                    description: if desc_input.value.trim().is_empty() {
1110                                        None
1111                                    } else {
1112                                        Some(desc_input.value.trim().to_string())
1113                                    },
1114                                };
1115
1116                                let res = match id {
1117                                    Some(pid) => self.client.update_project(pid, &input),
1118                                    None => self.client.create_project(&input),
1119                                };
1120
1121                                match res {
1122                                    Ok(p) => {
1123                                        self.set_status(format!("Saved project '{}'", p.name), false);
1124                                        self.load_stats();
1125                                        self.load_projects();
1126                                    }
1127                                    Err(e) => self.set_status(format!("Project save error: {}", e), true),
1128                                }
1129                            }
1130                            self.modal = None;
1131                        }
1132                        InputAction::Consumed | InputAction::Ignored => {
1133                            self.modal = Some(Modal::ProjectForm {
1134                                id,
1135                                name_input,
1136                                desc_input,
1137                                focus_desc,
1138                            });
1139                        }
1140                    }
1141                }
1142            },
1143
1144            Some(Modal::PromptForm {
1145                id,
1146                mut title_input,
1147                project_choice_idx,
1148                mut pinned,
1149                focus_field,
1150            }) => match key {
1151                KeyCode::Esc if focus_field != 0 => self.modal = None,
1152                KeyCode::Tab => {
1153                    let next = (focus_field + 1) % 3;
1154                    self.modal = Some(Modal::PromptForm {
1155                        id,
1156                        title_input,
1157                        project_choice_idx,
1158                        pinned,
1159                        focus_field: next,
1160                    });
1161                }
1162                KeyCode::BackTab => {
1163                    let prev = (focus_field + 2) % 3;
1164                    self.modal = Some(Modal::PromptForm {
1165                        id,
1166                        title_input,
1167                        project_choice_idx,
1168                        pinned,
1169                        focus_field: prev,
1170                    });
1171                }
1172                KeyCode::Left if focus_field == 1 => {
1173                    let next_idx = if project_choice_idx > 0 {
1174                        project_choice_idx - 1
1175                    } else {
1176                        self.projects.len()
1177                    };
1178                    self.modal = Some(Modal::PromptForm {
1179                        id,
1180                        title_input,
1181                        project_choice_idx: next_idx,
1182                        pinned,
1183                        focus_field,
1184                    });
1185                }
1186                KeyCode::Right if focus_field == 1 => {
1187                    let next_idx = (project_choice_idx + 1) % (self.projects.len() + 1);
1188                    self.modal = Some(Modal::PromptForm {
1189                        id,
1190                        title_input,
1191                        project_choice_idx: next_idx,
1192                        pinned,
1193                        focus_field,
1194                    });
1195                }
1196                KeyCode::Char(' ') if focus_field == 2 => {
1197                    pinned = !pinned;
1198                    self.modal = Some(Modal::PromptForm {
1199                        id,
1200                        title_input,
1201                        project_choice_idx,
1202                        pinned,
1203                        focus_field,
1204                    });
1205                }
1206                _ if focus_field == 0 => {
1207                    match title_input.handle_key(KeyEvent::new(key, KeyModifiers::NONE)) {
1208                        InputAction::Cancel => self.modal = None,
1209                        InputAction::Submit => {
1210                            if !title_input.value.trim().is_empty() {
1211                                let selected_pid = if project_choice_idx == 0 {
1212                                    None
1213                                } else {
1214                                    self.projects.get(project_choice_idx - 1).map(|p| p.id)
1215                                };
1216
1217                                let input = PromptInput {
1218                                    title: title_input.value.trim().to_string(),
1219                                    project_id: Some(selected_pid),
1220                                    pinned: Some(pinned),
1221                                    ..Default::default()
1222                                };
1223
1224                                let res = match id {
1225                                    Some(nid) => self.client.update_prompt(nid, &input),
1226                                    None => self.client.create_prompt(&input),
1227                                };
1228
1229                                match res {
1230                                    Ok(p) => {
1231                                        self.set_status(format!("Saved prompt '{}'", p.title), false);
1232                                        self.load_stats();
1233                                        self.load_projects();
1234                                        self.load_pinned_prompts();
1235                                        self.load_prompts();
1236                                    }
1237                                    Err(e) => self.set_status(format!("Prompt save error: {}", e), true),
1238                                }
1239                            }
1240                            self.modal = None;
1241                        }
1242                        InputAction::Consumed | InputAction::Ignored => {
1243                            self.modal = Some(Modal::PromptForm {
1244                                id,
1245                                title_input,
1246                                project_choice_idx,
1247                                pinned,
1248                                focus_field,
1249                            });
1250                        }
1251                    }
1252                }
1253                KeyCode::Enter => {
1254                    if !title_input.value.trim().is_empty() {
1255                        let selected_pid = if project_choice_idx == 0 {
1256                            None
1257                        } else {
1258                            self.projects.get(project_choice_idx - 1).map(|p| p.id)
1259                        };
1260
1261                        let input = PromptInput {
1262                            title: title_input.value.trim().to_string(),
1263                            project_id: Some(selected_pid),
1264                            pinned: Some(pinned),
1265                            ..Default::default()
1266                        };
1267
1268                        let res = match id {
1269                            Some(nid) => self.client.update_prompt(nid, &input),
1270                            None => self.client.create_prompt(&input),
1271                        };
1272
1273                        match res {
1274                            Ok(p) => {
1275                                self.set_status(format!("Saved prompt '{}'", p.title), false);
1276                                self.load_stats();
1277                                self.load_projects();
1278                                self.load_pinned_prompts();
1279                                self.load_prompts();
1280                            }
1281                            Err(e) => self.set_status(format!("Prompt save error: {}", e), true),
1282                        }
1283                    }
1284                    self.modal = None;
1285                }
1286                _ => {}
1287            },
1288
1289            Some(Modal::ConfirmDelete { target }) => match key {
1290                KeyCode::Esc | KeyCode::Char('n') => self.modal = None,
1291                KeyCode::Char('y') | KeyCode::Enter => {
1292                    self.modal = None;
1293                    match target {
1294                        DeleteTarget::Project(p) => match self.client.delete_project(p.id) {
1295                            Ok(_) => {
1296                                self.set_status(format!("Deleted project '{}'", p.name), false);
1297                                self.sidebar_selected = 0;
1298                                self.load_stats();
1299                                self.load_projects();
1300                                self.load_pinned_prompts();
1301                                self.load_prompts();
1302                            }
1303                            Err(e) => {
1304                                self.set_status(format!("Delete project error: {}", e), true)
1305                            }
1306                        },
1307                        DeleteTarget::Prompt(p) => match self.client.delete_prompt(p.id) {
1308                            Ok(_) => {
1309                                self.set_status(format!("Deleted prompt '{}'", p.title), false);
1310                                self.load_stats();
1311                                self.load_projects();
1312                                self.load_pinned_prompts();
1313                                self.load_prompts();
1314                            }
1315                            Err(e) => {
1316                                self.set_status(format!("Delete prompt error: {}", e), true)
1317                            }
1318                        },
1319                        DeleteTarget::Attachment {
1320                            prompt_id,
1321                            attachment_id,
1322                            filename,
1323                        } => match self.client.delete_attachment(prompt_id, attachment_id) {
1324                            Ok(_) => {
1325                                self.set_status(format!("Deleted attachment {}", filename), false);
1326                                self.load_stats();
1327                                self.load_current_prompt_detail();
1328                            }
1329                            Err(e) => {
1330                                self.set_status(format!("Delete attachment error: {}", e), true)
1331                            }
1332                        },
1333                    }
1334                }
1335                _ => {}
1336            },
1337
1338            Some(Modal::Attachments {
1339                cursor,
1340                upload_input,
1341                dest_input,
1342            }) => {
1343                let attachments = self
1344                    .current_prompt
1345                    .as_ref()
1346                    .map(|d| d.attachments.clone())
1347                    .unwrap_or_default();
1348
1349                if let Some(mut path_input) = upload_input {
1350                    match path_input.handle_key(KeyEvent::new(key, KeyModifiers::NONE)) {
1351                        InputAction::Cancel => {
1352                            self.modal = Some(Modal::Attachments {
1353                                cursor,
1354                                upload_input: None,
1355                                dest_input: None,
1356                            });
1357                        }
1358                        InputAction::Submit => {
1359                            if let Some(prompt) = &self.current_prompt {
1360                                let path = std::path::Path::new(path_input.value.trim());
1361                                if path.exists() {
1362                                    match self.client.upload_attachment(prompt.id, path) {
1363                                        Ok(_) => {
1364                                            self.set_status("Uploaded attachment", false);
1365                                            self.load_stats();
1366                                            self.load_current_prompt_detail();
1367                                        }
1368                                        Err(e) => {
1369                                            self.set_status(format!("Upload error: {}", e), true)
1370                                        }
1371                                    }
1372                                } else {
1373                                    self.set_status(
1374                                        format!("File not found: {}", path_input.value),
1375                                        true,
1376                                    );
1377                                }
1378                            }
1379                            self.modal = Some(Modal::Attachments {
1380                                cursor,
1381                                upload_input: None,
1382                                dest_input: None,
1383                            });
1384                        }
1385                        InputAction::Consumed | InputAction::Ignored => {
1386                            self.modal = Some(Modal::Attachments {
1387                                cursor,
1388                                upload_input: Some(path_input),
1389                                dest_input: None,
1390                            });
1391                        }
1392                    }
1393                    return;
1394                }
1395
1396                if let Some(mut dest_input_val) = dest_input {
1397                    match dest_input_val.handle_key(KeyEvent::new(key, KeyModifiers::NONE)) {
1398                        InputAction::Cancel => {
1399                            self.modal = Some(Modal::Attachments {
1400                                cursor,
1401                                upload_input: None,
1402                                dest_input: None,
1403                            });
1404                        }
1405                        InputAction::Submit => {
1406                            if let Some(att) = attachments.get(cursor) {
1407                                let path = std::path::Path::new(dest_input_val.value.trim());
1408                                match self.client.download_attachment(&att.url, path) {
1409                                    Ok(_) => self.set_status(
1410                                        format!("Saved attachment to {}", dest_input_val.value),
1411                                        false,
1412                                    ),
1413                                    Err(e) => {
1414                                        self.set_status(format!("Download error: {}", e), true)
1415                                    }
1416                                }
1417                            }
1418                            self.modal = Some(Modal::Attachments {
1419                                cursor,
1420                                upload_input: None,
1421                                dest_input: None,
1422                            });
1423                        }
1424                        InputAction::Consumed | InputAction::Ignored => {
1425                            self.modal = Some(Modal::Attachments {
1426                                cursor,
1427                                upload_input: None,
1428                                dest_input: Some(dest_input_val),
1429                            });
1430                        }
1431                    }
1432                    return;
1433                }
1434
1435                match key {
1436                    KeyCode::Esc => self.modal = None,
1437                    KeyCode::Char('j') | KeyCode::Down => {
1438                        if !attachments.is_empty() && cursor + 1 < attachments.len() {
1439                            self.modal = Some(Modal::Attachments {
1440                                cursor: cursor + 1,
1441                                upload_input: None,
1442                                dest_input: None,
1443                            });
1444                        }
1445                    }
1446                    KeyCode::Char('k') | KeyCode::Up => {
1447                        if cursor > 0 {
1448                            self.modal = Some(Modal::Attachments {
1449                                cursor: cursor - 1,
1450                                upload_input: None,
1451                                dest_input: None,
1452                            });
1453                        }
1454                    }
1455                    KeyCode::Char('u') => {
1456                        self.modal = Some(Modal::Attachments {
1457                            cursor,
1458                            upload_input: Some(TextInput::new(String::new())),
1459                            dest_input: None,
1460                        });
1461                    }
1462                    KeyCode::Char('s') => {
1463                        if let Some(att) = attachments.get(cursor) {
1464                            self.modal = Some(Modal::Attachments {
1465                                cursor,
1466                                upload_input: None,
1467                                dest_input: Some(TextInput::new(att.filename.clone())),
1468                            });
1469                        }
1470                    }
1471                    KeyCode::Char('y') => {
1472                        if let Some(att) = attachments.get(cursor) {
1473                            if let Some(cb) = &mut self.clipboard {
1474                                let full_url = if att.url.starts_with("http") {
1475                                    att.url.clone()
1476                                } else {
1477                                    format!("{}{}", self.config.base_url, att.url)
1478                                };
1479                                let _ = cb.set_text(full_url);
1480                                self.set_status("Copied attachment URL to clipboard", false);
1481                            }
1482                        }
1483                    }
1484                    KeyCode::Char('d') => {
1485                        if let Some(att) = attachments.get(cursor) {
1486                            if let Some(prompt) = &self.current_prompt {
1487                                self.modal = Some(Modal::ConfirmDelete {
1488                                    target: DeleteTarget::Attachment {
1489                                        prompt_id: prompt.id,
1490                                        attachment_id: att.id,
1491                                        filename: att.filename.clone(),
1492                                    },
1493                                });
1494                            }
1495                        }
1496                    }
1497                    _ => {}
1498                }
1499            }
1500
1501            Some(Modal::Help) => match key {
1502                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('?') | KeyCode::Enter => {
1503                    self.modal = None;
1504                }
1505                _ => {}
1506            },
1507
1508            None => {}
1509        }
1510    }
1511}
1512
1513#[cfg(test)]
1514pub mod tests {
1515    use super::*;
1516
1517    #[test]
1518    pub fn test_sort_prompts_pinned_first_and_alphabetical() {
1519        let mut prompts = vec![
1520            Prompt {
1521                id: 1,
1522                project_id: None,
1523                project_name: None,
1524                title: "Zebra Prompt".to_string(),
1525                body: None,
1526                pinned: false,
1527                pinned_position: None,
1528                attachments_count: 0,
1529                created_at: None,
1530                updated_at: None,
1531            },
1532            Prompt {
1533                id: 2,
1534                project_id: None,
1535                project_name: None,
1536                title: "Apple Prompt".to_string(),
1537                body: None,
1538                pinned: false,
1539                pinned_position: None,
1540                attachments_count: 0,
1541                created_at: None,
1542                updated_at: None,
1543            },
1544            Prompt {
1545                id: 3,
1546                project_id: None,
1547                project_name: None,
1548                title: "Banana Prompt (Pinned)".to_string(),
1549                body: None,
1550                pinned: true,
1551                pinned_position: Some(1),
1552                attachments_count: 0,
1553                created_at: None,
1554                updated_at: None,
1555            },
1556        ];
1557
1558        sort_prompts(&mut prompts);
1559
1560        assert_eq!(prompts[0].id, 3); // Pinned prompt first
1561        assert_eq!(prompts[1].id, 2); // Apple Prompt
1562        assert_eq!(prompts[2].id, 1); // Zebra Prompt
1563    }
1564
1565    #[test]
1566    pub fn test_sidebar_items_resolution() {
1567        let cfg = Config::new("http://localhost:3000");
1568        let app = App {
1569            config: cfg.clone(),
1570            client: ApiClient::new(&cfg),
1571            should_quit: false,
1572            pending_editor: None,
1573            status: None,
1574            focused_pane: Pane::Prompts,
1575            view_mode: ViewMode::Preview,
1576            modal: None,
1577            stats: Stats::default(),
1578            preset_hosts: vec![],
1579            projects: vec![Project {
1580                id: 10,
1581                name: "AI Agents".to_string(),
1582                description: None,
1583                prompts_count: 2,
1584                created_at: None,
1585                updated_at: None,
1586            }],
1587            pinned_prompts: vec![Prompt {
1588                id: 99,
1589                project_id: None,
1590                project_name: None,
1591                title: "Pinned System Prompt".to_string(),
1592                body: None,
1593                pinned: true,
1594                pinned_position: Some(1),
1595                attachments_count: 0,
1596                created_at: None,
1597                updated_at: None,
1598            }],
1599            prompts: vec![],
1600            current_prompt: None,
1601            checklist_items: vec![],
1602            sidebar_selected: 0,
1603            prompts_selected: 0,
1604            detail_selected_checklist: None,
1605            detail_scroll: 0,
1606            search_query: None,
1607            clipboard: None,
1608        };
1609
1610        assert_eq!(app.total_sidebar_items(), 5);
1611        assert_eq!(app.get_sidebar_item(0), ScopeItem::All);
1612        assert_eq!(app.get_sidebar_item(1), ScopeItem::Pinned);
1613        assert_eq!(app.get_sidebar_item(2), ScopeItem::Standalone);
1614        assert_eq!(app.get_sidebar_item(3), ScopeItem::Project(app.projects[0].clone()));
1615        assert_eq!(app.get_sidebar_item(4), ScopeItem::PinnedPrompt(app.pinned_prompts[0].clone()));
1616    }
1617}