edamame 0.1.2

A fast TUI Markdown editor and viewer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
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
//! Settings overlay.
//!
//! Friendly, curated subset of `config.toml` editable in-place.  The
//! overlay is intentionally narrower than the file: anything that's
//! truly esoteric (developer logging, modal handler name, image cell
//! ceilings) stays in the file where users who care can edit it
//! directly.  The in-app overlay should always be simpler than
//! reading the TOML.
//!
//! Layout:
//!
//! ```text
//! Open Config folder              [ Open ]
//! Open config.toml in editor      [ Open ]
//!
//! Autosave                        |   off
//!   Automatically save changes when idle
//!
//!   Char limit                     100
//! Maximum content width in characters when limit is on
//! ...
//! ```
//!
//! Editable rows are listed alphabetically by label, except `Show line
//! numbers`, which sits below the two image-visibility rows so the image
//! group stays contiguous.  The remote-images row is locked (greyed +
//! skipped, in the muted hint color) while `Show images` is `Never`,
//! mirroring the welcome modal's cascade.
//!
//! The first two rows are "open externally" actions — the folder row
//! shells `xdg-open` (or the OS equivalent) on the config directory;
//! the file row suspends the TUI and runs `$VISUAL`/`$EDITOR` on
//! `config.toml`.  A blank divider separates them from the editable
//! settings beneath.
//!
//! Each row's description appears beneath it only when the row is
//! focused, conserving vertical space.  Booleans render as on/off toggle
//! sliders and enum-valued fields as cycle pills — both change on
//! Left/Right (or Enter).  Numeric fields are text inputs that are
//! editable the moment the row has focus (no "press Enter to begin"); the
//! draft commits on Enter or when focus leaves the row, and an invalid
//! draft reverts on leave.

mod rows;

use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
    buffer::Buffer,
    layout::Rect,
    text::{Line, Span},
    widgets::{Paragraph, StatefulWidget, Widget},
};

use crate::config::{Config, ImagesEnabled, RemoteImagePolicy, Theme};
use crate::ui::content_width::{max_row_width, optional_text_width};
use crate::ui::controls::{self, Control, ControlEvent, ControlInput};
use crate::ui::overlay_nav::next_focusable;

/// Width of the label column in the settings overlay (column count of the
/// padded `{label:<LABEL_PAD$}` slot before the value column begins).
/// Wide enough to fit the longest setting label without clipping; narrow
/// enough to leave room for the value on terminals around 80 columns.
const LABEL_PAD: usize = 28;
/// Width of the focus-marker column (`› ` / two spaces) rendered before
/// every row's label.  The control's value column starts after the marker
/// and the padded label — shared by the content-width sizing pass and the
/// click hit-rect capture.
const FOCUS_MARKER_WIDTH: usize = 2;
use crate::ui::scroll_container::{
    centered_rect_for_content, draw_frame, ContentSize, FrameOpts, ModalKind, ScrollContainerState,
    VERTICAL_CHROME_ROWS,
};

use self::rows::{build_rows, RowAction, RowDef};

// Re-exports for the bin-only `app::modal::settings` live-update wiring.
// The lib itself never reads them, so allow(dead_code) on the helper
// suppresses the otherwise-spurious `cargo clippy --lib` warning.
#[allow(unused_imports)]
pub(crate) use self::rows::{
    HEADER_NOTE, LABEL_AUTOSAVE, LABEL_BIG_H1, LABEL_BLINK_CURSOR, LABEL_DIFF_ON_CHANGE,
    LABEL_LIMIT_WIDTH, LABEL_LINE_NUMBERS, LABEL_SCROLL_SPEED, LABEL_SHOW_DIAGRAMS,
    LABEL_SHOW_IMAGES, LABEL_SHOW_REMOTE_IMAGES, LABEL_SYNTAX_HIGHLIGHTING, LABEL_TABLE_BUTTONS,
    LABEL_VIM_MODE, LABEL_VISUAL_LINE_NAV,
};

/// All row labels in display order, including non-focusable dividers.
/// Used by the App-level live-update wiring tests in
/// `app/modal/settings.rs` so that adding a new row to `build_rows`
/// becomes an explicit, reviewable change at the App layer too.
#[allow(dead_code)]
pub(crate) fn all_row_labels() -> Vec<&'static str> {
    build_rows().into_iter().map(|r| r.label).collect()
}

/// Outcome of dispatching a key event to the settings overlay.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SettingsResponse {
    Continue,
    Cancelled,
    /// User chose `Open config.toml in editor` — caller
    /// should suspend the TUI and run `$VISUAL`/`$EDITOR`, falling
    /// back to `open::that(&config_path)`.
    OpenInExternalEditor,
    /// User chose the new top-row "Open Config folder" entry —
    /// caller should `open::that(&config_dir)` so the OS file
    /// manager surfaces the folder.  Distinct from
    /// `OpenInExternalEditor` because this path doesn't need to
    /// suspend the TUI: `xdg-open` returns immediately and edamame
    /// stays in the foreground.
    OpenConfigFolder,
    /// A field changed.  The overlay's [`Config`] reference has
    /// already been mutated; the caller is expected to call
    /// `Config::save` and flash a `Configuration updated`
    /// notification.  Carries the human-readable label of the
    /// changed field.
    FieldChanged(&'static str),
}

