simplemailclient 0.1.1

A simple terminal mail client (SMTP send, IMAP fetch) with a TUI.
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
//! Split-pane TUI:
//!   Left sidebar  – folder list (Inbox / Sent / Starred / Trash) + contact list
//!   Right top     – message list for selected folder
//!   Right bottom  – message reading pane
//!
//! Keybinds come from config (defaults: q quit, c compose, r reply, d delete,
//! s star, S sync, Tab/BackTab cycle folders, j/k navigate, Enter open).

use std::io;
use std::time::{Duration, Instant};
use anyhow::Result;
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap},
    Frame, Terminal,
};
use crate::config::Config;
use crate::store::{Folder, MailStore, Message};
use crate::transport;

// ─── State ────────────────────────────────────────────────────────────────────

const FOLDERS: [Folder; 4] = [Folder::Inbox, Folder::Sent, Folder::Starred, Folder::Trash];

#[derive(Debug, Clone, Copy, PartialEq)]
enum Focus {
    Folders,
    Messages,
    Reading,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum ComposeField {
    To,
    Body,
}

#[derive(Debug, Clone)]
enum Mode {
    Normal,
    /// Compose / reply modal.
    Compose {
        to: String,
        body: String,
        field: ComposeField,
    },
}

/// What the compose modal wants the main loop to do once the borrow on
/// `state.mode` is released (so async send can run outside the borrow).
enum ComposeAction {
    None,
    Abort,
    Send { to: String, body: String },
}

struct AppState<'a> {
    cfg: &'a Config,
    store: &'a MailStore,
    folder_idx: usize,
    msg_list_state: ListState,
    messages: Vec<(usize, Message)>, // (store_index, message)
    reading: Option<Message>,
    status: String,
    show_contacts: bool,
    focus: Focus,
    mode: Mode,
}

impl<'a> AppState<'a> {
    fn new(cfg: &'a Config, store: &'a MailStore) -> Self {
        let mut s = Self {
            cfg,
            store,
            folder_idx: 0,
            msg_list_state: ListState::default(),
            messages: vec![],
            reading: None,
            status: format!(" mailrs  •  {}", cfg.identity),
            show_contacts: false,
            focus: Focus::Messages,
            mode: Mode::Normal,
        };
        s.reload_messages();
        s
    }

    fn current_folder(&self) -> &Folder {
        &FOLDERS[self.folder_idx]
    }

    fn reload_messages(&mut self) {
        self.messages = self.store.messages_in(self.current_folder());
        self.messages.reverse(); // newest first
        if self.messages.is_empty() {
            self.msg_list_state.select(None);
        } else {
            let sel = self.msg_list_state.selected().unwrap_or(0);
            self.msg_list_state.select(Some(sel.min(self.messages.len() - 1)));
        }
        self.reading = self.selected_message();
    }

    fn selected_message(&self) -> Option<Message> {
        let i = self.msg_list_state.selected()?;
        self.messages.get(i).map(|(_, m)| m.clone())
    }

    fn selected_store_index(&self) -> Option<usize> {
        let i = self.msg_list_state.selected()?;
        self.messages.get(i).map(|(idx, _)| *idx)
    }

    fn next_msg(&mut self) {
        if self.messages.is_empty() { return; }
        let i = self.msg_list_state.selected().unwrap_or(0);
        let next = (i + 1).min(self.messages.len() - 1);
        self.msg_list_state.select(Some(next));
        self.open_selected();
    }

    fn prev_msg(&mut self) {
        if self.messages.is_empty() { return; }
        let i = self.msg_list_state.selected().unwrap_or(0);
        let prev = i.saturating_sub(1);
        self.msg_list_state.select(Some(prev));
        self.open_selected();
    }

    fn open_selected(&mut self) {
        if let Some(idx) = self.selected_store_index() {
            self.store.mark_read(idx).ok();
        }
        self.reading = self.selected_message();
        if let Some(ref mut m) = self.reading {
            m.read = true;
        }
    }

    fn next_folder(&mut self) {
        self.folder_idx = (self.folder_idx + 1) % FOLDERS.len();
        self.msg_list_state.select(None);
        self.reading = None;
        self.reload_messages();
    }

    fn prev_folder(&mut self) {
        self.folder_idx = (self.folder_idx + FOLDERS.len() - 1) % FOLDERS.len();
        self.msg_list_state.select(None);
        self.reading = None;
        self.reload_messages();
    }
}

// ─── Entry point ─────────────────────────────────────────────────────────────

