simplemailclient 0.2.3

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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
//! 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::env;
use std::io;
use std::time::{Duration, Instant};
use anyhow::Result;
use base64::Engine;
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::{Attachment, 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,
    /// The contacts panel (visible only when show_contacts is true).
    Contacts,
    Messages,
    Reading,
}

/// Which field is active inside the "Add contact" overlay.
#[derive(Debug, Clone, Copy, PartialEq)]
enum AddContactField {
    Address,
    Nickname,
}

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

#[derive(Debug, Clone)]
enum Mode {
    Normal,
    /// Compose / reply modal. Carries the recipient, body, and queued
    /// attachment file paths so nothing is lost when switching fields.
    Compose {
        to: String,
        body: String,
        /// Paths of files queued as attachments.
        attachments: Vec<String>,
        /// Current text in the attachment-path input field.
        attach_input: String,
        field: ComposeField,
    },
    /// Full-screen overlay showing a decoded text attachment.
    ViewAttachment {
        filename: String,
        /// Decoded UTF-8 content of the file.
        content: String,
        /// Vertical scroll offset (lines from top).
        scroll: u16,
    },
    /// Overlay for manually adding a new contact.
    AddContact {
        address: String,
        nickname: String,
        field: AddContactField,
    },
    /// Overlay for editing an existing contact's nickname.
    SetNickname {
        /// Address of the contact being edited.
        address: String,
        /// Current text in the nickname input.
        nickname: String,
    },
}

/// 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,
    /// Set the status line (e.g. attachment feedback) without leaving compose.
    Notice(String),
    Abort,
    Send {
        to: String,
        body: String,
        attachments: Vec<String>,
    },
}