/// Mutable state for an open settings overlay.
pub struct SettingsState {
    /// Index into [`Self::rows`].  Never rests on a divider or another
    /// non-focusable row: it is seeded to the first Cycle/Edit row by
    /// [`Self::new`], stepped by [`Self::move_focus`] (which skips
    /// ineligible rows), and the one other assignment site —
    /// [`Self::focus_clicked_row`], via [`Self::handle_click`] — checks
    /// `focus_eligible` against the live config before calling it.  A new
    /// assignment site owes the same guard; `rows` is built once in `new`
    /// and never rebuilt, so nothing re-snaps a stale index.
    pub focused: usize,
    /// Editable draft for the focused text-input (numeric) row.  Seeded
    /// by [`Self::open_draft_for_focused`] whenever focus lands on such a
    /// row (so it's editable on focus) and committed at a boundary (Enter
    /// or focus-leave); `None` on toggle / pill / action rows.
    pub editing: Option<String>,
    /// Last error from a rejected edit.  Cleared on the next
    /// successful edit / cancel.
    pub last_error: Option<String>,
    /// Empty placeholder — kept so the row table's `read` / `cycle`
    /// function pointers can continue to take `&[String]`.  Theme
    /// selection moved out of the settings overlay into a dedicated
    /// `Action::SwitchTheme` modal, so no live row needs this list
    /// anymore.
    pub theme_names: Vec<String>,
    /// Vertical scroll bookkeeping for the row table.  Up/Down move
    /// `focused` and pull the viewport via `ensure_visible`; PgUp/PgDn
    /// and the mouse wheel drive `scroll_state.scroll` directly without
    /// touching focus.
    pub scroll_state: ScrollContainerState,
    /// Absolute terminal rect of the rendered `esc` close hint.
    pub esc_button_rect: Option<Rect>,
    /// Cached "remote policy before the images→Never cascade" so that
    /// flipping `Show images` back out of `Never` restores the user's
    /// prior `Show remote images` choice.  Mirrors the welcome modal's
    /// `pre_cascade_remote` (see `ui::welcome`).
    pre_cascade_remote: Option<RemoteImagePolicy>,
    /// `(row index, control rect)` for each focusable row visible in the
    /// last render, in absolute terminal coords.  Drives click dispatch;
    /// rebuilt every frame so scrolling can't leave stale geometry.
    row_hit_rects: Vec<(usize, Rect)>,
    rows: Vec<RowDef>,
}

impl SettingsState {
    pub fn new() -> Self {
        let mut state = Self {
            focused: 0,
            editing: None,
            last_error: None,
            theme_names: Vec::new(),
            scroll_state: ScrollContainerState::default(),
            esc_button_rect: None,
            pre_cascade_remote: None,
            row_hit_rects: Vec::new(),
            rows: build_rows(),
        };
        // Default focus to the first editable setting rather than the
        // "open externally" pair at the top.  Most users open the
        // overlay to tweak a setting; the externals are still one Up
        // arrow away.  Picking the first Cycle/Edit row keeps this
        // correct as the (alphabetized) row order changes.
        state.focused = state
            .rows
            .iter()
            .position(|r| {
                r.kind.focusable && matches!(r.kind.action, RowAction::Cycle | RowAction::Edit)
            })
            .or_else(|| state.first_focusable_index())
            .unwrap_or(0);
        state
    }

    /// Apply a key event, possibly mutating `config`.
    ///
    /// A numeric (text-input) row is *editable as soon as it has focus* —
    /// there is no "press Enter to begin": [`Self::open_draft_for_focused`]
    /// seeds an editable draft whenever focus lands on such a row, and
    /// typing edits the draft in place.  The draft is **committed** (parsed,
    /// validated, written to `config`) only at a boundary — Enter, or when
    /// focus leaves the row — so a multi-keystroke value still produces a
    /// single config write / flash.  An invalid draft is reverted when
    /// focus leaves; Esc closes the overlay and abandons any uncommitted
    /// draft.  Toggle / pill rows change immediately on Left/Right (or
    /// Enter), like before.
    pub fn handle_key(&mut self, key: &KeyEvent, config: &mut Config) -> SettingsResponse {
        // PgUp/PgDn/Home/End move the viewport without touching focus or
        // the open draft.
        if self.scroll_state.handle_paging_key(key) {
            return SettingsResponse::Continue;
        }

        match key.code {
            KeyCode::Esc => {
                // Abandon any uncommitted text draft and close.
                self.editing = None;
                self.last_error = None;
                SettingsResponse::Cancelled
            }
            KeyCode::Up => self.move_focus_committing(-1, config),
            KeyCode::Down => self.move_focus_committing(1, config),
            KeyCode::Left => self.apply_control_input(config, ControlInput::Left),
            KeyCode::Right => self.apply_control_input(config, ControlInput::Right),
            KeyCode::Enter => self.activate_focused(config),
            KeyCode::Backspace => {
                if let Some(buf) = self.editing.as_mut() {
                    buf.pop();
                    self.last_error = None;
                }
                SettingsResponse::Continue
            }
            KeyCode::Char(c) => {
                use crossterm::event::KeyModifiers;
                if let Some(buf) = self.editing.as_mut() {
                    if !key
                        .modifiers
                        .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
                    {
                        buf.push(c);
                        self.last_error = None;
                    }
                }
                SettingsResponse::Continue
            }
            _ => SettingsResponse::Continue,
        }
    }

    /// Insert a bracketed paste into the focused row's editable draft, if
    /// one is open.  No-op on toggle / pill rows (cycled, not typed into).
    /// The paste is flattened to one line and length-capped by
    /// [`crate::ui::sanitize_paste`]; the value is still validated when the
    /// draft commits via the row's `write_string`.
    pub fn paste(&mut self, text: &str) {
        if let Some(buf) = self.editing.as_mut() {
            buf.push_str(&crate::ui::sanitize_paste(text));
            self.last_error = None;
        }
    }

    /// Enter on the focused row: open externally, cycle a toggle / pill, or
    /// commit a text-input draft in place (staying on the row).
    fn activate_focused(&mut self, config: &mut Config) -> SettingsResponse {
        let action = self.rows.get(self.focused).map(|r| r.kind.action);
        match action {
            Some(RowAction::OpenExternalEditor) => SettingsResponse::OpenInExternalEditor,
            Some(RowAction::OpenConfigFolder) => SettingsResponse::OpenConfigFolder,
            Some(RowAction::Cycle) => self.apply_control_input(config, ControlInput::Activate),
            Some(RowAction::Edit) => self.commit_draft(config),
            None => SettingsResponse::Continue,
        }
    }

    /// Commit the focused text-input row's draft to `config`.  Returns
    /// [`SettingsResponse::FieldChanged`] when a *changed* draft validates
    /// and is written (the draft is refreshed to the normalized value, so
    /// the row stays editable); on a validation error the draft is kept and
    /// `last_error` set; an unchanged draft is a no-op.  No-op on non-edit
    /// rows.
    fn commit_draft(&mut self, config: &mut Config) -> SettingsResponse {
        let draft = match self.editing.as_deref() {
            Some(d) => d.to_owned(),
            None => return SettingsResponse::Continue,
        };
        let (is_edit, label, read, write_string) = match self.rows.get(self.focused) {
            Some(r) => (
                matches!(r.kind.action, RowAction::Edit),
                r.label,
                r.kind.read,
                r.kind.write_string,
            ),
            None => return SettingsResponse::Continue,
        };
        if !is_edit || draft == read(config, &self.theme_names) {
            return SettingsResponse::Continue;
        }
        match write_string(config, &draft) {
            Ok(()) => {
                self.last_error = None;
                self.editing = Some(read(config, &self.theme_names));
                SettingsResponse::FieldChanged(label)
            }
            Err(e) => {
                self.last_error = Some(e);
                SettingsResponse::Continue
            }
        }
    }