pub async fn run(cfg: &Config, store: &MailStore) -> Result<()> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let result = run_loop(cfg, store, &mut terminal).await;

    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen, DisableMouseCapture)?;
    terminal.show_cursor()?;

    result
}

async fn run_loop<B: ratatui::backend::Backend + io::Write>(
    cfg: &Config,
    store: &MailStore,
    terminal: &mut Terminal<B>,
) -> Result<()> {
    let mut state = AppState::new(cfg, store);
    let kb = &cfg.keybinds;

    // Auto-sync every 10 seconds while idle.
    const AUTO_SYNC_INTERVAL: Duration = Duration::from_secs(10);
    let mut last_sync = Instant::now();

    loop {
        terminal.draw(|f| draw(f, &mut state))?;

        // ── Auto-sync ────────────────────────────────────────────────────────
        // Fire only when idle in Normal mode so it never interrupts composing.
        if matches!(state.mode, Mode::Normal) && last_sync.elapsed() >= AUTO_SYNC_INTERVAL {
            match transport::fetch_imap(cfg, store).await {
                Ok(_) => {
                    state.reload_messages();
                    state.status = format!(" Auto-synced · {} unread", store.unread_count());
                }
                Err(e) => state.status = format!(" Auto-sync error: {}", e),
            }
            last_sync = Instant::now();
        }

        // Wait up to 200ms for input; the timeout lets the auto-sync timer tick
        // even when the user isn't pressing anything.
        if !event::poll(Duration::from_millis(200))? {
            continue;
        }

        if let Event::Key(key) = event::read()? {
            // On Windows, crossterm emits both Press and Release events.
            // Ignore everything except Press so each keystroke registers once.
            if key.kind != KeyEventKind::Press {
                continue;
            }

            // ── Compose / reply modal input ──────────────────────────────────
            // Compute an action while borrowing state.mode, then act on it
            // after the borrow is released (so the async send can run).
            let in_compose = matches!(state.mode, Mode::Compose { .. });
            if let Mode::Compose { to, body, field } = &mut state.mode {
                let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                let action = match key.code {
                    // Ctrl+S → send
                    KeyCode::Char('s') if ctrl => ComposeAction::Send {
                        to: to.clone(),
                        body: body.clone(),
                    },
                    KeyCode::Esc => ComposeAction::Abort,
                    // Tab / Down → toggle between To and Body
                    KeyCode::Tab | KeyCode::Down => {
                        *field = match field {
                            ComposeField::To   => ComposeField::Body,
                            ComposeField::Body => ComposeField::To,
                        };
                        ComposeAction::None
                    }
                    // Shift+Tab / Up → same (only two fields)
                    KeyCode::BackTab | KeyCode::Up => {
                        *field = match field {
                            ComposeField::To   => ComposeField::Body,
                            ComposeField::Body => ComposeField::To,
                        };
                        ComposeAction::None
                    }
                    KeyCode::Enter => match field {
                        // Enter in To jumps to the body
                        ComposeField::To   => { *field = ComposeField::Body; ComposeAction::None }
                        // Enter in body inserts a newline
                        ComposeField::Body => { body.push('\n'); ComposeAction::None }
                    },
                    KeyCode::Backspace => {
                        match field {
                            ComposeField::To   => { to.pop(); }
                            ComposeField::Body => { body.pop(); }
                        }
                        ComposeAction::None
                    }
                    // Plain character (ignore ctrl-combos so they don't insert text)
                    KeyCode::Char(c) if !ctrl => {
                        match field {
                            ComposeField::To   => to.push(c),
                            ComposeField::Body => body.push(c),
                        }
                        ComposeAction::None
                    }
                    _ => ComposeAction::None,
                };

                // Act on the action now that the &mut borrow above has ended.
                match action {
                    ComposeAction::None => {}
                    ComposeAction::Abort => {
                        state.mode = Mode::Normal;
                        state.status = " Compose aborted".to_string();
                    }
                    ComposeAction::Send { to, body } => {
                        let to = to.trim().to_string();
                        let body = body.trim().to_string();
                        if to.is_empty() || body.is_empty() {
                            state.status = " ✗ Recipient and body required".to_string();
                        } else {
                            state.status = " Sending…".to_string();
                            terminal.draw(|f| draw(f, &mut state))?;
                            match resolve_recipient(cfg, store, &to) {
                                Ok(resolved) => {
                                    match transport::send_smtp(cfg, &resolved, &body).await {
                                        Ok(_) => {
                                            store.record_sent(&resolved, &body).ok();
                                            state.reload_messages();
                                            state.status = format!(" ✓ Sent to {}", resolved);
                                            state.mode = Mode::Normal;
                                        }
                                        // Keep the draft open so it can be retried.
                                        Err(e) => {
                                            state.status = format!(" ✗ Send failed: {}", e)
                                        }
                                    }
                                }
                                Err(e) => state.status = format!("{}", e),
                            }
                        }
                    }
                }
            }
            if in_compose {
                // The modal consumes every key — never fall through to global
                // keybinds (otherwise typing 'q' would quit, etc.).
                continue;
            }

            let ch = match key.code {
                KeyCode::Char(c) => Some(c.to_string()),
                _ => None,
            };

            // ── Global keybinds ──────────────────────────────────────────────
            if let Some(ref k) = ch {
                if k == &kb.quit {
                    break;
                }

                if k == &kb.sync {
                    state.status = " Syncing…".to_string();
                    terminal.draw(|f| draw(f, &mut state))?;
                    match transport::fetch_imap(cfg, store).await {
                        Ok(_) => {
                            state.reload_messages();
                            state.status = format!(
                                " Sync complete  •  {} unread",
                                store.unread_count()
                            );
                        }
                        Err(e) => state.status = format!(" Sync error: {}", e),
                    }
                    last_sync = Instant::now(); // reset auto-sync timer
                    continue;
                }

                if k == &kb.compose {
                    state.mode = Mode::Compose {
                        to: String::new(),
                        body: String::new(),
                        field: ComposeField::To,
                    };
                    state.status = " Compose — Ctrl+S send · Tab field · Esc cancel".to_string();
                    continue;
                }

                if k == &kb.reply {
                    if let Some(msg) = state.reading.clone() {
                        state.mode = Mode::Compose {
                            to: msg.from.clone(),
                            body: String::new(),
                            field: ComposeField::Body,
                        };
                        state.status = " Reply — Ctrl+S send · Tab field · Esc cancel".to_string();
                    }
                    continue;
                }

                if k == &kb.star {
                    if let Some(idx) = state.selected_store_index() {
                        state.store.toggle_star(idx).ok();
                        state.reload_messages();
                    }
                    continue;
                }

                if k == &kb.delete {
                    if let Some(idx) = state.selected_store_index() {
                        // Grab the UID before we move the message locally
                        let uid = state.store.get_message(idx).and_then(|m| m.uid);

                        // Always apply the local trash move immediately
                        state.store.move_to_trash(idx).ok();
                        state.reload_messages();
                        state.status = " Moved to trash".to_string();
                        terminal.draw(|f| draw(f, &mut state))?;

                        // Best-effort: also move on the IMAP server so it
                        // doesn't re-appear on the next sync
                        if let Some(uid) = uid {
                            if let Err(e) = transport::imap_move_to_trash(cfg, uid).await {
                                state.status = format!(
                                    " Local trash OK — IMAP: {}",
                                    e
                                );
                            }
                        }
                    }
                    continue;
                }

                if k == "?" {
                    state.show_contacts = !state.show_contacts;
                    continue;
                }
            }

            // ── Navigation ───────────────────────────────────────────────────
            match key.code {
                KeyCode::Tab => {
                    state.focus = match state.focus {
                        Focus::Folders  => Focus::Messages,
                        Focus::Messages => Focus::Reading,
                        Focus::Reading  => Focus::Folders,
                    };
                }
                KeyCode::BackTab => {
                    state.focus = match state.focus {
                        Focus::Folders  => Focus::Reading,
                        Focus::Messages => Focus::Folders,
                        Focus::Reading  => Focus::Messages,
                    };
                }
                KeyCode::Left => {
                    if state.focus == Focus::Messages || state.focus == Focus::Reading {
                        state.focus = Focus::Folders;
                    }
                }
                KeyCode::Right => {
                    if state.focus == Focus::Folders {
                        state.focus = Focus::Messages;
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    match state.focus {
                        Focus::Folders  => state.next_folder(),
                        Focus::Messages => state.next_msg(),
                        Focus::Reading  => {}
                    }
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    match state.focus {
                        Focus::Folders  => state.prev_folder(),
                        Focus::Messages => state.prev_msg(),
                        Focus::Reading  => {}
                    }
                }
                KeyCode::Enter => state.open_selected(),
                _ => {}
            }
        }
    }

    Ok(())
}

// ─── Drawing ─────────────────────────────────────────────────────────────────

fn draw(f: &mut Frame, state: &mut AppState) {
    let area = f.size();

    // Outer: status bar at bottom
    let outer = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(1)])
        .split(area);

    let main_area = outer[0];
    let status_area = outer[1];

    // Main: sidebar | content
    let main_split = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Length(22), Constraint::Min(1)])
        .split(main_area);

    let sidebar_area = main_split[0];
    let content_area = main_split[1];

    // Content: message list (top) | reading pane (bottom)
    let content_split = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
        .split(content_area);

    let list_area = content_split[0];
    let read_area = content_split[1];

    draw_sidebar(f, state, sidebar_area);
    draw_message_list(f, state, list_area);
    draw_reading_pane(f, state, read_area);
    draw_status_bar(f, state, status_area);

    // Draw compose overlay if in compose mode
    if let Mode::Compose { to, body, field } = &state.mode {
        draw_compose(f, to, body, *field, area);
    }
}