/// Actions produced by the AddContact / SetNickname overlays.
enum ContactAction {
    None,
    Abort,
    AddContact { address: String, nickname: String },
    SetNickname { address: String, nickname: 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,
    /// Index of the currently selected attachment in the reading pane (0-based).
    selected_attachment: usize,
    /// Index of the selected contact in the contacts panel (0-based into all_contacts()).
    contact_selected: usize,
}

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,
            selected_attachment: 0,
            contact_selected: 0,
        };
        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();
        self.selected_attachment = 0;
    }

    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();
        self.selected_attachment = 0;
        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 {
            let unread_before = store.unread_count();
            match transport::fetch_imap(cfg, store).await {
                Ok(_) => {
                    state.reload_messages();
                    let unread_after = store.unread_count();
                    if unread_after > unread_before {
                        bell();
                    }
                    state.status = format!(" Auto-synced · {} unread", unread_after);
                }
                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, attachments, attach_input, field } = &mut state.mode {
                let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                let action = match key.code {
                    // Ctrl+S → send.
                    // Auto-commit any unsubmitted path sitting in attach_input
                    // so the user doesn't have to press Enter before Ctrl+S.
                    // If the path is invalid, block the send and report why.
                    KeyCode::Char('s') if ctrl => {
                        let pending = attach_input.trim().to_string();
                        let attach_err = if !pending.is_empty() {
                            validate_attachment(&pending).err()
                        } else {
                            None
                        };
                        if let Some(e) = attach_err {
                            ComposeAction::Notice(format!(
                                " ✗ Attachment: {} — fix or clear it first",
                                e
                            ))
                        } else {
                            // Commit the pending path (if any) then send
                            if !pending.is_empty() {
                                attachments.push(pending);
                                attach_input.clear();
                            }
                            ComposeAction::Send {
                                to: to.clone(),
                                body: body.clone(),
                                attachments: attachments.clone(),
                            }
                        }
                    }
                    KeyCode::Esc => ComposeAction::Abort,
                    // Tab flow: To → Body → Attach → Body.
                    // When leaving the Attach field, auto-commit any typed path.
                    // If the path is invalid, show the error and keep focus on Attach.
                    KeyCode::Tab | KeyCode::Down => {
                        let commit_err = if *field == ComposeField::Attach {
                            let p = attach_input.trim().to_string();
                            if p.is_empty() { None } else {
                                match validate_attachment(&p) {
                                    Ok(_) => { attachments.push(p); attach_input.clear(); None }
                                    Err(e) => Some(e),
                                }
                            }
                        } else { None };
                        if let Some(e) = commit_err {
                            ComposeAction::Notice(format!("{}", e))
                        } else {
                            *field = match *field {
                                ComposeField::To     => ComposeField::Body,
                                ComposeField::Body   => ComposeField::Attach,
                                ComposeField::Attach => ComposeField::Body,
                            };
                            ComposeAction::None
                        }
                    }
                    KeyCode::BackTab | KeyCode::Up => {
                        let commit_err = if *field == ComposeField::Attach {
                            let p = attach_input.trim().to_string();
                            if p.is_empty() { None } else {
                                match validate_attachment(&p) {
                                    Ok(_) => { attachments.push(p); attach_input.clear(); None }
                                    Err(e) => Some(e),
                                }
                            }
                        } else { None };
                        if let Some(e) = commit_err {
                            ComposeAction::Notice(format!("{}", e))
                        } else {
                            *field = match *field {
                                ComposeField::To     => ComposeField::Body,
                                ComposeField::Body   => ComposeField::Attach,
                                ComposeField::Attach => ComposeField::Body,
                            };
                            ComposeAction::None
                        }
                    }
                    KeyCode::Enter => match field {
                        // Enter in To jumps straight to the body
                        ComposeField::To => {
                            *field = ComposeField::Body;
                            ComposeAction::None
                        }
                        // Enter in Attach adds the typed path to the queue
                        ComposeField::Attach => {
                            let path = attach_input.trim().to_string();
                            if path.is_empty() {
                                ComposeAction::None
                            } else {
                                match validate_attachment(&path) {
                                    Ok(size) => {
                                        attachments.push(path.clone());
                                        attach_input.clear();
                                        ComposeAction::Notice(format!(
                                            " ✓ Attached {} ({})",
                                            path,
                                            human_size(size)
                                        ))
                                    }
                                    Err(e) => ComposeAction::Notice(format!("{}", e)),
                                }
                            }
                        }
                        // Enter in the body inserts a newline
                        ComposeField::Body => {
                            body.push('\n');
                            ComposeAction::None
                        }
                    },
                    KeyCode::Backspace => {
                        match field {
                            ComposeField::To => { to.pop(); }
                            ComposeField::Attach => {
                                // Backspace on an empty input removes the last file
                                if attach_input.is_empty() {
                                    attachments.pop();
                                } else {
                                    attach_input.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::Attach => attach_input.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::Notice(msg) => state.status = msg,
                    ComposeAction::Abort => {
                        state.mode = Mode::Normal;
                        state.status = " Compose aborted".to_string();
                    }
                    ComposeAction::Send { to, body, attachments } => {
                        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, &attachments).await {
                                        Ok(_) => {
                                            // Record sent message with its attachments,
                                            // stored separately from the body.
                                            let store_atts = paths_to_attachments(&attachments);
                                            store.record_sent(&resolved, &body, store_atts).ok();
                                            state.reload_messages();
                                            // Always show the file count so it's
                                            // obvious whether attachments were sent.
                                            state.status = if attachments.is_empty() {
                                                format!(" ✓ Sent to {} (no attachments)", resolved)
                                            } else {
                                                format!(" ✓ Sent to {} + {} file(s)", resolved, attachments.len())
                                            };
                                            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;
            }

            // ── Attachment viewer overlay input ──────────────────────────────
            let in_view = matches!(state.mode, Mode::ViewAttachment { .. });
            if let Mode::ViewAttachment { scroll, .. } = &mut state.mode {
                match key.code {
                    KeyCode::Esc | KeyCode::Char('q') => {
                        state.mode = Mode::Normal;
                    }
                    KeyCode::Down | KeyCode::Char('j') => {
                        *scroll = scroll.saturating_add(1);
                    }
                    KeyCode::Up | KeyCode::Char('k') => {
                        *scroll = scroll.saturating_sub(1);
                    }
                    KeyCode::PageDown => {
                        *scroll = scroll.saturating_add(20);
                    }
                    KeyCode::PageUp => {
                        *scroll = scroll.saturating_sub(20);
                    }
                    _ => {}
                }
            }
            if in_view {
                continue;
            }

            // ── AddContact overlay input ─────────────────────────────────────
            let in_add_contact = matches!(state.mode, Mode::AddContact { .. });
            let contact_action = if let Mode::AddContact { address, nickname, field } = &mut state.mode {
                let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                match key.code {
                    KeyCode::Esc => ContactAction::Abort,
                    // Tab / Enter on Address → move to Nickname
                    KeyCode::Tab | KeyCode::Enter if *field == AddContactField::Address => {
                        *field = AddContactField::Nickname;
                        ContactAction::None
                    }
                    // Enter / Ctrl+S on Nickname → submit
                    KeyCode::Enter | KeyCode::Char('s') if *field == AddContactField::Nickname || key.code == KeyCode::Char('s') && ctrl => {
                        ContactAction::AddContact {
                            address: address.trim().to_string(),
                            nickname: nickname.trim().to_string(),
                        }
                    }
                    KeyCode::Backspace => {
                        match field {
                            AddContactField::Address  => { address.pop(); }
                            AddContactField::Nickname => { nickname.pop(); }
                        }
                        ContactAction::None
                    }
                    KeyCode::Char(c) if !ctrl => {
                        match field {
                            AddContactField::Address  => address.push(c),
                            AddContactField::Nickname => nickname.push(c),
                        }
                        ContactAction::None
                    }
                    _ => ContactAction::None,
                }
            } else {
                ContactAction::None
            };
            if in_add_contact {
                match contact_action {
                    ContactAction::None => {}
                    ContactAction::Abort => {
                        state.mode = Mode::Normal;
                        state.status = " Cancelled".to_string();
                    }
                    ContactAction::AddContact { address, nickname } => {
                        if address.is_empty() {
                            state.status = " ✗ Address required".to_string();
                        } else {
                            let nick = if nickname.is_empty() { None } else { Some(nickname.as_str()) };
                            match state.store.add_contact(&address, nick) {
                                Ok(c) => {
                                    // Select the newly added contact
                                    let contacts = state.store.all_contacts();
                                    state.contact_selected = contacts
                                        .iter()
                                        .position(|x| x.address == c.address)
                                        .unwrap_or(0);
                                    state.mode = Mode::Normal;
                                    state.status = format!(" ✓ Contact added: {}", address);
                                }
                                Err(e) => state.status = format!("{}", e),
                            }
                        }
                    }
                    ContactAction::SetNickname { .. } => {}
                }
                continue;
            }

            // ── SetNickname overlay input ────────────────────────────────────
            let in_set_nickname = matches!(state.mode, Mode::SetNickname { .. });
            let nick_action = if let Mode::SetNickname { address, nickname } = &mut state.mode {
                let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                match key.code {
                    KeyCode::Esc => ContactAction::Abort,
                    KeyCode::Enter | KeyCode::Char('s') if !matches!(key.code, KeyCode::Char('s')) || ctrl => {
                        ContactAction::SetNickname {
                            address: address.clone(),
                            nickname: nickname.trim().to_string(),
                        }
                    }
                    KeyCode::Backspace => { nickname.pop(); ContactAction::None }
                    KeyCode::Char(c) if !ctrl => { nickname.push(c); ContactAction::None }
                    _ => ContactAction::None,
                }
            } else {
                ContactAction::None
            };
            if in_set_nickname {
                match nick_action {
                    ContactAction::None => {}
                    ContactAction::Abort => {
                        state.mode = Mode::Normal;
                        state.status = " Cancelled".to_string();
                    }
                    ContactAction::SetNickname { address, nickname } => {
                        match state.store.set_nickname(&address, &nickname) {
                            Ok(_) => {
                                state.mode = Mode::Normal;
                                let desc = if nickname.is_empty() {
                                    format!(" ✓ Nickname cleared for {}", address)
                                } else {
                                    format!(" ✓ Nickname '{}' set for {}", nickname, address)
                                };
                                state.status = desc;
                            }
                            Err(e) => state.status = format!("{}", e),
                        }
                    }
                    _ => {}
                }
                continue;
            }

            // ── Contacts pane keybinds (when Contacts pane is focused) ───────
            if state.focus == Focus::Contacts && state.show_contacts {
                let contacts = state.store.all_contacts();
                let n = contacts.len();
                let consumed = match key.code {
                    KeyCode::Down | KeyCode::Char('j') => {
                        if n > 0 { state.contact_selected = (state.contact_selected + 1).min(n - 1); }
                        true
                    }
                    KeyCode::Up | KeyCode::Char('k') => {
                        state.contact_selected = state.contact_selected.saturating_sub(1);
                        true
                    }
                    KeyCode::Char('a') => {
                        state.mode = Mode::AddContact {
                            address: String::new(),
                            nickname: String::new(),
                            field: AddContactField::Address,
                        };
                        state.status =
                            " Add contact — type address, Tab for nickname, Enter to save, Esc cancel"
                                .to_string();
                        true
                    }
                    KeyCode::Char('d') => {
                        if let Some(c) = contacts.get(state.contact_selected) {
                            let addr = c.address.clone();
                            match state.store.delete_contact(&addr) {
                                Ok(_) => {
                                    let new_n = state.store.all_contacts().len();
                                    if new_n > 0 {
                                        state.contact_selected =
                                            state.contact_selected.min(new_n - 1);
                                    } else {
                                        state.contact_selected = 0;
                                    }
                                    state.status = format!(" ✓ Deleted contact {}", addr);
                                }
                                Err(e) => state.status = format!("{}", e),
                            }
                        }
                        true
                    }
                    KeyCode::Char('n') => {
                        if let Some(c) = contacts.get(state.contact_selected) {
                            let current_nick = c.nickname.clone().unwrap_or_default();
                            state.mode = Mode::SetNickname {
                                address: c.address.clone(),
                                nickname: current_nick,
                            };
                            state.status = format!(
                                " Nickname for {} — type alias, Enter to save (empty = clear), Esc cancel",
                                c.address
                            );
                        }
                        true
                    }
                    _ => false,
                };
                if consumed { 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))?;
                    let unread_before = store.unread_count();
                    match transport::fetch_imap(cfg, store).await {
                        Ok(_) => {
                            state.reload_messages();
                            let unread_after = store.unread_count();
                            if unread_after > unread_before {
                                bell();
                            }
                            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(),
                        attachments: Vec::new(),
                        attach_input: String::new(),
                        field: ComposeField::To,
                    };
                    state.status = " Compose — type To, Tab to body, Tab again for attach, Ctrl+S send, 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(),
                            attachments: Vec::new(),
                            attach_input: String::new(),
                            field: ComposeField::Body,
                        };
                        state.status = " Reply — type body, Ctrl+S send, Tab for attach 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;
                    if state.show_contacts {
                        // Opening → jump straight into the contacts pane so
                        // a / d / n work immediately without extra Tab presses.
                        state.focus = Focus::Contacts;
                    } else if state.focus == Focus::Contacts {
                        // Closing while focused on contacts → back to folders.
                        state.focus = Focus::Folders;
                    }
                    continue;
                }
            }

            // ── Ctrl+A: save selected attachment (Reading pane) ──────────────
            if key.code == KeyCode::Char('a')
                && key.modifiers.contains(KeyModifiers::CONTROL)
                && state.focus == Focus::Reading
            {
                if let Some(msg) = &state.reading {
                    if let Some(att) = msg.attachments.get(state.selected_attachment) {
                        match save_attachment_to_disk(att) {
                            Ok(path) => state.status = format!(" ✓ Saved to {}", path),
                            Err(e) => state.status = format!(" ✗ Save failed: {}", e),
                        }
                    }
                }
                continue;
            }

            // ── Navigation ───────────────────────────────────────────────────
            match key.code {
                KeyCode::Tab => {
                    state.focus = match state.focus {
                        Focus::Folders  => if state.show_contacts { Focus::Contacts } else { Focus::Messages },
                        Focus::Contacts => Focus::Messages,
                        Focus::Messages => Focus::Reading,
                        Focus::Reading  => Focus::Folders,
                    };
                }
                KeyCode::BackTab => {
                    state.focus = match state.focus {
                        Focus::Folders  => Focus::Reading,
                        Focus::Contacts => Focus::Folders,
                        Focus::Messages => if state.show_contacts { Focus::Contacts } else { Focus::Folders },
                        Focus::Reading  => Focus::Messages,
                    };
                }
                KeyCode::Left => {
                    if state.focus == Focus::Messages || state.focus == Focus::Reading {
                        state.focus = if state.show_contacts { Focus::Contacts } else { Focus::Folders };
                    } else if state.focus == Focus::Contacts {
                        state.focus = Focus::Folders;
                    }
                }
                KeyCode::Right => {
                    if state.focus == Focus::Folders {
                        state.focus = if state.show_contacts { Focus::Contacts } else { Focus::Messages };
                    } else if state.focus == Focus::Contacts {
                        state.focus = Focus::Messages;
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    match state.focus {
                        Focus::Folders  => state.next_folder(),
                        Focus::Contacts => {} // handled above in contacts block
                        Focus::Messages => state.next_msg(),
                        Focus::Reading  => {
                            // Navigate through attachments
                            if let Some(msg) = &state.reading {
                                let n = msg.attachments.len();
                                if n > 0 && state.selected_attachment + 1 < n {
                                    state.selected_attachment += 1;
                                }
                            }
                        }
                    }
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    match state.focus {
                        Focus::Folders  => state.prev_folder(),
                        Focus::Contacts => {} // handled above in contacts block
                        Focus::Messages => state.prev_msg(),
                        Focus::Reading  => {
                            if state.selected_attachment > 0 {
                                state.selected_attachment -= 1;
                            }
                        }
                    }
                }
                KeyCode::Enter => {
                    if state.focus == Focus::Reading {
                        // Open the selected attachment inline if it's text.
                        if let Some(msg) = &state.reading {
                            if let Some(att) = msg.attachments.get(state.selected_attachment) {
                                match try_decode_text(att) {
                                    Ok(content) => {
                                        state.mode = Mode::ViewAttachment {
                                            filename: att.filename.clone(),
                                            content,
                                            scroll: 0,
                                        };
                                    }
                                    Err(e) => {
                                        state.status = format!(
                                            " ✗ Cannot preview: {} — use Ctrl+A to save",
                                            e
                                        );
                                    }
                                }
                            }
                        }
                    } else {
                        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, attachments, attach_input, field } = &state.mode {
        draw_compose(f, to, body, attachments, attach_input, *field, area);
    }

    // Draw attachment viewer overlay (rendered on top of everything)
    if let Mode::ViewAttachment { filename, content, scroll } = &state.mode {
        draw_attachment_viewer(f, filename, content, *scroll, area);
    }

    // Draw contact management overlays
    if let Mode::AddContact { address, nickname, field } = &state.mode {
        draw_add_contact(f, address, nickname, *field, area);
    }
    if let Mode::SetNickname { address, nickname } = &state.mode {
        draw_set_nickname(f, address, nickname, 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 panel
    let contacts_focused = state.focus == Focus::Contacts;
    let contacts_border_color = if contacts_focused { Color::Cyan } else { Color::DarkGray };
    let contacts_block = Block::default()
        .borders(Borders::TOP)
        .title(" Contacts [?] ")
        .border_style(Style::default().fg(contacts_border_color));

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

        // Split the inner area: list + 1-line hint at bottom
        let contacts_split = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(1), Constraint::Length(1)])
            .split(inner_contacts);

        let all = state.store.all_contacts();
        let items: Vec<ListItem> = all
            .iter()
            .enumerate()
            .map(|(i, c)| {
                let selected = contacts_focused && i == state.contact_selected;
                let nick_part = c
                    .nickname
                    .as_deref()
                    .map(|n| format!(" ({})", n))
                    .unwrap_or_default();
                let label = format!(" [{}] {}{}", c.id, c.user, nick_part);
                if selected {
                    ListItem::new(label).style(
                        Style::default()
                            .fg(Color::Black)
                            .bg(Color::Cyan)
                            .add_modifier(Modifier::BOLD),
                    )
                } else {
                    ListItem::new(label).style(Style::default().fg(Color::Gray))
                }
            })
            .collect();
        f.render_widget(List::new(items), contacts_split[0]);

        // Hint row
        let hint = if contacts_focused {
            Span::styled(
                " a add · d del · n nick",
                Style::default().fg(Color::DarkGray),
            )
        } else {
            Span::styled(
                " Tab to manage",
                Style::default().fg(Color::DarkGray),
            )
        };
        f.render_widget(Paragraph::new(Line::from(hint)), contacts_split[1]);
    } else {
        let count = state.store.all_contacts().len();
        let p = Paragraph::new(format!(" {} contacts\n [?] to manage", 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 clip = if msg.attachments.is_empty() { " " } else { "📎" };
            let date = msg.timestamp.format("%b %d %H:%M").to_string();
            let from = truncate(&msg.from, 22);
            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(clip),
                Span::raw(" "),
                Span::styled(format!("{:<22}", 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) => {
            // Header + body text only — attachments are listed separately below.
            let mut lines = 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()),
            ];

            if !msg.attachments.is_empty() {
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    format!("📎 Attachments ({})", msg.attachments.len()),
                    Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
                )));
                for (i, att) in msg.attachments.iter().enumerate() {
                    let selected = i == state.selected_attachment && state.focus == Focus::Reading;
                    let style = if selected {
                        Style::default().fg(Color::Black).bg(Color::Yellow)
                    } else {
                        Style::default().fg(Color::White)
                    };
                    let hint = if selected { "   ← Enter preview · Ctrl+A save" } else { "" };
                    lines.push(Line::from(Span::styled(
                        format!("  {} ({}){}", att.filename, human_size(att.size), hint),
                        style,
                    )));
                }
                if state.focus != Focus::Reading {
                    lines.push(Line::from(Span::styled(
                        "  (Tab to this pane · ↑↓ pick · Enter preview text · Ctrl+A save)",
                        Style::default().fg(Color::DarkGray),
                    )));
                }
            }

            lines
        }
    };

    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  ^A save  ? 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.
///
/// Resolution order:
/// 1. All digits            → contact ID lookup
/// 2. Matches a nickname    → that contact's address (case-insensitive)
/// 3. Contains '@'          → use as-is, register if new
/// 4. Otherwise             → bare username, append config domain
fn resolve_recipient(cfg: &Config, store: &MailStore, to: &str) -> Result<String> {
    let to = to.trim();
    // Numeric ID
    if !to.is_empty() && to.chars().all(|c| c.is_ascii_digit()) {
        return store.resolve_contact_id(to);
    }
    // Nickname (case-insensitive exact match)
    if let Some(addr) = store.find_by_nickname(to) {
        store.ensure_contact(&addr)?;
        return Ok(addr);
    }
    // Full address or bare username
    let addr = cfg.resolve_address(to);
    store.ensure_contact(&addr)?;
    Ok(addr)
}

/// Read each queued file path and turn it into a stored [`Attachment`]
/// (base64-encoded, MIME guessed from extension). Files that can't be read are
/// silently skipped — the send already succeeded, this is just the local record.
fn paths_to_attachments(paths: &[String]) -> Vec<Attachment> {
    paths
        .iter()
        .filter_map(|path| {
            let data = std::fs::read(path).ok()?;
            let filename = std::path::Path::new(path)
                .file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_else(|| "attachment".to_string());
            Some(Attachment {
                filename,
                size: data.len() as u64,
                mime_type: transport::guess_mime(path).to_string(),
                data: base64::engine::general_purpose::STANDARD.encode(&data),
            })
        })
        .collect()
}

/// 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, Attach, and Body fields, with the
/// focused field highlighted and showing a cursor.
fn draw_compose(
    f: &mut Frame,
    to: &str,
    body: &str,
    attachments: &[String],
    attach_input: &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 · Enter/Tab next field · Esc cancel ")
        .border_style(Style::default().fg(Color::Cyan));
    let inner = block.inner(modal);
    f.render_widget(block, modal);

    // Attach section grows with the number of queued files (capped for layout).
    let attach_h = 2 + attachments.len().min(5) as u16;
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(2),        // To
            Constraint::Length(attach_h), // Attach
            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],
    );

    // ── Attach field ──
    // The hint only shows when the input is empty so it doesn't slide
    // alongside the typed text.
    let attach_focused = field == ComposeField::Attach;
    let attach_first_line = if attach_input.is_empty() {
        Line::from(vec![
            Span::styled("Attach: ", label_style(attach_focused)),
            Span::styled(cursor(attach_focused).to_string(), Style::default().fg(Color::White)),
            Span::styled(
                "  type a path, Enter to queue · any type <25MB",
                Style::default().fg(Color::DarkGray),
            ),
        ])
    } else {
        Line::from(vec![
            Span::styled("Attach: ", label_style(attach_focused)),
            Span::styled(
                format!("{}{}", attach_input, cursor(attach_focused)),
                Style::default().fg(Color::White),
            ),
        ])
    };
    let mut attach_lines = vec![attach_first_line];
    for path in attachments.iter().take(5) {
        attach_lines.push(Line::from(Span::styled(
            format!("  📎 {}", path),
            Style::default().fg(Color::Green),
        )));
    }
    if attachments.len() > 5 {
        attach_lines.push(Line::from(Span::styled(
            format!("  …and {} more", attachments.len() - 5),
            Style::default().fg(Color::DarkGray),
        )));
    }
    f.render_widget(
        Paragraph::new(attach_lines).block(
            Block::default()
                .borders(Borders::BOTTOM)
                .border_style(Style::default().fg(Color::DarkGray)),
        ),
        chunks[1],
    );

    // ── 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[2],
    );
}

/// Validate a candidate attachment: must exist, be a file, and be under the
/// size limit. Any file type is allowed (binary included). Returns the size.
fn validate_attachment(path: &str) -> std::result::Result<u64, String> {
    let p = std::path::Path::new(path);
    let meta = std::fs::metadata(p).map_err(|_| format!("File not found: {}", path))?;
    if !meta.is_file() {
        return Err(format!("Not a file: {}", path));
    }
    let size = meta.len();
    if size > transport::MAX_ATTACHMENT_BYTES {
        return Err(format!("Over 25 MB: {}", path));
    }
    Ok(size)
}

/// Human-readable byte size, e.g. "3.2 KB".
fn human_size(bytes: u64) -> String {
    if bytes >= 1024 * 1024 {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    } else if bytes >= 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{} B", bytes)
    }
}

/// Save an attachment to disk in the Downloads folder (falling back to
/// Documents, then a temp dir). Returns the path where it was written.
fn save_attachment_to_disk(att: &Attachment) -> std::result::Result<String, String> {
    use std::path::PathBuf;

    let dir = if let Some(home) = dirs::home_dir() {
        let candidates = [home.join("Downloads"), home.join("Documents"), home.clone()];
        candidates
            .iter()
            .find(|p| p.is_dir())
            .cloned()
            .unwrap_or_else(|| {
                #[cfg(target_os = "windows")]
                { PathBuf::from(env::var("TEMP").unwrap_or_else(|_| ".".to_string())) }
                #[cfg(not(target_os = "windows"))]
                { PathBuf::from("/tmp") }
            })
    } else {
        PathBuf::from(".")
    };

    let path = dir.join(&att.filename);

    let data = base64::engine::general_purpose::STANDARD
        .decode(&att.data)
        .map_err(|e| format!("Decode failed: {}", e))?;

    std::fs::write(&path, data).map_err(|e| format!("Write failed: {}", e))?;

    Ok(path.display().to_string())
}

/// Emit a terminal BEL character. Written to stderr so it doesn't interfere
/// with ratatui's stdout buffer.
fn bell() {
    eprint!("\x07");
}

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

/// Render a full-screen overlay showing the contents of a text attachment.
fn draw_attachment_viewer(f: &mut Frame, filename: &str, content: &str, scroll: u16, area: Rect) {
    let modal = centered_rect(88, 85, area);
    f.render_widget(Clear, modal);

    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" 📄 {}  —  ↑↓/jk scroll · PgUp/PgDn · Esc close ", filename))
        .border_style(Style::default().fg(Color::Yellow));

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

    let p = Paragraph::new(content.to_string())
        .scroll((scroll, 0))
        .wrap(Wrap { trim: false })
        .style(Style::default().fg(Color::White));

    f.render_widget(p, inner);
}