    /// Seed (or clear) the editable draft for the currently-focused row:
    /// a text-input row gets its current value as an editable draft, every
    /// other row clears the draft.  Called whenever focus settles on a new
    /// row so text inputs are editable on focus without an explicit "begin
    /// edit" step.
    pub(super) fn open_draft_for_focused(&mut self, config: &Config) {
        self.editing = match self.rows.get(self.focused) {
            Some(r) if matches!(r.kind.action, RowAction::Edit) => {
                Some((r.kind.read)(config, &self.theme_names))
            }
            _ => None,
        };
    }

    /// Apply a [`ControlInput`] to the focused option row through the shared
    /// transition layer ([`Control::apply`]), writing the result back into
    /// `config`.  Only applies to toggle / pill rows; no-op on numeric /
    /// edit-only and button rows (their `read_value` / `write_value` are
    /// `None`) so an accidental Left arrow doesn't surprise the user.  A
    /// disabled row (e.g. the cascade-locked remote-images row) never
    /// changes.  Changing `Show images` cascades the remote-images policy
    /// to / from `Never`, matching the welcome modal.
    fn apply_control_input(
        &mut self,
        config: &mut Config,
        input: ControlInput,
    ) -> SettingsResponse {
        // Copy the bits we need (all `Copy`: a `&'static str`, two `fn`
        // pointers, a `Control`) before mutating `config` / `self` so the
        // borrow of `self.rows` doesn't outlive the apply call.
        let (label, control, read_value, write_value, disabled) = match self.rows.get(self.focused)
        {
            Some(r) => (
                r.label,
                r.kind.options,
                r.kind.read_value,
                r.kind.write_value,
                r.is_disabled(config),
            ),
            None => return SettingsResponse::Continue,
        };
        if disabled {
            return SettingsResponse::Continue;
        }
        // Only option rows carry all three; numeric / button rows opt out.
        let (Some(control), Some(read_value), Some(write_value)) =
            (control, read_value, write_value)
        else {
            return SettingsResponse::Continue;
        };
        let was_images_never = matches!(config.images.enabled, ImagesEnabled::Never);
        match control.apply(read_value(config), input) {
            ControlEvent::Changed(next) => {
                write_value(config, next);
                if label == rows::LABEL_SHOW_IMAGES {
                    self.apply_images_cascade(config, was_images_never);
                }
                SettingsResponse::FieldChanged(label)
            }
            ControlEvent::Activated | ControlEvent::Ignored => SettingsResponse::Continue,
        }
    }

    /// Apply the images→remote cascade after `Show images` changed.
    /// Delegates to the shared [`controls::apply_images_cascade`] so
    /// the welcome modal and the settings overlay can't drift.
    fn apply_images_cascade(&mut self, config: &mut Config, was_never: bool) {
        config.images.remote_policy = controls::apply_images_cascade(
            config.images.enabled,
            was_never,
            config.images.remote_policy,
            &mut self.pre_cascade_remote,
        );
    }

    /// Move focus by `delta`, committing the row being left.  The current
    /// text-input draft (if any) is committed first — a valid change is
    /// written and surfaces as [`SettingsResponse::FieldChanged`]; an
    /// invalid or unchanged draft is silently dropped (revert-on-leave).
    /// Focus then moves and the new row's draft is opened.
    fn move_focus_committing(&mut self, delta: i32, config: &mut Config) -> SettingsResponse {
        let committed = self.commit_draft(config);
        // Leaving the row abandons any still-uncommitted (invalid) draft
        // and its error.
        self.editing = None;
        self.last_error = None;
        self.move_focus(delta, config);
        self.open_draft_for_focused(config);
        committed
    }

    fn move_focus(&mut self, delta: i32, config: &Config) {
        if let Some(idx) = next_focusable(&self.rows, self.focused, delta, |r| {
            r.focus_eligible(config)
        }) {
            self.focused = idx;
            self.scroll_state.ensure_visible(self.focused as u16);
        }
    }

    fn first_focusable_index(&self) -> Option<usize> {
        self.rows.iter().position(|r| r.kind.focusable)
    }

    /// Route a click at terminal `(col, row)` to the focusable row whose
    /// control rect (cached by the last render) it lands in.  Focuses the
    /// clicked row — committing any open draft on the row being left, exactly
    /// as an arrow move would — then acts on it: an option row cycles via the
    /// shared [`Control::apply`] (`Activate`); an external-action row fires
    /// its [`SettingsResponse`]; an edit row just takes focus (its draft is
    /// now open).  A click that misses every row, or lands on a disabled
    /// (cascade-locked) one, is a no-op.
    pub fn handle_click(&mut self, col: u16, row: u16, config: &mut Config) -> SettingsResponse {
        let Some(&(idx, _)) = self
            .row_hit_rects
            .iter()
            .find(|(_, r)| rect_contains(*r, col, row))
        else {
            return SettingsResponse::Continue;
        };
        // Re-check eligibility against the live config: a row locked since
        // the last render (e.g. the cascade-locked remote-images row)
        // absorbs the click without moving focus.
        if !self
            .rows
            .get(idx)
            .map(|r| r.focus_eligible(config))
            .unwrap_or(false)
        {
            return SettingsResponse::Continue;
        }
        let committed = self.focus_clicked_row(idx, config);
        match self.rows.get(self.focused).map(|r| r.kind.action) {
            Some(RowAction::OpenExternalEditor) => SettingsResponse::OpenInExternalEditor,
            Some(RowAction::OpenConfigFolder) => SettingsResponse::OpenConfigFolder,
            Some(RowAction::Cycle) => self.apply_control_input(config, ControlInput::Activate),
            // An edit row only takes focus (its draft opens); surface the
            // commit of whatever row we left so its live-update still fires.
            Some(RowAction::Edit) | None => committed,
        }
    }

