fresh-editor 0.3.8

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
//! Mouse input handling for the Settings dialog.
//!
//! This module contains all mouse event handling for the settings modal,
//! including clicks, scrolling, and drag operations.

use crate::app::Editor;
use anyhow::Result as AnyhowResult;
use rust_i18n::t;

use super::items::SettingControl;
use super::{FocusPanel, SettingsHit, SettingsLayout};
use crate::view::controls::DualListColumn;

/// Computed layout for entry dialog hit testing
struct EntryDialogLayout {
    dialog_x: u16,
    dialog_y: u16,
    dialog_width: u16,
    dialog_height: u16,
    inner_x: u16,
    inner_y: u16,
    inner_width: u16,
    inner_height: u16,
    button_y: u16,
    scrollbar_x: u16,
}

impl EntryDialogLayout {
    /// Compute entry dialog layout from modal area
    fn from_modal(modal: ratatui::layout::Rect) -> Option<Self> {
        if modal.width == 0 || modal.height == 0 {
            return None;
        }

        let dialog_width = (modal.width * 85 / 100).clamp(50, 90);
        let dialog_height = (modal.height * 90 / 100).max(15);
        let dialog_x = modal.x + (modal.width.saturating_sub(dialog_width)) / 2;
        let dialog_y = modal.y + (modal.height.saturating_sub(dialog_height)) / 2;

        Some(Self {
            dialog_x,
            dialog_y,
            dialog_width,
            dialog_height,
            inner_x: dialog_x + 2,
            inner_y: dialog_y + 1,
            inner_width: dialog_width.saturating_sub(4),
            inner_height: dialog_height.saturating_sub(5),
            button_y: dialog_y + dialog_height - 2,
            scrollbar_x: dialog_x + dialog_width - 3,
        })
    }

    fn contains(&self, col: u16, row: u16) -> bool {
        col >= self.dialog_x
            && col < self.dialog_x + self.dialog_width
            && row >= self.dialog_y
            && row < self.dialog_y + self.dialog_height
    }

    fn in_content_area(&self, col: u16, row: u16) -> bool {
        col >= self.inner_x
            && col < self.inner_x + self.inner_width
            && row >= self.inner_y
            && row < self.inner_y + self.inner_height
    }

    fn near_scrollbar(&self, col: u16) -> bool {
        col >= self.scrollbar_x.saturating_sub(2) && col <= self.dialog_x + self.dialog_width
    }
}