fn draw_sidebar(f: &mut Frame, state: &mut AppState, area: Rect) {
    let border_color = if state.focus == Focus::Folders {
        Color::Cyan
    } else {
        Color::DarkGray
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Folders ")
        .border_style(Style::default().fg(border_color));

    let inner = block.inner(area);
    f.render_widget(block, area);

    // Folder list
    let folder_items: Vec<ListItem> = FOLDERS
        .iter()
        .enumerate()
        .map(|(i, folder)| {
            let unread = state.store.unread_in(folder);
            let label = if unread > 0 {
                format!(" {} ({})", folder.label(), unread)
            } else {
                format!(" {}", folder.label())
            };
            let style = if i == state.folder_idx {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Cyan)
                    .add_modifier(Modifier::BOLD)
            } else if unread > 0 {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default().fg(Color::White)
            };
            ListItem::new(label).style(style)
        })
        .collect();

    // Split sidebar: folders top, contacts bottom
    let sidebar_split = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(FOLDERS.len() as u16 + 2), Constraint::Min(1)])
        .split(inner);

    let folder_list = List::new(folder_items);
    f.render_widget(folder_list, sidebar_split[0]);

    // Contacts grouped by domain
    let contacts_block = Block::default()
        .borders(Borders::TOP)
        .title(" Contacts [?] ")
        .border_style(Style::default().fg(Color::DarkGray));

    if state.show_contacts {
        let inner_contacts = contacts_block.inner(sidebar_split[1]);
        f.render_widget(contacts_block, sidebar_split[1]);

        let by_domain = state.store.contacts_by_domain();
        let mut items: Vec<ListItem> = vec![];
        let mut domains: Vec<String> = by_domain.keys().cloned().collect();
        domains.sort();

        for domain in domains {
            items.push(ListItem::new(
                Span::styled(format!(" @{}", domain), Style::default().fg(Color::Cyan)),
            ));
            for c in &by_domain[&domain] {
                let label = format!("  [{}] {}", c.id, c.user);
                items.push(ListItem::new(label).style(Style::default().fg(Color::Gray)));
            }
        }

        f.render_widget(List::new(items), inner_contacts);
    } else {
        let count = state.store.all_contacts().len();
        let p = Paragraph::new(format!(" {} contacts\n [?] to view", count))
            .style(Style::default().fg(Color::DarkGray));
        let inner_contacts = contacts_block.inner(sidebar_split[1]);
        f.render_widget(contacts_block, sidebar_split[1]);
        f.render_widget(p, inner_contacts);
    }
}