    /// Move focus to an explicit row index — the click counterpart of
    /// [`Self::move_focus_committing`].  Commits the row being left (a valid
    /// change surfaces as [`SettingsResponse::FieldChanged`]; an invalid or
    /// unchanged draft is dropped), moves focus, and opens the new row's
    /// draft.
    fn focus_clicked_row(&mut self, idx: usize, config: &mut Config) -> SettingsResponse {
        let committed = self.commit_draft(config);
        self.editing = None;
        self.last_error = None;
        self.focused = idx;
        self.scroll_state.ensure_visible(self.focused as u16);
        self.open_draft_for_focused(config);
        committed
    }
}

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

// ─── View ──────────────────────────────────────────────────────────────────

pub struct SettingsView<'a> {
    pub theme: &'a Theme,
    pub config: &'a Config,
    pub cursor_visible: bool,
}

impl<'a> StatefulWidget for SettingsView<'a> {
    type State = SettingsState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        // Build per-row spans (without the inline description) so we
        // can size the modal and figure out which rows fit on screen.
        let row_lines = build_row_lines(state, self.config, self.theme, self.cursor_visible);
        let content_width = settings_content_width(state, self.config);

        // Pinned-bottom region: one row per description line (a
        // description may be multi-line, `\n`-separated) when the focused
        // row has one, plus 2 rows for the error footer (blank + ✗ msg).
        let focused_row = state.rows.get(state.focused);
        let focused_desc = focused_row.and_then(|r| r.resolved_description(self.config));
        let desc_rows = focused_desc
            .as_deref()
            .map(|d| d.lines().count() as u16)
            .unwrap_or(0);
        let pinned_bottom: u16 = desc_rows + (if state.last_error.is_some() { 2 } else { 0 });

        let content = ContentSize {
            width: content_width,
            height: row_lines.len() as u16,
            pinned_top: 0,
            pinned_bottom,
            ..Default::default()
        };
        let rect = centered_rect_for_content(content, area);

        // Pre-compute layout so the title's arrow indicator reflects
        // the post-observe scroll bounds.  Vertical chrome is fixed by
        // `draw_frame`; the body area below it holds the scroll list +
        // pinned footer.
        let inner_h = rect.height.saturating_sub(VERTICAL_CHROME_ROWS);
        let table_height = inner_h.saturating_sub(pinned_bottom);
        state
            .scroll_state
            .observe(row_lines.len() as u16, table_height);
        state.scroll_state.ensure_visible(state.focused as u16);

        let layout = draw_frame(
            rect,
            buf,
            FrameOpts {
                title: "Settings",
                kind: ModalKind::Normal,
                show_close_hint: true,
                content,
                theme: self.theme,
            },
        );
        state.esc_button_rect = layout.esc_hit_rect;
        let inner = layout.body;
        if inner.height < 2 || inner.width == 0 {
            return;
        }

        let scroll = state.scroll_state.scroll as usize;
        let visible_rows = table_height as usize;

        let table_area = Rect {
            x: inner.x,
            y: inner.y,
            width: inner.width,
            height: table_height,
        };
        let visible: Vec<Line<'_>> = row_lines
            .into_iter()
            .skip(scroll)
            .take(visible_rows)
            .collect();
        Paragraph::new(visible)
            .style(self.theme.modal_bg)
            .render(table_area, buf);

        // Capture per-visible-row hit-rects for click dispatch.  A click
        // anywhere on the row — focus marker, label, or control — focuses and
        // operates it, so the rect spans the whole `marker + label + value`
        // run from the body's left edge.  The label column is the wider of
        // `LABEL_PAD` and the actual label, since a label longer than the pad
        // is not truncated (the control shifts right with it).  Indices align
        // 1:1 with the `skip(scroll).take(visible_rows)` draw above.
        let end = (scroll + visible_rows).min(state.rows.len());
        let mut hit_rects: Vec<(usize, Rect)> = Vec::new();
        for idx in scroll..end {
            let row = &state.rows[idx];
            if !row.kind.focusable {
                continue;
            }
            let label_w = row.label.chars().count().max(LABEL_PAD);
            let value_w = row_value_width(row, self.config, &state.theme_names).max(1);
            let w = ((FOCUS_MARKER_WIDTH + label_w + value_w) as u16).min(table_area.width);
            hit_rects.push((
                idx,
                Rect {
                    x: table_area.x,
                    y: table_area.y + (idx - scroll) as u16,
                    width: w,
                    height: 1,
                },
            ));
        }
        state.row_hit_rects = hit_rects;

        if state.scroll_state.max_scroll() > 0 {
            let bar_area = Rect {
                x: layout.scrollbar_col,
                y: table_area.y,
                width: 1,
                height: table_area.height,
            };
            crate::ui::scrollbar::render_for_scroll_state(
                bar_area,
                &state.scroll_state,
                self.theme,
                buf,
            );
        }

        // Pinned footer: description (when present) followed by error.
        let mut footer_y = inner.y + table_height;
        if let Some(desc) = focused_desc.as_deref() {
            // No leading indent: the description left-aligns with the
            // header note ("Common options shown below …") at the body
            // edge rather than under the row labels.  A multi-line
            // description renders one row per `\n`-separated line.
            for line in desc.lines() {
                let desc_area = Rect {
                    x: inner.x,
                    y: footer_y,
                    width: inner.width,
                    height: 1,
                };
                Paragraph::new(Line::from(Span::styled(
                    line.to_owned(),
                    self.theme.modal_description,
                )))
                .style(self.theme.modal_bg)
                .render(desc_area, buf);
                footer_y += 1;
            }
        }
        if let Some(err) = state.last_error.as_ref() {
            // Blank spacer row, then the error.
            let err_area = Rect {
                x: inner.x,
                y: footer_y + 1,
                width: inner.width,
                height: 1,
            };
            Paragraph::new(Line::from(Span::styled(
                format!("✗ {err}"),
                self.theme.transient_error,
            )))
            .style(self.theme.modal_bg)
            .render(err_area, buf);
        }
    }
}