/// Render the "Add contact" overlay.
fn draw_add_contact(
    f: &mut Frame,
    address: &str,
    nickname: &str,
    field: AddContactField,
    area: Rect,
) {
    let modal = centered_rect(60, 30, area);
    f.render_widget(Clear, modal);

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Add contact  —  Tab next field · Enter save · 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), Constraint::Length(2), Constraint::Min(1)])
        .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 { "" };

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

    // Nickname field
    let nick_focused = field == AddContactField::Nickname;
    let nick_hint = if nickname.is_empty() && !nick_focused {
        Span::styled("  optional", Style::default().fg(Color::DarkGray))
    } else {
        Span::raw("")
    };
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled("Nickname: ", label_style(nick_focused)),
            Span::styled(
                format!("{}{}", nickname, cursor(nick_focused)),
                Style::default().fg(Color::White),
            ),
            nick_hint,
        ]))
        .block(
            Block::default()
                .borders(Borders::BOTTOM)
                .border_style(Style::default().fg(Color::DarkGray)),
        ),
        chunks[1],
    );

    // Hint
    f.render_widget(
        Paragraph::new(Span::styled(
            " Nickname lets you type it in the To field instead of the address",
            Style::default().fg(Color::DarkGray),
        )),
        chunks[2],
    );
}