impl Editor {
    /// Handle mouse events when settings modal is open.
    pub(crate) fn handle_settings_mouse(
        &mut self,
        mouse_event: crossterm::event::MouseEvent,
        is_double_click: bool,
    ) -> AnyhowResult<bool> {
        use crossterm::event::{MouseButton, MouseEventKind};

        let col = mouse_event.column;
        let row = mouse_event.row;

        // When help overlay is open, consume all mouse events
        if let Some(ref state) = self.settings_state {
            if state.showing_help {
                return Ok(false);
            }
        }

        // Handle confirm dialog mouse events
        let showing_confirm = self
            .settings_state
            .as_ref()
            .map(|s| s.showing_confirm_dialog)
            .unwrap_or(false);
        if showing_confirm {
            match mouse_event.kind {
                MouseEventKind::Moved => {
                    let hover = self.get_confirm_dialog_button_at(col, row);
                    if let Some(ref mut state) = self.settings_state {
                        state.confirm_dialog_hover = hover;
                    }
                    return Ok(hover.is_some());
                }
                MouseEventKind::Down(MouseButton::Left) => {
                    return self.handle_confirm_dialog_click(col, row);
                }
                _ => {}
            }
            return Ok(false);
        }

        // Handle mouse events for entry dialog
        if let Some(ref mut state) = self.settings_state {
            if state.showing_entry_dialog() {
                match mouse_event.kind {
                    MouseEventKind::Moved => {
                        return Ok(self.entry_dialog_update_hover(col, row));
                    }
                    MouseEventKind::ScrollUp => {
                        if let Some(dialog) = state.entry_dialog_mut() {
                            dialog.scroll_up();
                            return Ok(true);
                        }
                    }
                    MouseEventKind::ScrollDown => {
                        if let Some(dialog) = state.entry_dialog_mut() {
                            dialog.scroll_down(20);
                            return Ok(true);
                        }
                    }
                    MouseEventKind::Drag(MouseButton::Left) => {
                        return Ok(self.entry_dialog_scrollbar_drag(col, row));
                    }
                    MouseEventKind::Down(MouseButton::Left) => {
                        return self.handle_entry_dialog_click(col, row, is_double_click);
                    }
                    _ => {}
                }
                return Ok(false);
            }
        }

        // Track hover position and compute hover hit for visual feedback
        match mouse_event.kind {
            MouseEventKind::Moved => {
                let hover_hit = self
                    .active_chrome()
                    .settings_layout
                    .as_ref()
                    .and_then(|layout: &SettingsLayout| layout.hit_test(col, row));

                if let Some(ref mut state) = self.settings_state {
                    let old_hit = state.hover_hit;
                    state.hover_position = Some((col, row));
                    state.hover_hit = hover_hit;

                    // Update dropdown hover index when hovering over options
                    let new_hover_idx = match hover_hit {
                        Some(SettingsHit::ControlDropdownOption(_, opt_idx)) => Some(opt_idx),
                        _ => None,
                    };
                    let hover_changed = state.set_dropdown_hover(new_hover_idx);

                    return Ok(old_hit != hover_hit || hover_changed);
                }
                return Ok(false);
            }
            MouseEventKind::ScrollUp => {
                // If a dropdown is open, forward scroll to it
                if let Some(ref mut state) = self.settings_state {
                    if state.is_dropdown_open() {
                        state.dropdown_scroll(-3);
                        return Ok(true);
                    }
                    // If search is active and we have results, scroll search results
                    if state.search_active && !state.search_results.is_empty() {
                        return Ok(state.search_scroll_up(3));
                    }
                }
                // Wheel over the categories panel scrolls it independently.
                if self.over_categories_panel(col, row) {
                    if let Some(ref mut state) = self.settings_state {
                        state.categories_scroll.scroll.scroll_by(-3);
                        return Ok(true);
                    }
                }
                return Ok(self.settings_scroll_up(3));
            }
            MouseEventKind::ScrollDown => {
                // If a dropdown is open, forward scroll to it
                if let Some(ref mut state) = self.settings_state {
                    if state.is_dropdown_open() {
                        state.dropdown_scroll(3);
                        return Ok(true);
                    }
                    // If search is active and we have results, scroll search results
                    if state.search_active && !state.search_results.is_empty() {
                        return Ok(state.search_scroll_down(3));
                    }
                }
                if self.over_categories_panel(col, row) {
                    if let Some(ref mut state) = self.settings_state {
                        state.categories_scroll.scroll.scroll_by(3);
                        return Ok(true);
                    }
                }
                return Ok(self.settings_scroll_down(3));
            }
            MouseEventKind::Drag(MouseButton::Left) => {
                // Check if dragging on search scrollbar
                if let Some(ref mut state) = self.settings_state {
                    if state.search_active && !state.search_results.is_empty() {
                        if let Some(scrolled) = self.search_scrollbar_drag(col, row) {
                            return Ok(scrolled);
                        }
                    }
                }
                return Ok(self.settings_scrollbar_drag(col, row));
            }
            MouseEventKind::Down(MouseButton::Left) => {}
            _ => return Ok(false),
        }

        // Use cached settings layout for hit testing
        let Some(hit) = self
            .active_chrome()
            .settings_layout
            .as_ref()
            .and_then(|layout: &SettingsLayout| layout.hit_test(col, row))
        else {
            return Ok(false);
        };

        // Check if a dropdown is open and click is outside of it
        if let Some(ref mut state) = self.settings_state {
            if state.is_dropdown_open() {
                let is_click_on_open_dropdown = matches!(
                    hit,
                    SettingsHit::ControlDropdown(idx) | SettingsHit::ControlDropdownOption(idx, _)
                        if idx == state.selected_item
                );
                if !is_click_on_open_dropdown {
                    state.dropdown_cancel();
                    return Ok(true);
                }
            }
        }

        match hit {
            SettingsHit::Outside | SettingsHit::Background | SettingsHit::SettingsPanel => {}
            SettingsHit::Category(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Categories);
                    state.selected_category = idx;
                    state.selected_item = 0;
                    state.scroll_panel = crate::view::ui::ScrollablePanel::new();
                    state.sub_focus = None;
                    // Click lands the cursor on the category row itself
                    // (not on a section), even after auto-expand reveals
                    // child sections — matches keyboard Up/Down arriving
                    // here.
                    state.tree_cursor_section = None;
                    // Deliberate click on a category — auto-expand so the
                    // user immediately sees its sections.
                    state.auto_expand_current_category();
                }
            }
            SettingsHit::CategoryDisclosure(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.toggle_category_expanded(idx);
                }
            }
            SettingsHit::CategorySection(cat_idx, section_idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.jump_to_section(cat_idx, section_idx);
                }
            }
            SettingsHit::CategoriesPanel | SettingsHit::CategoriesScrollbar => {
                // Click without scroll wheel — no-op for now (the panel-area
                // hit only fires when no other category/section row was hit).
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Categories);
                }
            }
            SettingsHit::SearchResult(idx) => {
                // Click on search result - select it and jump to it (same as Enter)
                if let Some(ref mut state) = self.settings_state {
                    state.selected_search_result = idx;
                    state.jump_to_search_result();
                }
            }
            SettingsHit::Item(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                }
            }
            SettingsHit::ControlToggle(idx) | SettingsHit::ControlDropdown(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                }
                self.settings_activate_current();
            }
            SettingsHit::ControlDropdownOption(idx, option_idx) => {
                // Click on a dropdown option - select it and close dropdown
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.dropdown_select(option_idx);
                }
            }
            SettingsHit::ControlDecrement(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                }
                self.settings_decrement_current();
            }
            SettingsHit::ControlIncrement(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                }
                self.settings_increment_current();
            }
            SettingsHit::ControlNumberValue(idx) => {
                // Click on the value between the brackets — focus the item
                // and enter inline editing mode (matches the Enter-key flow).
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.start_number_editing();
                }
            }
            SettingsHit::ControlText(idx) | SettingsHit::ControlTextListRow(idx, _) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.start_editing();
                }
            }
            SettingsHit::ControlMapRow(idx, row_idx) => {
                let is_add_new_row = if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;

                    let mut is_add_new = false;
                    if let Some(page) = state.pages.get_mut(state.selected_category) {
                        if let Some(item) = page.items.get_mut(idx) {
                            if let SettingControl::Map(map_state) = &mut item.control {
                                is_add_new = row_idx >= map_state.entries.len();
                                map_state.focused_entry = if row_idx < map_state.entries.len() {
                                    Some(row_idx)
                                } else {
                                    None
                                };
                            }
                        }
                    }
                    is_add_new
                } else {
                    false
                };
                // "Add new" row activates on single click (#604), entries require double-click
                if is_add_new_row || is_double_click {
                    self.settings_activate_current();
                }
            }
            SettingsHit::ControlMapAddNew(idx) => {
                // Click on map add-new row - focus it and activate immediately
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;

                    if let Some(page) = state.pages.get_mut(state.selected_category) {
                        if let Some(item) = page.items.get_mut(idx) {
                            if let SettingControl::Map(map_state) = &mut item.control {
                                map_state.focused_entry = None; // Focus add-new row
                            }
                        }
                    }
                }
                // Single click on add-new activates immediately
                self.settings_activate_current();
            }
            SettingsHit::ControlDualListAvailable(idx, row) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.with_dual_list_mut(idx, |dl| {
                        dl.active_column = DualListColumn::Available;
                        dl.available_cursor = row;
                    });
                    state.start_editing();
                }
            }
            SettingsHit::ControlDualListIncluded(idx, row) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.with_dual_list_mut(idx, |dl| {
                        dl.active_column = DualListColumn::Included;
                        dl.included_cursor = row;
                    });
                    state.start_editing();
                }
            }
            SettingsHit::ControlDualListAdd(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.with_dual_list_mut(idx, |dl| dl.add_selected());
                    state.on_value_changed();
                    state.refresh_dual_list_sibling();
                }
            }
            SettingsHit::ControlDualListRemove(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.with_dual_list_mut(idx, |dl| dl.remove_selected());
                    state.on_value_changed();
                    state.refresh_dual_list_sibling();
                }
            }
            SettingsHit::ControlDualListMoveUp(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.with_dual_list_mut(idx, |dl| dl.move_up());
                    state.on_value_changed();
                }
            }
            SettingsHit::ControlDualListMoveDown(idx) => {
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.with_dual_list_mut(idx, |dl| dl.move_down());
                    state.on_value_changed();
                }
            }
            SettingsHit::ControlInherit(idx) => {
                // Click on [Inherit] button - set value to null (inherited)
                if let Some(ref mut state) = self.settings_state {
                    state.focus.set(FocusPanel::Settings);
                    state.selected_item = idx;
                    state.set_current_to_null();
                }
            }
            SettingsHit::LayerButton => {
                if let Some(ref mut state) = self.settings_state {
                    state.cycle_target_layer();
                }
            }
            SettingsHit::SaveButton => self.close_settings(true),
            SettingsHit::CancelButton => {
                if let Some(ref mut state) = self.settings_state {
                    if state.has_changes() {
                        state.showing_confirm_dialog = true;
                        state.confirm_dialog_selection = 0;
                    } else {
                        state.visible = false;
                    }
                }
            }
            SettingsHit::ResetButton => {
                if let Some(ref mut state) = self.settings_state {
                    state.reset_current_to_default();
                }
            }
            SettingsHit::ClearCategoryButton => {
                if let Some(ref mut state) = self.settings_state {
                    state.clear_current_category();
                }
            }
            SettingsHit::EditButton => {
                // Open config file for the selected layer
                if let Some(ref state) = self.settings_state {
                    let layer = state.target_layer;
                    // Best-effort: open may fail if file doesn't exist yet
                    #[allow(clippy::let_underscore_must_use)]
                    let _ = self.open_config_file(layer);
                }
            }
            SettingsHit::Scrollbar => self.settings_scrollbar_click(row),
            SettingsHit::SearchScrollbar => self.search_scrollbar_click(row),
            SettingsHit::SearchResultsPanel => {
                // Clicking on search results panel background - no action needed
            }
        }

        Ok(true)
    }

    /// Whether the given screen coords sit inside the categories panel —
    /// used to route mouse-wheel events to the correct scroll target.
    fn over_categories_panel(&self, col: u16, row: u16) -> bool {
        self.active_chrome()
            .settings_layout
            .as_ref()
            .and_then(|layout| layout.categories_panel_area)
            .is_some_and(|area| {
                col >= area.x
                    && col < area.x.saturating_add(area.width)
                    && row >= area.y
                    && row < area.y.saturating_add(area.height)
            })
    }

    fn settings_scroll_up(&mut self, delta: usize) -> bool {
        self.settings_state
            .as_mut()
            .map(|state| state.scroll_up(delta))
            .unwrap_or(false)
    }

    fn settings_scroll_down(&mut self, delta: usize) -> bool {
        self.settings_state
            .as_mut()
            .map(|state| state.scroll_down(delta))
            .unwrap_or(false)
    }

    fn settings_scrollbar_click(&mut self, row: u16) {
        if let Some(ref scrollbar_area) = self
            .active_chrome()
            .settings_layout
            .as_ref()
            .and_then(|l| l.scrollbar_area)
        {
            if scrollbar_area.height > 0 {
                let relative_y = row.saturating_sub(scrollbar_area.y);
                let ratio = relative_y as f32 / scrollbar_area.height as f32;
                if let Some(ref mut state) = self.settings_state {
                    state.scroll_to_ratio(ratio);
                }
            }
        }
    }

    fn settings_scrollbar_drag(&mut self, col: u16, row: u16) -> bool {
        if let Some(ref scrollbar_area) = self
            .active_chrome()
            .settings_layout
            .as_ref()
            .and_then(|l| l.scrollbar_area)
        {
            let in_scrollbar_x = col >= scrollbar_area.x.saturating_sub(1)
                && col <= scrollbar_area.x + scrollbar_area.width;
            if in_scrollbar_x && scrollbar_area.height > 0 {
                let relative_y = row.saturating_sub(scrollbar_area.y);
                let ratio = relative_y as f32 / scrollbar_area.height as f32;
                if let Some(ref mut state) = self.settings_state {
                    return state.scroll_to_ratio(ratio);
                }
            }
        }
        false
    }

    fn search_scrollbar_click(&mut self, row: u16) {
        if let Some(ref scrollbar_area) = self
            .active_chrome()
            .settings_layout
            .as_ref()
            .and_then(|l| l.search_scrollbar_area)
        {
            if scrollbar_area.height > 0 {
                let relative_y = row.saturating_sub(scrollbar_area.y);
                let ratio = relative_y as f32 / scrollbar_area.height as f32;
                if let Some(ref mut state) = self.settings_state {
                    state.search_scroll_to_ratio(ratio);
                }
            }
        }
    }

    fn search_scrollbar_drag(&mut self, col: u16, row: u16) -> Option<bool> {
        if let Some(ref scrollbar_area) = self
            .active_chrome()
            .settings_layout
            .as_ref()
            .and_then(|l| l.search_scrollbar_area)
        {
            let in_scrollbar_x = col >= scrollbar_area.x.saturating_sub(1)
                && col <= scrollbar_area.x + scrollbar_area.width;
            if in_scrollbar_x && scrollbar_area.height > 0 {
                let relative_y = row.saturating_sub(scrollbar_area.y);
                let ratio = relative_y as f32 / scrollbar_area.height as f32;
                if let Some(ref mut state) = self.settings_state {
                    return Some(state.search_scroll_to_ratio(ratio));
                }
            }
        }
        None // Not on search scrollbar
    }

    fn entry_dialog_layout(&self) -> Option<EntryDialogLayout> {
        self.active_chrome()
            .settings_layout
            .as_ref()
            .and_then(|l| EntryDialogLayout::from_modal(l.modal_area))
    }

    fn entry_dialog_scrollbar_drag(&mut self, col: u16, row: u16) -> bool {
        let Some(layout) = self.entry_dialog_layout() else {
            return false;
        };

        if layout.near_scrollbar(col) && layout.inner_height > 0 {
            let relative_y = row.saturating_sub(layout.inner_y);
            let ratio = (relative_y as f32 / layout.inner_height as f32).clamp(0.0, 1.0);

            if let Some(ref mut state) = self.settings_state {
                if let Some(dialog) = state.entry_dialog_mut() {
                    dialog.scroll_to_ratio(ratio);
                    return true;
                }
            }
        }
        false
    }

    fn entry_dialog_update_hover(&mut self, col: u16, row: u16) -> bool {
        let Some(layout) = self.entry_dialog_layout() else {
            return false;
        };

        let Some(ref mut state) = self.settings_state else {
            return false;
        };
        let Some(dialog) = state.entry_dialog_mut() else {
            return false;
        };

        let old_item = dialog.hover_item;
        let old_button = dialog.hover_button;

        // Reset hover state
        dialog.hover_item = None;
        dialog.hover_button = None;

        if !layout.contains(col, row) {
            return old_item.is_some() || old_button.is_some();
        }

        // Check button hover. Layout matches `render_entry_dialog`:
        // [Save, Cancel] or [Save, Cancel, Delete] with a wider gap
        // before Delete so the destructive button stands apart.
        if row == layout.button_y {
            let has_delete = !dialog.is_new && !dialog.no_delete;
            let buttons: &[&str] = if has_delete {
                &["[ Save ]", "[ Cancel ]", "[ Delete ]"]
            } else {
                &["[ Save ]", "[ Cancel ]"]
            };
            let delete_idx = if has_delete {
                Some(buttons.len() - 1)
            } else {
                None
            };
            const BUTTON_GAP: u16 = 2;
            const DELETE_GAP: u16 = 6;
            let total_width: u16 = buttons
                .iter()
                .enumerate()
                .map(|(i, b)| {
                    let gap = if Some(i) == delete_idx {
                        DELETE_GAP
                    } else if i == 0 {
                        0
                    } else {
                        BUTTON_GAP
                    };
                    b.len() as u16 + gap
                })
                .sum();
            let mut x = layout.dialog_x + (layout.dialog_width.saturating_sub(total_width)) / 2;

            for (idx, label) in buttons.iter().enumerate() {
                if idx > 0 {
                    let gap = if Some(idx) == delete_idx {
                        DELETE_GAP
                    } else {
                        BUTTON_GAP
                    };
                    x += gap;
                }
                let width = label.len() as u16;
                if col >= x && col < x + width {
                    dialog.hover_button = Some(idx);
                    break;
                }
                x += width;
            }
        }

        // Check item hover (only for editable items)
        if layout.in_content_area(col, row) {
            let click_y = (row - layout.inner_y) as usize + dialog.scroll_offset;
            let mut content_y: usize = 0;

            // Check if we have a separator between read-only and editable items
            let first_editable = dialog.first_editable_index;
            let has_separator = first_editable > 0 && first_editable < dialog.items.len();

            for (idx, item) in dialog.items.iter().enumerate() {
                // Account for separator before first editable item
                if has_separator && idx == first_editable {
                    content_y += 1; // separator height
                }

                let item_end = content_y + item.control.control_height() as usize;
                if click_y >= content_y && click_y < item_end {
                    // Only hover on editable items
                    if !item.read_only {
                        dialog.hover_item = Some(idx);
                    }
                    break;
                }
                content_y = item_end;
            }
        }

        old_item != dialog.hover_item || old_button != dialog.hover_button
    }

    fn handle_entry_dialog_click(
        &mut self,
        col: u16,
        row: u16,
        _is_double_click: bool,
    ) -> AnyhowResult<bool> {
        let Some(layout) = self.entry_dialog_layout() else {
            return Ok(false);
        };

        if !layout.contains(col, row) {
            return Ok(false);
        }

        // Button click
        if row == layout.button_y {
            return self.handle_entry_dialog_button_click(col, &layout);
        }

        // Item click
        if layout.in_content_area(col, row) {
            return self.handle_entry_dialog_item_click(col, row, &layout);
        }

        Ok(false)
    }

    fn handle_entry_dialog_button_click(
        &mut self,
        col: u16,
        layout: &EntryDialogLayout,
    ) -> AnyhowResult<bool> {
        let Some(ref mut state) = self.settings_state else {
            return Ok(false);
        };
        let Some(dialog) = state.entry_dialog_mut() else {
            return Ok(false);
        };

        let has_delete = !dialog.is_new && !dialog.no_delete;
        let buttons: &[&str] = if has_delete {
            &["[ Save ]", "[ Cancel ]", "[ Delete ]"]
        } else {
            &["[ Save ]", "[ Cancel ]"]
        };
        let delete_idx = if has_delete {
            Some(buttons.len() - 1)
        } else {
            None
        };
        const BUTTON_GAP: u16 = 2;
        const DELETE_GAP: u16 = 6;
        let total_width: u16 = buttons
            .iter()
            .enumerate()
            .map(|(i, b)| {
                let gap = if Some(i) == delete_idx {
                    DELETE_GAP
                } else if i == 0 {
                    0
                } else {
                    BUTTON_GAP
                };
                b.len() as u16 + gap
            })
            .sum();
        let mut x = layout.dialog_x + (layout.dialog_width.saturating_sub(total_width)) / 2;

        for (idx, label) in buttons.iter().enumerate() {
            if idx > 0 {
                let gap = if Some(idx) == delete_idx {
                    DELETE_GAP
                } else {
                    BUTTON_GAP
                };
                x += gap;
            }
            let width = label.len() as u16;
            if col >= x && col < x + width {
                dialog.focus_on_buttons = true;
                dialog.focused_button = idx;
                return self.settings_entry_dialog_activate_button();
            }
            x += width;
        }
        Ok(false)
    }

    fn handle_entry_dialog_item_click(
        &mut self,
        col: u16,
        row: u16,
        layout: &EntryDialogLayout,
    ) -> AnyhowResult<bool> {
        let Some(ref mut state) = self.settings_state else {
            return Ok(false);
        };
        let Some(dialog) = state.entry_dialog_mut() else {
            return Ok(false);
        };

        let click_y = (row - layout.inner_y) as usize + dialog.scroll_offset;
        let mut content_y: usize = 0;

        // Check if we have a separator between read-only and editable items
        let first_editable = dialog.first_editable_index;
        let has_separator = first_editable > 0 && first_editable < dialog.items.len();

        for (idx, item) in dialog.items.iter().enumerate() {
            // Account for separator before first editable item
            if has_separator && idx == first_editable {
                content_y += 1; // separator height
            }

            let item_end = content_y + item.control.control_height() as usize;
            if click_y >= content_y && click_y < item_end {
                // Skip clicks on read-only items
                if item.read_only {
                    return Ok(false);
                }
                let sub_row = click_y - content_y;
                // TextList rows render as: label (sub_row 0), one row
                // per committed item, then the trailing add-new row.
                // Map the click to either remove (`[x]`), focus +
                // edit (text area), or activate-pending (`[+] Add new`
                // / input `[+]`). Without this, every click in a
                // TextList row just opened the input, ignoring `[x]`
                // and the row-text targets entirely.
                if matches!(item.control, SettingControl::TextList(_)) {
                    return self.handle_text_list_click(idx, sub_row, col, layout);
                }
                dialog.focus_on_buttons = false;
                dialog.selected_item = idx;
                dialog.update_focus_states();
                if !dialog.editing_text {
                    dialog.start_editing();
                }
                return Ok(true);
            }
            content_y = item_end;
        }
        Ok(false)
    }

    fn handle_text_list_click(
        &mut self,
        item_idx: usize,
        sub_row: usize,
        col: u16,
        _layout: &EntryDialogLayout,
    ) -> AnyhowResult<bool> {
        let Some(ref mut state) = self.settings_state else {
            return Ok(false);
        };
        let Some(dialog) = state.entry_dialog_mut() else {
            return Ok(false);
        };
        let item = match dialog.items.get_mut(item_idx) {
            Some(it) => it,
            None => return Ok(false),
        };
        let tl = match &mut item.control {
            SettingControl::TextList(s) => s,
            _ => return Ok(false),
        };

        // sub_row 0 is the label row.
        if sub_row == 0 {
            // Focus the control on a generic label click; user
            // can keyboard from there.
            dialog.focus_on_buttons = false;
            dialog.selected_item = item_idx;
            dialog.update_focus_states();
            return Ok(true);
        }

        let n_items = tl.items.len();
        // Compute which TextList row was clicked: existing item rows
        // are sub_row 1..=n_items, the add-new row is sub_row n_items+1.
        let on_add_row = sub_row == n_items + 1;
        let item_row_idx = if !on_add_row { Some(sub_row - 1) } else { None };

        // Hit-test the trailing button (`[x]` or `[+]`). The renderer
        // uses indent=2 then `[xxx]` for actual_field_width chars, then
        // ` ` then `[x]` or `[+]` (3 chars). The dialog inner area starts
        // at `inner_x + focus_indicator_width` (3 cols). Computing the
        // exact column would need the actual_field_width, which we
        // don't carry here; treat anything in the rightmost ~5 chars
        // of the rendered row that the user is likely to click as the
        // trailing button. With the dialog defaulting to 30-char fields
        // this lands cleanly on `[x]` / `[+]`.
        let dialog_inner_right = _layout.dialog_x + _layout.dialog_width.saturating_sub(2);
        let in_trailing_button = col + 5 >= dialog_inner_right
            || {
                // Fallback: if the row text is shorter than the field
                // (common — items rarely fill 30 chars), the user clicks
                // the [x] which is right after `]`. Use a hand-rolled
                // approximation: text_indent + field_width + 1 ≤ col.
                let text_indent = _layout.dialog_x + 2 + 3 /* focus indicator */ + 2 /* TextList indent */ + 1 /* `[` */;
                let estimated_field_width = 28u16;
                col >= text_indent + estimated_field_width + 1
            };

        match (on_add_row, item_row_idx, in_trailing_button) {
            // Click on `[+]` of an active input: commit pending.
            (true, _, true) if tl.pending_active || !tl.new_item_text.is_empty() => {
                tl.add_item();
                dialog.user_edited = true;
                dialog.focus_on_buttons = false;
                dialog.selected_item = item_idx;
                tl.focused_item = None;
                tl.pending_active = false;
                dialog.update_focus_states();
                Ok(true)
            }
            // Click anywhere on the (collapsed) `[+] Add new` row, or
            // on the input text area: focus the trailing slot and
            // activate input mode so the user can start typing.
            (true, _, _) => {
                dialog.focus_on_buttons = false;
                dialog.selected_item = item_idx;
                tl.activate_pending();
                dialog.editing_text = true;
                dialog.update_focus_states();
                Ok(true)
            }
            // Click on `[x]` of a committed row: remove it.
            (false, Some(row_idx), true) if row_idx < tl.items.len() => {
                tl.remove_item(row_idx);
                dialog.user_edited = true;
                dialog.focus_on_buttons = false;
                dialog.selected_item = item_idx;
                dialog.update_focus_states();
                Ok(true)
            }
            // Click on a committed row's text area: focus that item.
            (false, Some(row_idx), false) if row_idx < tl.items.len() => {
                dialog.focus_on_buttons = false;
                dialog.selected_item = item_idx;
                tl.focused_item = Some(row_idx);
                tl.pending_active = false;
                dialog.update_focus_states();
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    fn settings_entry_dialog_activate_button(&mut self) -> AnyhowResult<bool> {
        let Some(ref mut state) = self.settings_state else {
            return Ok(false);
        };

        let (btn, has_delete) = {
            let Some(dialog) = state.entry_dialog() else {
                return Ok(false);
            };
            let has_delete = !dialog.is_new && !dialog.no_delete;
            (dialog.focused_button, has_delete)
        };

        // Button order: [Save, Cancel] or [Save, Cancel, Delete].
        match (btn, has_delete) {
            (0, _) => state.save_entry_dialog(),
            (1, _) => state.close_entry_dialog(),
            (2, true) => state.request_entry_delete_confirm(),
            _ => state.close_entry_dialog(),
        }
        Ok(true)
    }

    fn handle_confirm_dialog_click(&mut self, col: u16, row: u16) -> AnyhowResult<bool> {
        if let Some(idx) = self.get_confirm_dialog_button_at(col, row) {
            match idx {
                0 => self.save_settings_and_close(),
                1 => self.discard_settings_and_close(),
                2 => {
                    if let Some(ref mut state) = self.settings_state {
                        state.showing_confirm_dialog = false;
                    }
                }
                _ => {}
            }
            return Ok(true);
        }
        Ok(false)
    }

    /// Returns which confirm dialog button (0-2) is at the given position, if any
    fn get_confirm_dialog_button_at(&self, col: u16, row: u16) -> Option<usize> {
        let modal_area = self
            .active_chrome()
            .settings_layout
            .as_ref()
            .map(|l| l.modal_area)?;

        let changes_count = self
            .settings_state
            .as_ref()
            .map(|s| s.get_change_descriptions().len())
            .unwrap_or(0);

        // Calculate dialog dimensions (same as in render_confirm_dialog)
        let dialog_width = 50u16.min(modal_area.width.saturating_sub(4));
        let dialog_height = (7 + changes_count as u16)
            .min(20)
            .min(modal_area.height.saturating_sub(4));
        let dialog_x = modal_area.x + (modal_area.width.saturating_sub(dialog_width)) / 2;
        let dialog_y = modal_area.y + (modal_area.height.saturating_sub(dialog_height)) / 2;

        let inner_x = dialog_x + 2;
        let inner_width = dialog_width.saturating_sub(4);
        let button_y = dialog_y + dialog_height - 3;

        // Check if on button row
        if row != button_y {
            return None;
        }

        // Button labels (must match render_confirm_dialog)
        let options = [
            t!("confirm.save_and_exit").to_string(),
            t!("confirm.discard").to_string(),
            t!("confirm.cancel").to_string(),
        ];
        let total_width: u16 = options.iter().map(|o| o.len() as u16 + 4).sum::<u16>() + 4;
        let mut x = inner_x + (inner_width.saturating_sub(total_width)) / 2;

        for (idx, label) in options.iter().enumerate() {
            let button_width = label.len() as u16 + 4;
            if col >= x && col < x + button_width + 1 {
                return Some(idx);
            }
            x += button_width + 3;
        }

        None
    }

    fn save_settings_and_close(&mut self) {
        self.save_settings();
        if let Some(ref mut state) = self.settings_state {
            state.visible = false;
            state.showing_confirm_dialog = false;
        }
    }

    fn discard_settings_and_close(&mut self) {
        if let Some(ref mut state) = self.settings_state {
            state.visible = false;
            state.showing_confirm_dialog = false;
        }
    }
}