fn draw_message_list(f: &mut Frame, state: &mut AppState, area: Rect) {
    let folder_name = state.current_folder().label();
    let title = format!(" {}{} messages ", folder_name, state.messages.len());

    let items: Vec<ListItem> = state
        .messages
        .iter()
        .map(|(_, msg)| {
            let unread_dot = if !msg.read { "" } else { " " };
            let star = if msg.starred { "" } else { " " };
            let date = msg.timestamp.format("%b %d %H:%M").to_string();
            let from = truncate(&msg.from, 24);
            let preview: String = msg.body.lines().next().unwrap_or("").chars().take(30).collect();

            let line = Line::from(vec![
                Span::styled(unread_dot, Style::default().fg(Color::Cyan)),
                Span::raw(star),
                Span::raw(" "),
                Span::styled(format!("{:<24}", from), Style::default().fg(Color::White)),
                Span::raw(" "),
                Span::styled(format!("{:<14}", date), Style::default().fg(Color::DarkGray)),
                Span::styled(preview, Style::default().fg(Color::Gray)),
            ]);

            let style = if !msg.read {
                Style::default().add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };
            ListItem::new(line).style(style)
        })
        .collect();

    let border_color = if state.focus == Focus::Messages {
        Color::Cyan
    } else {
        Color::DarkGray
    };
    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .border_style(Style::default().fg(border_color)),
        )
        .highlight_style(
            Style::default()
                .bg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        );

    f.render_stateful_widget(list, area, &mut state.msg_list_state);
}