/// Render the "Set nickname" overlay for an existing contact.
fn draw_set_nickname(f: &mut Frame, address: &str, nickname: &str, area: Rect) {
    let modal = centered_rect(56, 26, area);
    f.render_widget(Clear, modal);

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Set nickname  —  Enter save · empty = clear · 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(1), Constraint::Length(2), Constraint::Min(1)])
        .split(inner);

    f.render_widget(
        Paragraph::new(Span::styled(
            format!(" {}", address),
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD),
        )),
        chunks[0],
    );

    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled("Nickname: ", Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)),
            Span::styled(format!("{}_", nickname), Style::default().fg(Color::White)),
        ]))
        .block(
            Block::default()
                .borders(Borders::BOTTOM)
                .border_style(Style::default().fg(Color::DarkGray)),
        ),
        chunks[1],
    );

    f.render_widget(
        Paragraph::new(Span::styled(
            " Leave empty and press Enter to clear the nickname",
            Style::default().fg(Color::DarkGray),
        )),
        chunks[2],
    );
}

/// Try to decode an attachment as UTF-8 text for inline preview.
/// Succeeds for any file whose bytes are valid UTF-8 (text, markdown, source
/// code, CSV, …). Returns an error for binary files.
fn try_decode_text(att: &Attachment) -> std::result::Result<String, String> {
    let data = base64::engine::general_purpose::STANDARD
        .decode(&att.data)
        .map_err(|e| format!("Base64 decode error: {}", e))?;
    String::from_utf8(data)
        .map_err(|_| "Binary file — not valid UTF-8 text".to_string())
}