/// Build one display line per row.  The focused row's description is
/// *not* included here — it's pinned into the modal's footer instead.
fn build_row_lines<'a>(
    state: &SettingsState,
    config: &Config,
    theme: &'a Theme,
    cursor_visible: bool,
) -> Vec<Line<'a>> {
    let mut lines: Vec<Line<'_>> = Vec::with_capacity(state.rows.len());
    for (idx, row) in state.rows.iter().enumerate() {
        if !row.kind.focusable && row.label.is_empty() {
            lines.push(Line::from(""));
            continue;
        }
        if !row.kind.focusable && row.label == HEADER_NOTE {
            lines.push(Line::from(Span::styled(
                row.label.to_owned(),
                theme.modal_close_hint,
            )));
            continue;
        }
        let focused = idx == state.focused;
        let editing = focused && state.editing.is_some();
        let disabled = row.is_disabled(config);

        // The label column (marker + padding) is one unit per the control
        // scheme: when the row is focused the whole column takes the focus
        // fill — for a toggle that's the only place focus shows, since the
        // toggle widget keeps its value color.
        let marker = if focused { "› " } else { "  " };
        let label_padded = format!("{marker}{:<pad$}", row.label, pad = LABEL_PAD);
        let label_style = controls::control_label_style(focused, disabled, theme);
        let mut spans: Vec<Span<'static>> = vec![Span::styled(label_padded, label_style)];

        if let Some(control) = row.kind.options {
            // Option rows render the current value as a toggle (on/off
            // slider) or a multi-value pill, chosen by the control kind.
            let current = (row.kind.read)(config, &state.theme_names);
            match control {
                Control::Toggle => spans.extend(controls::toggle_spans(
                    current.eq_ignore_ascii_case("on"),
                    focused,
                    disabled,
                    theme,
                )),
                Control::Pill(labels) => {
                    let current_index = labels
                        .iter()
                        .position(|l| l.eq_ignore_ascii_case(&current))
                        .unwrap_or(0);
                    spans.extend(controls::pill_spans(
                        labels,
                        current_index,
                        focused,
                        disabled,
                        theme,
                    ));
                }
                Control::Button(label) => {
                    spans.extend(controls::button_spans(label, focused, theme));
                }
            }
        } else if editing {
            // Focused text-input row: render the live, editable draft with
            // a distinctly-colored (accent `theme.cursor`) blink-stable
            // block cursor at the append-only end, so the cursor itself is
            // the "type here" signal and never blends into the focus fill.
            let draft = state.editing.as_deref().unwrap_or("");
            let cursor = draft.chars().count();
            spans.extend(crate::ui::cursor::text_field_spans(
                draft,
                cursor,
                cursor_visible,
                controls::text_value_style(true, theme),
                theme.cursor,
            ));
        } else {
            // Unfocused text input or an external-action row: the value
            // styled as a text-input control (focus fill when focused,
            // `secondary` foreground at rest).
            let value = (row.kind.read)(config, &state.theme_names);
            spans.push(Span::styled(
                value,
                controls::text_value_style(focused, theme),
            ));
        }
        lines.push(Line::from(spans));
    }
    lines
}

/// Content-aware width: max over rows of `marker(2) + label_pad +
/// value_w`, plus the longest description so the pinned-footer copy
/// doesn't get clipped.  Sizes against the *whole* row set so the
/// modal width doesn't jiggle as focus moves.
fn settings_content_width(state: &SettingsState, config: &Config) -> u16 {
    let row_max = max_row_width(&state.rows, |r| {
        if !r.kind.focusable && r.label == HEADER_NOTE {
            return r.label.chars().count();
        }
        FOCUS_MARKER_WIDTH + LABEL_PAD + row_value_width(r, config, &state.theme_names)
    });
    // The description is left-aligned at the body edge (no indent), so
    // size against its raw length.  Resolve it so a dynamic description
    // (e.g. the blink cadence) can't clip.
    let desc_max = max_row_width(&state.rows, |r| {
        // A description may be multi-line (`\n`-separated); size against
        // its widest line, not the whole string.
        r.resolved_description(config)
            .map(|d| d.lines().map(|l| l.chars().count()).max().unwrap_or(0))
            .unwrap_or(0)
    });
    let err_max = optional_text_width(state.last_error.as_deref(), 2);
    row_max.max(desc_max).max(err_max)
}

/// Rendered width (in cells) of a row's value column: the control's fixed
/// width for an option/button row, or the displayed string length for a
/// numeric / external-action row.  Shared by the content-width sizing pass
/// and the click hit-rect capture so the two can't disagree.
fn row_value_width(row: &RowDef, config: &Config, theme_names: &[String]) -> usize {
    match row.kind.options {
        Some(Control::Toggle) => controls::toggle_width(),
        Some(Control::Pill(labels)) => controls::pill_width(labels),
        Some(Control::Button(label)) => controls::button_width(label),
        None => (row.kind.read)(config, theme_names).chars().count(),
    }
}