fn draw_reading_pane(f: &mut Frame, state: &mut AppState, area: Rect) {
    let border_color = if state.focus == Focus::Reading {
        Color::Cyan
    } else {
        Color::DarkGray
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Message ")
        .border_style(Style::default().fg(border_color));

    let lines: Vec<Line> = match &state.reading {
        None => vec![Line::from("No message selected.")],
        Some(msg) => vec![
            Line::from(format!("From : {}", msg.from)),
            Line::from(format!("To   : {}", msg.to)),
            Line::from(format!("Date : {}", msg.timestamp.format("%Y-%m-%d %H:%M:%S"))),
            Line::from("".repeat(60)),
            Line::from(msg.body.clone()),
        ],
    };

    let paragraph = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false })
        .style(Style::default().fg(Color::White));

    f.render_widget(paragraph, area);
}

fn draw_status_bar(f: &mut Frame, state: &AppState, area: Rect) {
    let kb = &state.cfg.keybinds;
    let help = format!(
        "  {}quit  {}compose  {}reply  {}star  {}delete  {}sync  Tab/←→ panes  ↑↓/jk nav  ? contacts",
        kb.quit, kb.compose, kb.reply, kb.star, kb.delete, kb.sync
    );

    let bar = Paragraph::new(Line::from(vec![
        Span::styled(&state.status, Style::default().fg(Color::Cyan)),
        Span::styled(&help, Style::default().fg(Color::DarkGray)),
    ]))
    .style(Style::default().bg(Color::Black));

    f.render_widget(bar, area);
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// Resolve a compose "To" string into a full email address.
/// Accepts a numeric contact ID, a bare username, or a full address.
fn resolve_recipient(cfg: &Config, store: &MailStore, to: &str) -> Result<String> {
    let to = to.trim();
    if !to.is_empty() && to.chars().all(|c| c.is_ascii_digit()) {
        store.resolve_contact_id(to)
    } else {
        let addr = cfg.resolve_address(to);
        store.ensure_contact(&addr)?;
        Ok(addr)
    }
}

/// Centered rectangle covering `percent_x` × `percent_y` of `area`.
fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let vertical = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(area);
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(vertical[1])[1]
}

/// Render the compose / reply modal: To and Body fields.
fn draw_compose(
    f: &mut Frame,
    to: &str,
    body: &str,
    field: ComposeField,
    area: Rect,
) {
    let modal = centered_rect(70, 60, area);

    // Clear the area behind the modal so the UI underneath doesn't bleed through.
    f.render_widget(Clear, modal);

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Compose  —  Ctrl+S send · Tab field · Esc cancel ")
        .border_style(Style::default().fg(Color::Cyan));
    let inner = block.inner(modal);
    f.render_widget(block, modal);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(2), // To
            Constraint::Min(1),    // Body
        ])
        .split(inner);

    let label_style = |focused: bool| {
        if focused {
            Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::DarkGray)
        }
    };
    let cursor = |focused: bool| if focused { "_" } else { "" };

    // ── To field ──
    let to_focused = field == ComposeField::To;
    let to_line = Line::from(vec![
        Span::styled("To: ", label_style(to_focused)),
        Span::styled(format!("{}{}", to, cursor(to_focused)), Style::default().fg(Color::White)),
    ]);
    f.render_widget(
        Paragraph::new(to_line).block(
            Block::default()
                .borders(Borders::BOTTOM)
                .border_style(Style::default().fg(Color::DarkGray)),
        ),
        chunks[0],
    );

    // ── Body field ──
    let body_focused = field == ComposeField::Body;
    f.render_widget(
        Paragraph::new(format!("{}{}", body, cursor(body_focused)))
            .wrap(Wrap { trim: false })
            .style(Style::default().fg(Color::White)),
        chunks[1],
    );
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        format!("{}", s.chars().take(max - 1).collect::<String>())
    }
}