/// True when `(col, row)` falls inside `rect`.
fn rect_contains(rect: Rect, col: u16, row: u16) -> bool {
    col >= rect.x && col < rect.x + rect.width && row >= rect.y && row < rect.y + rect.height
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{ImagesEnabled, RemoteImagePolicy};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn focus_row(state: &mut SettingsState, config: &Config, label: &str) {
        let idx = state
            .rows
            .iter()
            .position(|r| r.label == label)
            .unwrap_or_else(|| panic!("missing row {label}"));
        state.focused = idx;
        // Mirror real navigation: landing on a row opens its draft so a
        // text-input row is editable on focus.
        state.open_draft_for_focused(config);
    }

    #[test]
    fn toggle_arrows_are_direction_bound() {
        // Phase 3 routed settings option rows through `Control::apply`, so
        // toggle arrows became direction-bound everywhere: Left = off,
        // Right = on (Enter/Space still flip).  Previously a settings toggle
        // flipped on either arrow; no test exercised that, so this locks in
        // the new behavior.
        let mut config = Config::default();
        config.editor.autosave_enabled = false;
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Autosave");
        // Left on an already-off toggle is a no-op (not a flip-on).
        let resp = state.handle_key(&key(KeyCode::Left), &mut config);
        assert_eq!(resp, SettingsResponse::Continue);
        assert!(!config.editor.autosave_enabled, "Left means off");
        // Right turns it on; a second Right is a no-op.
        let resp = state.handle_key(&key(KeyCode::Right), &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert!(config.editor.autosave_enabled, "Right means on");
        let resp = state.handle_key(&key(KeyCode::Right), &mut config);
        assert_eq!(resp, SettingsResponse::Continue);
        assert!(config.editor.autosave_enabled, "Right when on is a no-op");
        // Left turns it back off.
        let resp = state.handle_key(&key(KeyCode::Left), &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert!(!config.editor.autosave_enabled, "Left means off");
    }

    #[test]
    fn cycle_toggles_use_visual_line_navigation() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Use visual line navigation");
        assert!(config.editor.visual_line_nav); // default true
        let resp = state.handle_key(&key(KeyCode::Enter), &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert!(!config.editor.visual_line_nav);
    }

    #[test]
    fn cycle_toggles_vim_mode_handler() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Vim mode");
        assert_eq!(config.modal.handler, "default"); // default: off
        let resp = state.handle_key(&key(KeyCode::Enter), &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert_eq!(config.modal.handler, "vim");
        state.handle_key(&key(KeyCode::Enter), &mut config);
        assert_eq!(config.modal.handler, "default");
    }

    #[test]
    fn cycle_advances_show_images_through_ask_always_never() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Show images");
        assert_eq!(config.images.enabled, ImagesEnabled::Ask);
        state.handle_key(&key(KeyCode::Enter), &mut config);
        assert_eq!(config.images.enabled, ImagesEnabled::Always);
        state.handle_key(&key(KeyCode::Enter), &mut config);
        assert_eq!(config.images.enabled, ImagesEnabled::Never);
        state.handle_key(&key(KeyCode::Enter), &mut config);
        assert_eq!(config.images.enabled, ImagesEnabled::Ask);
    }

    #[test]
    fn editor_max_width_is_editable_on_focus_and_round_trips() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        // No "Enter to begin": focusing the row opens its draft.
        focus_row(&mut state, &config, "  Char limit");
        assert_eq!(state.editing.as_deref(), Some("100"));
        for _ in 0..3 {
            state.handle_key(&key(KeyCode::Backspace), &mut config);
        }
        for c in "200".chars() {
            state.handle_key(&key(KeyCode::Char(c)), &mut config);
        }
        // Enter commits in place and the row stays editable.
        let resp = state.handle_key(&key(KeyCode::Enter), &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert_eq!(config.editor.max_width_cols, 200);
        assert_eq!(state.editing.as_deref(), Some("200"));
    }

    #[test]
    fn text_input_commits_on_focus_leave() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "  Char limit");
        for _ in 0..3 {
            state.handle_key(&key(KeyCode::Backspace), &mut config);
        }
        for c in "200".chars() {
            state.handle_key(&key(KeyCode::Char(c)), &mut config);
        }
        // Leaving the row (without Enter) commits the valid draft.
        let resp = state.handle_key(&key(KeyCode::Up), &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert_eq!(config.editor.max_width_cols, 200);
        assert_ne!(state.rows[state.focused].label, "  Char limit");
    }

    #[test]
    fn invalid_draft_reverts_on_focus_leave() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "  Char limit");
        for _ in 0..3 {
            state.handle_key(&key(KeyCode::Backspace), &mut config);
        }
        for c in "abc".chars() {
            state.handle_key(&key(KeyCode::Char(c)), &mut config);
        }
        // Leaving with an invalid draft silently reverts — no write, no
        // lingering error.
        let resp = state.handle_key(&key(KeyCode::Up), &mut config);
        assert_eq!(resp, SettingsResponse::Continue);
        assert_eq!(config.editor.max_width_cols, 100);
        assert!(state.last_error.is_none());
    }

    #[test]
    fn enter_on_open_config_folder_row_emits_open_config_folder() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Open config folder");
        let resp = state.handle_key(&key(KeyCode::Enter), &mut config);
        assert_eq!(resp, SettingsResponse::OpenConfigFolder);
    }

    #[test]
    fn enter_on_config_toml_row_emits_open_external_editor() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Open config.toml");
        let resp = state.handle_key(&key(KeyCode::Enter), &mut config);
        assert_eq!(resp, SettingsResponse::OpenInExternalEditor);
    }

    #[test]
    fn default_focus_is_first_editable_row() {
        // Most users open Settings to adjust a setting, not the
        // externals.  Default focus skips past the open-externally
        // pair (and the divider) and lands on the first editable row
        // (alphabetically, "Autosave").
        let state = SettingsState::new();
        assert_eq!(state.rows[state.focused].label, "Autosave");
    }

    #[test]
    fn arrow_navigation_skips_divider_row() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        // Default focus is the first editable row — Up must skip the
        // blank divider and land on "Open config.toml in editor".
        state.handle_key(&key(KeyCode::Up), &mut config);
        assert_eq!(state.rows[state.focused].label, "Open config.toml");
        state.handle_key(&key(KeyCode::Up), &mut config);
        assert_eq!(state.rows[state.focused].label, "Open config folder");
    }

    #[test]
    fn left_right_cycle_show_remote_images() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "  Show remote images");
        assert_eq!(config.images.remote_policy, RemoteImagePolicy::Ask);
        state.handle_key(&key(KeyCode::Right), &mut config);
        assert_eq!(config.images.remote_policy, RemoteImagePolicy::Always);
        state.handle_key(&key(KeyCode::Left), &mut config);
        assert_eq!(config.images.remote_policy, RemoteImagePolicy::Ask);
    }

    #[test]
    fn invalid_inline_value_is_rejected() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "  Char limit");
        // Replace `100` with garbage (draft is already open on focus).
        for _ in 0..3 {
            state.handle_key(&key(KeyCode::Backspace), &mut config);
        }
        for c in "abc".chars() {
            state.handle_key(&key(KeyCode::Char(c)), &mut config);
        }
        // Enter on an invalid draft flags the error and keeps the draft
        // (the row stays editable so the user can fix it).
        let resp = state.handle_key(&key(KeyCode::Enter), &mut config);
        assert!(matches!(resp, SettingsResponse::Continue));
        assert!(state.last_error.is_some());
        assert_eq!(config.editor.max_width_cols, 100); // unchanged
        assert_eq!(state.editing.as_deref(), Some("abc"));
    }

    #[test]
    fn escape_cancels_overlay_when_not_editing() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        let resp = state.handle_key(&key(KeyCode::Esc), &mut config);
        assert_eq!(resp, SettingsResponse::Cancelled);
    }

    #[test]
    fn escape_closes_overlay_and_abandons_uncommitted_draft() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "  Char limit");
        // Type an uncommitted change, then Esc.
        for c in "9".chars() {
            state.handle_key(&key(KeyCode::Char(c)), &mut config);
        }
        assert!(state.editing.is_some());
        let resp = state.handle_key(&key(KeyCode::Esc), &mut config);
        // Esc closes the overlay (it no longer just cancels an edit) and
        // the uncommitted draft is dropped — config is untouched.
        assert_eq!(resp, SettingsResponse::Cancelled);
        assert!(state.editing.is_none());
        assert_eq!(config.editor.max_width_cols, 100);
    }

    #[test]
    fn rows_match_curated_list() {
        // The phase 10 review pinned the exact set of rows.  Lock it
        // in here so adding a new row to `build_rows` becomes an
        // explicit, reviewable change.  The empty entry between the
        // "open externally" pair and the editable settings is the
        // non-focusable divider row.
        let labels: Vec<&str> = build_rows().iter().map(|r| r.label).collect();
        assert_eq!(
            labels,
            vec![
                rows::HEADER_NOTE,
                "",
                "Open config folder",
                "Open config.toml",
                "",
                // Editable settings, alphabetized by label — except
                // "Show line numbers", grouped below the image rows.
                "Autosave",
                "Big H1 headings",
                "Blink cursor",
                "Check for updates",
                "Limit editor width",
                "  Char limit",
                "Scroll speed",
                "Diff when file changes",
                "Show diagrams",
                "Show images",
                "  Show remote images",
                "Show line numbers",
                "Show table buttons",
                "Syntax highlighting",
                "Use visual line navigation",
                "Vim mode",
            ]
        );
    }

    #[test]
    fn dropped_legacy_rows_are_absent() {
        // The review removed several rows: tab_width, line_wrap,
        // code_block_wrap, preserve_blank_lines,
        // suppress_capability_warnings, images.max_width/max_height,
        // dev.logging.  Confirm none accidentally come back via a
        // future schema rebase.
        let labels: Vec<&str> = build_rows().iter().map(|r| r.label).collect();
        for stale in [
            "editor.tab_width",
            "editor.line_wrap",
            "editor.code_block_wrap",
            "editor.preserve_blank_lines",
            "editor.suppress_capability_warnings",
            "images.max_width",
            "images.max_height",
            "dev.logging",
            // Removed from the overlay: hint duration and diff intro are
            // file-only now, and the export toggles moved to the
            // export-flow modal.
            "Hint duration",
            "Diff intro",
            "Export inlined images",
            "Export diagrams as SVG",
        ] {
            assert!(
                !labels.contains(&stale),
                "stale row '{stale}' is still in the schema"
            );
        }
    }

    // ── Scroll-container integration ────────────────────────────────────

    use ratatui::{backend::TestBackend, Terminal};

    fn theme_ref() -> &'static Theme {
        Box::leak(Box::new(Theme::default()))
    }

    fn render(state: &mut SettingsState, config: &Config, w: u16, h: u16) -> String {
        let backend = TestBackend::new(w, h);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                frame.render_stateful_widget(
                    SettingsView {
                        theme: theme_ref(),
                        config,
                        cursor_visible: true,
                    },
                    frame.area(),
                    state,
                );
            })
            .unwrap();
        terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol().chars().next().unwrap_or(' '))
            .collect()
    }

    #[test]
    fn settings_renders_scrollbar_when_more_rows_than_visible_height() {
        let config = Config::default();
        let mut state = SettingsState::new();
        // 80 cols × 8 rows: only ~5 row slots after frame + footer.
        // Settings has 13 rows.
        let contents = render(&mut state, &config, 80, 12);
        assert!(
            contents.contains('█'),
            "expected scrollbar thumb glyph, got: {contents}"
        );
    }

    #[test]
    fn settings_pgdown_advances_scroll_without_moving_focus() {
        let config = Config::default();
        let mut state = SettingsState::new();
        render(&mut state, &config, 80, 12);
        let focused_before = state.focused;
        state.handle_key(&key(KeyCode::PageDown), &mut Config::default());
        assert_eq!(state.focused, focused_before, "PgDn must not move focus");
        assert!(state.scroll_state.scroll > 0, "PgDn must advance scroll");
    }

    #[test]
    fn settings_wheel_scrolls_list() {
        let config = Config::default();
        let mut state = SettingsState::new();
        render(&mut state, &config, 80, 12);
        let focused_before = state.focused;
        state.scroll_state.scroll_by(2);
        assert_eq!(state.scroll_state.scroll, 2);
        assert_eq!(state.focused, focused_before);
    }

    #[test]
    fn settings_modal_width_shrinks_to_content_in_wide_terminal() {
        let config = Config::default();
        let mut state = SettingsState::new();
        let term_w = 200u16;
        let term_h = 30u16;
        let contents = render(&mut state, &config, term_w, term_h);
        let max_border = (0..term_h)
            .map(|y| {
                let row: String = contents
                    .chars()
                    .skip((y as usize) * term_w as usize)
                    .take(term_w as usize)
                    .collect();
                row.chars().filter(|&c| c == '─').count()
            })
            .max()
            .unwrap_or(0);
        let modal_width = max_border + 2;
        // 80% of 200 would be 160; content is much narrower.
        assert!(
            modal_width < 130,
            "expected content-aware width well below 80% of 200, got modal width {modal_width}"
        );
    }

    #[test]
    fn option_row_marks_current_value_with_focused_style_when_focused() {
        let config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Show images");
        let theme = theme_ref();
        let lines = build_row_lines(&state, &config, theme, true);
        let row = lines
            .iter()
            .find(|l| {
                l.spans
                    .first()
                    .is_some_and(|s| s.content.contains("Show images"))
            })
            .expect("Show images row");
        let ask_pill = row
            .spans
            .iter()
            .find(|s| s.content.contains("Ask"))
            .unwrap();
        assert_eq!(ask_pill.style, theme.modal_button_focused);
    }

    #[test]
    fn settings_description_appears_in_pinned_footer() {
        let config = Config::default();
        let mut state = SettingsState::new();
        // Default focus is on the first editable row ("Autosave"),
        // which has a description.
        let contents = render(&mut state, &config, 100, 25);
        assert!(
            contents.contains("Automatically save"),
            "expected focused-row description in pinned footer, got: {contents}"
        );
    }

    #[test]
    fn blink_cursor_description_embeds_config_cadence() {
        // The "Blink cursor" row's description is dynamic: it reads the
        // file-only `cursor_blink_ms` so the hint reflects the user's
        // configured cadence rather than a hardcoded value.
        let mut config = Config::default();
        config.editor.cursor_blink_ms = 777;
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Blink cursor");
        let contents = render(&mut state, &config, 100, 30);
        assert!(
            contents.contains("Blink cursor every 777 ms"),
            "expected dynamic blink description, got: {contents}"
        );
    }

    #[test]
    fn blink_cursor_row_toggles_config_flag() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Blink cursor");
        assert!(config.editor.cursor_blink); // default on
        let resp = state.handle_key(&key(KeyCode::Enter), &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert!(!config.editor.cursor_blink);
    }

    #[test]
    fn check_for_updates_row_toggles_config_flag() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Check for updates");
        assert!(config.editor.check_for_updates, "opt-out, so on by default");
        let resp = state.handle_key(&key(KeyCode::Enter), &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert!(!config.editor.check_for_updates);
    }

    // ── Click dispatch ──────────────────────────────────────────────────

    /// Resolve the cached control rect for a labeled row after a render.
    fn rect_for(state: &SettingsState, label: &str) -> Rect {
        let idx = state
            .rows
            .iter()
            .position(|r| r.label == label)
            .unwrap_or_else(|| panic!("missing row {label}"));
        state
            .row_hit_rects
            .iter()
            .find(|(i, _)| *i == idx)
            .map(|(_, r)| *r)
            .unwrap_or_else(|| panic!("row {label} not in hit rects (off-screen?)"))
    }

    #[test]
    fn click_cycles_a_pill_row_and_focuses_it() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        render(&mut state, &config, 120, 40);
        assert_eq!(config.images.enabled, ImagesEnabled::Ask);
        let r = rect_for(&state, "Show images");
        let resp = state.handle_click(r.x, r.y, &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert_eq!(config.images.enabled, ImagesEnabled::Always);
        assert_eq!(state.rows[state.focused].label, "Show images");
    }

    #[test]
    fn click_flips_a_toggle_row() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        render(&mut state, &config, 120, 40);
        let before = config.editor.autosave_enabled;
        let r = rect_for(&state, "Autosave");
        let resp = state.handle_click(r.x, r.y, &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert_eq!(config.editor.autosave_enabled, !before);
    }

    #[test]
    fn click_on_a_long_label_row_operates_its_shifted_control() {
        // A label longer than `LABEL_PAD` is not truncated, so the control
        // renders further right than the padded column.  The hit-rect must
        // stretch to cover it: a click on the control cell still toggles, and
        // a click on the label cell does too (the whole row is one target).
        const LONG: &str = "Autosave with an unusually long label";
        assert!(
            LONG.chars().count() > LABEL_PAD,
            "label must exceed the pad to exercise the shift"
        );
        let mut config = Config::default();
        let mut state = SettingsState::new();
        // Repoint an existing toggle row at the long label.
        let idx = state
            .rows
            .iter()
            .position(|r| r.label == "Autosave")
            .expect("autosave row");
        state.rows[idx].label = LONG;
        render(&mut state, &config, 120, 40);

        let r = rect_for(&state, LONG);
        // The control sits past the `marker + label` run — beyond where the
        // old fixed `LABEL_PAD`-based rect would have ended.
        let control_col = r.x + (FOCUS_MARKER_WIDTH + LONG.chars().count()) as u16;
        assert!(
            control_col < r.x + r.width,
            "hit-rect must reach the shifted control"
        );
        let before = config.editor.autosave_enabled;
        let resp = state.handle_click(control_col, r.y, &mut config);
        assert!(matches!(resp, SettingsResponse::FieldChanged(_)));
        assert_eq!(config.editor.autosave_enabled, !before);

        // A click on the label cell operates the same control.
        state.handle_click(r.x, r.y, &mut config);
        assert_eq!(config.editor.autosave_enabled, before);
    }

    #[test]
    fn click_external_action_row_emits_its_response() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        render(&mut state, &config, 120, 40);
        let r = rect_for(&state, "Open config folder");
        assert_eq!(
            state.handle_click(r.x, r.y, &mut config),
            SettingsResponse::OpenConfigFolder
        );
    }

    #[test]
    fn click_on_a_locked_row_is_a_noop() {
        // Images Never locks the remote-images row; a click on it must not
        // move focus or change config.
        let mut config = Config::default();
        config.images.enabled = ImagesEnabled::Never;
        config.images.remote_policy = RemoteImagePolicy::Never;
        let mut state = SettingsState::new();
        render(&mut state, &config, 120, 40);
        let focused_before = state.focused;
        let r = rect_for(&state, "  Show remote images");
        let resp = state.handle_click(r.x, r.y, &mut config);
        assert_eq!(resp, SettingsResponse::Continue);
        assert_eq!(
            state.focused, focused_before,
            "locked row absorbs the click"
        );
        assert_eq!(config.images.remote_policy, RemoteImagePolicy::Never);
    }

    #[test]
    fn click_that_misses_every_row_is_a_noop() {
        let mut config = Config::default();
        let mut state = SettingsState::new();
        render(&mut state, &config, 120, 40);
        let focused_before = state.focused;
        // Column 0 is the focus-marker gutter, left of every control rect.
        let resp = state.handle_click(0, 0, &mut config);
        assert_eq!(resp, SettingsResponse::Continue);
        assert_eq!(state.focused, focused_before);
    }

    #[test]
    fn show_images_never_cascades_remote_to_never_and_locks_row() {
        // Mirrors the welcome modal: cycling Show images to Never forces
        // remote to Never, disables the remote row, and skips it on
        // navigation; leaving Never restores the prior remote choice.
        let mut config = Config::default();
        config.images.remote_policy = RemoteImagePolicy::Always;
        let mut state = SettingsState::new();
        focus_row(&mut state, &config, "Show images");
        // Ask → Always → Never.
        state.handle_key(&key(KeyCode::Enter), &mut config);
        state.handle_key(&key(KeyCode::Enter), &mut config);
        assert_eq!(config.images.enabled, ImagesEnabled::Never);
        assert_eq!(config.images.remote_policy, RemoteImagePolicy::Never);

        // The remote row is now disabled and skipped by Down navigation.
        let remote_idx = state
            .rows
            .iter()
            .position(|r| r.label == "  Show remote images")
            .unwrap();
        assert!(state.rows[remote_idx].is_disabled(&config));
        state.focused = remote_idx - 1; // row just above the locked one
        state.handle_key(&key(KeyCode::Down), &mut config);
        assert_ne!(state.focused, remote_idx, "Down must skip the locked row");

        // Leave Never (Never → Ask) — prior remote choice is restored.
        focus_row(&mut state, &config, "Show images");
        state.handle_key(&key(KeyCode::Enter), &mut config);
        assert_eq!(config.images.enabled, ImagesEnabled::Ask);
        assert_eq!(config.images.remote_policy, RemoteImagePolicy::Always);
        assert!(!state.rows[remote_idx].is_disabled(&config));
    }
}