tslime 0.1.1

A lightweight terminal screensaver simulating slime mold growth patterns
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
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
use crate::cli::Palette;
use crate::overlay::input::{KeyHint, OverlayInputHandler};
use crate::palette_manager;
use crate::render::palette::{
    interpolate_gradient, oklch_to_rgb, oklch_to_srgb, srgb_to_oklch, GradientStop, OklchColor,
    RgbColor,
};
use crate::render::panel::{
    footer_hints, Padding, PanelBuilder, RenderedOverlay, RichCell, TextAlignment,
};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

/// Number of colors in the palette gradient.
pub const PALETTE_COLOR_COUNT: usize = 11;

/// Number of spaces between keybind and label columns in the keybind section.
/// Set this to adjust column spacing in the Palette Editor keybinds panel.
pub const KEYBIND_LABEL_GAP: usize = 3;

/// Inner content width (between box borders + single space padding on each side).
const INNER_W: usize = 52;

/// Column offset from the start of an overlay line to the first content character.
/// With Padding::COMPACT (left=1) and a border: border(1) + padding.left(1) = 2.
const CONTENT_OFFSET: usize = 2;

/// Length of the OKLch slider track in characters.
const TRACK_LEN: usize = 38;

/// Maximum chroma value for slider display and clamping.
const MAX_CHROMA: f32 = 0.4;

/// Row indices for the palette editor overlay layout.
/// These are 0-indexed positions within the overlay content.
mod rows {
    /// Stop selector row (diamond indicators for palette colors).
    pub const STOP_SELECTOR: usize = 3;

    /// Lightness slider row.
    pub const LIGHTNESS_SLIDER: usize = 9;

    /// Chroma slider row.
    pub const CHROMA_SLIDER: usize = 12;

    /// Hue slider row.
    pub const HUE_SLIDER: usize = 15;

    /// First hint row (arrow key indicators).
    pub const HINT_ARROWS: usize = 18;

    /// Second hint row (adjust indicators).
    pub const HINT_ADJUST: usize = 19;

    /// Third hint row (Tab navigation).
    pub const HINT_TAB: usize = 20;

    /// Gradient preview strip row.
    pub const GRADIENT_STRIP: usize = 27;
}

// ─── Component enum ──────────────────────────────────────────────────────────

/// Component of the OKLch color being edited.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorComponent {
    /// Lightness component (0.0-1.0).
    Lightness,
    /// Chroma component (0.0-~0.4).
    Chroma,
    /// Hue component (0-360 degrees).
    Hue,
}

impl EditorComponent {
    /// Cycle to the next component in the L→C→H→L sequence.
    pub fn next(self) -> Self {
        match self {
            Self::Lightness => Self::Chroma,
            Self::Chroma => Self::Hue,
            Self::Hue => Self::Lightness,
        }
    }

    /// Cycle to the previous component in L←C←H←L sequence.
    pub fn prev(self) -> Self {
        match self {
            Self::Lightness => Self::Hue,
            Self::Chroma => Self::Lightness,
            Self::Hue => Self::Chroma,
        }
    }
}

// ─── Editor mode ─────────────────────────────────────────────────────────────

/// Current mode of the palette editor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorMode {
    /// Editing colors in the OKLch picker.
    Editing,
    /// Save dialog for naming and saving the current palette.
    SaveDialog,
    /// Load dialog for selecting a saved palette.
    LoadDialog,
}

// ─── Editor state ────────────────────────────────────────────────────────────

/// State of the palette editor overlay.
#[derive(Debug, Clone)]
pub struct PaletteEditorState {
    /// Current editor mode (Editing, SaveDialog, LoadDialog).
    pub mode: EditorMode,
    /// Index of the currently selected color (0-10 = individual stop, 11 = ALL).
    pub selected_color_index: usize,
    /// Currently selected OKLch component being edited.
    pub selected_component: EditorComponent,
    /// Current palette colors.
    pub colors: [RgbColor; PALETTE_COLOR_COUNT],
    /// Original colors when editor was opened (for discard/reset).
    pub original_colors: [RgbColor; PALETTE_COLOR_COUNT],
    /// Name of the base palette being edited.
    pub base_palette_name: String,
    /// Whether the palette has been modified.
    pub is_modified: bool,
    /// Input buffer for save dialog. `tui_input::Input` tracks value + cursor for
    /// mid-string editing (arrows/Home/End/Delete), not just append/backspace.
    pub save_name_input: tui_input::Input,
    /// Index of the currently selected saved palette in load dialog.
    pub saved_palette_index: usize,
    /// List of saved palettes from storage.
    pub saved_palettes_list: Vec<crate::palette_manager::SavedPalette>,
    /// Stored hue values for each color to preserve hue when chroma → 0.
    /// When chroma is near 0, hue becomes "powerless" (undefined per CSS Color Module Level 4).
    /// These stored values ensure hue is preserved during grayscale transitions.
    pub stored_hues: [f32; PALETTE_COLOR_COUNT],
}

impl PaletteEditorState {
    /// Create a new palette editor state from the given palette.
    pub fn new(palette: &Palette) -> Self {
        let colors = get_palette_colors(palette);
        let base_palette_name = palette.name().to_string();

        // Initialize stored hues from the initial palette colors
        let mut stored_hues = [0.0f32; PALETTE_COLOR_COUNT];
        for (i, &color) in colors.iter().enumerate() {
            let oklch = srgb_to_oklch(color);
            // If hue is NaN (color is grayscale), default to 0
            stored_hues[i] = if oklch.h.is_nan() { 0.0 } else { oklch.h };
        }

        Self {
            mode: EditorMode::Editing,
            selected_color_index: PALETTE_COLOR_COUNT,
            selected_component: EditorComponent::Lightness,
            colors,
            original_colors: colors,
            base_palette_name,
            is_modified: false,
            save_name_input: tui_input::Input::default(),
            saved_palette_index: 0,
            saved_palettes_list: Vec::new(),
            stored_hues,
        }
    }

    /// True when the special "ALL" slot is selected (index == PALETTE_COLOR_COUNT).
    pub fn is_all_selected(&self) -> bool {
        self.selected_color_index == PALETTE_COLOR_COUNT
    }

    /// Circular mean hue, linear mean lightness/chroma across all stops.
    /// Uses stored hues to preserve hue values when chroma is near 0 (powerless).
    fn average_oklch(&self) -> OklchColor {
        use crate::render::palette::OKLCH_EPSILON;

        let mut sin_sum = 0.0f32;
        let mut cos_sum = 0.0f32;
        let mut l_sum = 0.0f32;
        let mut c_sum = 0.0f32;
        let mut hue_count = 0;

        for (i, &color) in self.colors.iter().enumerate() {
            let oklch = srgb_to_oklch(color);
            l_sum += oklch.l;
            c_sum += oklch.c;

            // Use stored hue to avoid NaN when chroma ≈ 0
            // Only colors with non-negligible chroma contribute to hue average
            let hue = if oklch.c >= OKLCH_EPSILON {
                oklch.h
            } else {
                self.stored_hues[i]
            };

            if hue.is_finite() {
                let h_rad = hue.to_radians();
                sin_sum += h_rad.sin();
                cos_sum += h_rad.cos();
                hue_count += 1;
            }
        }

        let n = PALETTE_COLOR_COUNT as f32;
        let avg_h = if hue_count > 0 {
            let avg = sin_sum.atan2(cos_sum).to_degrees();
            if avg < 0.0 {
                avg + 360.0
            } else {
                avg
            }
        } else {
            0.0 // Default when no valid hues
        };

        OklchColor {
            l: l_sum / n,
            c: c_sum / n,
            h: avg_h,
        }
    }

    /// Get the OKLch color of the currently selected color (average when ALL selected).
    /// Uses stored hue when chroma is near 0 to preserve the intended hue value.
    pub fn current_oklch(&self) -> OklchColor {
        use crate::render::palette::OKLCH_EPSILON;

        if self.is_all_selected() {
            self.average_oklch()
        } else {
            let idx = self.selected_color_index;
            let mut oklch = srgb_to_oklch(self.colors[idx]);

            // When chroma is near 0, hue becomes "powerless" (NaN).
            // Use the stored hue to preserve the intended color.
            if oklch.c < OKLCH_EPSILON || oklch.h.is_nan() {
                oklch.h = self.stored_hues[idx];
            }

            oklch
        }
    }

    /// Set the RGB color of the currently selected color (no-op when ALL selected).
    pub fn set_current_color(&mut self, rgb: RgbColor) {
        if self.selected_color_index < PALETTE_COLOR_COUNT {
            self.colors[self.selected_color_index] = rgb;
            self.is_modified = true;
        }
    }

    /// Adjust all colors (or the selected one) using `f` to modify the OKLch value.
    /// Also updates stored_hues when chroma transitions from 0 to non-zero.
    fn adjust_oklch<F: Fn(&mut OklchColor)>(&mut self, f: F) {
        use crate::render::palette::OKLCH_EPSILON;

        if self.is_all_selected() {
            for i in 0..PALETTE_COLOR_COUNT {
                let mut oklch = srgb_to_oklch(self.colors[i]);
                let old_c = oklch.c;
                f(&mut oklch);

                // If chroma was 0 and is now non-zero, use stored hue
                if old_c < OKLCH_EPSILON && oklch.c >= OKLCH_EPSILON {
                    oklch.h = self.stored_hues[i];
                }

                self.colors[i] = oklch_to_rgb(oklch);

                // Update stored hue if chroma is still non-zero
                if oklch.c >= OKLCH_EPSILON {
                    self.stored_hues[i] = oklch.h;
                }
            }
            self.is_modified = true;
        } else {
            let idx = self.selected_color_index;
            let mut oklch = srgb_to_oklch(self.colors[idx]);
            let old_c = oklch.c;
            f(&mut oklch);

            // If chroma was 0 and is now non-zero, use stored hue
            if old_c < OKLCH_EPSILON && oklch.c >= OKLCH_EPSILON {
                oklch.h = self.stored_hues[idx];
            }

            self.set_current_color(oklch_to_rgb(oklch));

            // Update stored hue if chroma is still non-zero
            if oklch.c >= OKLCH_EPSILON {
                self.stored_hues[idx] = oklch.h;
            }
        }
    }

    /// Adjust the hue of the selected color(s) by `delta` degrees.
    /// Also updates stored_hues to preserve the new hue value.
    pub fn adjust_hue(&mut self, delta: f32) {
        self.adjust_oklch_with_hue_override(delta);
    }

    /// Helper to adjust OKLch with proper hue handling for NaN cases.
    /// Uses stored_hue as base when current chroma is too low.
    /// This is the single source of truth for hue adjustments.
    fn adjust_oklch_with_hue_override(&mut self, delta: f32) {
        use crate::render::palette::OKLCH_EPSILON;

        if self.is_all_selected() {
            for i in 0..PALETTE_COLOR_COUNT {
                let mut oklch = srgb_to_oklch(self.colors[i]);

                // Use stored hue as base if current hue is NaN (powerless)
                let base_hue = if oklch.h.is_nan() || oklch.c < OKLCH_EPSILON {
                    self.stored_hues[i]
                } else {
                    oklch.h
                };

                let new_hue = (base_hue + delta + 360.0) % 360.0;
                oklch.h = new_hue;
                self.colors[i] = oklch_to_rgb(oklch);

                // Update stored hue (single source of truth)
                self.stored_hues[i] = new_hue;
            }
            self.is_modified = true;
        } else {
            let idx = self.selected_color_index;
            let mut oklch = srgb_to_oklch(self.colors[idx]);

            // Use stored hue as base if current hue is NaN (powerless)
            let base_hue = if oklch.h.is_nan() || oklch.c < OKLCH_EPSILON {
                self.stored_hues[idx]
            } else {
                oklch.h
            };

            let new_hue = (base_hue + delta + 360.0) % 360.0;
            oklch.h = new_hue;
            self.colors[idx] = oklch_to_rgb(oklch);

            // Update stored hue (single source of truth)
            self.stored_hues[idx] = new_hue;

            self.is_modified = true;
        }
    }

    /// Adjust the chroma of the selected color(s) by `delta`.
    /// Preserves stored_hues so hue can be restored when chroma increases from 0.
    pub fn adjust_chroma(&mut self, delta: f32) {
        self.adjust_oklch(|oklch| oklch.c = (oklch.c + delta).clamp(0.0, MAX_CHROMA));
    }

    /// Adjust the lightness of the selected color(s) by `delta`.
    pub fn adjust_lightness(&mut self, delta: f32) {
        self.adjust_oklch(|oklch| oklch.l = (oklch.l + delta).clamp(0.0, 1.0));
    }

    /// Adjust the currently selected component by `delta`.
    pub fn adjust_selected_component(&mut self, delta: f32) {
        match self.selected_component {
            EditorComponent::Lightness => self.adjust_lightness(delta),
            EditorComponent::Chroma => self.adjust_chroma(delta),
            EditorComponent::Hue => self.adjust_hue(delta * 360.0),
        }
    }

    /// Reset colors to the original values when editor was opened.
    /// Also resets stored_hues to match the original colors.
    pub fn reset_to_original(&mut self) {
        self.colors = self.original_colors;

        // Recalculate stored hues from original colors
        for (i, &color) in self.colors.iter().enumerate() {
            let oklch = srgb_to_oklch(color);
            self.stored_hues[i] = if oklch.h.is_nan() { 0.0 } else { oklch.h };
        }
        self.is_modified = false;
    }

    /// Select the next color in the palette (wraps through ALL slot at index 11).
    pub fn select_next_color(&mut self) {
        self.selected_color_index = (self.selected_color_index + 1) % (PALETTE_COLOR_COUNT + 1);
    }

    /// Select the previous color in the palette (wraps back through ALL slot).
    pub fn select_prev_color(&mut self) {
        self.selected_color_index = if self.selected_color_index == 0 {
            PALETTE_COLOR_COUNT // wraps back to ALL slot
        } else {
            self.selected_color_index - 1
        };
    }

    /// Get the display name for the current palette state.
    pub fn display_name(&self) -> String {
        if self.is_modified {
            format!("{} (modified)", self.base_palette_name)
        } else {
            self.base_palette_name.clone()
        }
    }

    /// Returns the current colors as a `Palette::Custom` (used for live preview).
    pub fn to_palette(&self) -> Palette {
        Palette::Custom(self.colors.to_vec())
    }
}

impl OverlayInputHandler for PaletteEditorState {
    fn handle_key(&mut self, key: &KeyEvent) -> bool {
        match key.code {
            KeyCode::Esc => {
                match self.mode {
                    EditorMode::SaveDialog => {
                        self.save_name_input.reset();
                        self.mode = EditorMode::Editing;
                    }
                    EditorMode::LoadDialog => {
                        self.mode = EditorMode::Editing;
                    }
                    EditorMode::Editing => {
                        return false; // Signal to close overlay
                    }
                }
                true
            }
            KeyCode::Left => {
                if matches!(self.mode, EditorMode::SaveDialog) {
                    self.save_name_input
                        .handle(tui_input::InputRequest::GoToPrevChar);
                } else {
                    self.select_prev_color();
                }
                true
            }
            KeyCode::Right => {
                if matches!(self.mode, EditorMode::SaveDialog) {
                    self.save_name_input
                        .handle(tui_input::InputRequest::GoToNextChar);
                } else {
                    self.select_next_color();
                }
                true
            }
            KeyCode::Up => {
                if matches!(self.mode, EditorMode::LoadDialog) {
                    if self.saved_palette_index > 0 {
                        self.saved_palette_index -= 1;
                    }
                } else {
                    match self.selected_component {
                        EditorComponent::Lightness => self.adjust_lightness(0.02),
                        EditorComponent::Chroma => self.adjust_chroma(0.01),
                        EditorComponent::Hue => self.adjust_hue(5.0),
                    }
                }
                true
            }
            KeyCode::Down => {
                if matches!(self.mode, EditorMode::LoadDialog) {
                    if self.saved_palette_index + 1 < self.saved_palettes_list.len() {
                        self.saved_palette_index += 1;
                    }
                } else {
                    match self.selected_component {
                        EditorComponent::Lightness => self.adjust_lightness(-0.02),
                        EditorComponent::Chroma => self.adjust_chroma(-0.01),
                        EditorComponent::Hue => self.adjust_hue(-5.0),
                    }
                }
                true
            }
            KeyCode::Tab => {
                self.selected_component = self.selected_component.next();
                true
            }
            KeyCode::Char('h') | KeyCode::Char('H') => {
                self.selected_component = EditorComponent::Hue;
                true
            }
            KeyCode::Char('c') | KeyCode::Char('C') => {
                self.selected_component = EditorComponent::Chroma;
                true
            }
            KeyCode::Char('l') => {
                self.selected_component = EditorComponent::Lightness;
                true
            }
            KeyCode::Char('L') => {
                if let Ok(palettes) = palette_manager::list_palettes() {
                    self.saved_palettes_list = palettes;
                    self.saved_palette_index = 0;
                }
                self.mode = EditorMode::LoadDialog;
                true
            }
            KeyCode::Char('r') | KeyCode::Char('R') => {
                self.reset_to_original();
                true
            }
            KeyCode::Char('s') | KeyCode::Char('S') => {
                if key.modifiers.contains(KeyModifiers::CONTROL) {
                    self.mode = EditorMode::SaveDialog;
                }
                true
            }
            KeyCode::Enter => {
                match self.mode {
                    EditorMode::Editing => {
                        return false; // Signal to apply and close
                    }
                    EditorMode::SaveDialog => {
                        if !self.save_name_input.value().is_empty() {
                            let palette = palette_manager::SavedPalette::new(
                                self.save_name_input.value().to_string(),
                                self.colors,
                            );
                            if let Err(e) = palette_manager::save_palette(palette) {
                                eprintln!("Failed to save palette: {}", e);
                            }
                        }
                        self.save_name_input.reset();
                        self.mode = EditorMode::Editing;
                    }
                    EditorMode::LoadDialog => {
                        if let Some(palette) =
                            self.saved_palettes_list.get(self.saved_palette_index)
                        {
                            self.colors = palette.to_rgb_colors();
                            self.original_colors = palette.to_rgb_colors();
                            self.base_palette_name = palette.name.clone();
                            self.is_modified = false;
                        }
                        self.mode = EditorMode::Editing;
                    }
                }
                true
            }
            KeyCode::Char(c) => {
                if matches!(self.mode, EditorMode::SaveDialog)
                    && !key.modifiers.contains(KeyModifiers::CONTROL)
                {
                    if self.save_name_input.value().chars().count() < 24 {
                        self.save_name_input
                            .handle(tui_input::InputRequest::InsertChar(c));
                    }
                    true
                } else {
                    false
                }
            }
            KeyCode::Backspace => {
                if matches!(self.mode, EditorMode::SaveDialog) {
                    self.save_name_input
                        .handle(tui_input::InputRequest::DeletePrevChar);
                    true
                } else {
                    false
                }
            }
            KeyCode::Delete => {
                if matches!(self.mode, EditorMode::SaveDialog) {
                    self.save_name_input
                        .handle(tui_input::InputRequest::DeleteNextChar);
                    true
                } else {
                    false
                }
            }
            KeyCode::Home => {
                if matches!(self.mode, EditorMode::SaveDialog) {
                    self.save_name_input
                        .handle(tui_input::InputRequest::GoToStart);
                    true
                } else {
                    false
                }
            }
            KeyCode::End => {
                if matches!(self.mode, EditorMode::SaveDialog) {
                    self.save_name_input
                        .handle(tui_input::InputRequest::GoToEnd);
                    true
                } else {
                    false
                }
            }
            _ => false,
        }
    }

    fn key_hints(&self) -> Vec<KeyHint> {
        vec![
            KeyHint::new("←/→", "Select color"),
            KeyHint::new("↑/↓", "Adjust value"),
            KeyHint::new("Tab", "Cycle L/C/H"),
            KeyHint::new("Enter", "Apply/Confirm"),
            KeyHint::new("Ctrl+S", "Save palette"),
            KeyHint::new("Esc", "Discard/Cancel"),
            KeyHint::new("r", "Reset"),
            KeyHint::new("L", "Load palette"),
        ]
    }
}

/// Get the 11 gradient colors from a palette.
fn get_palette_colors(palette: &Palette) -> [RgbColor; PALETTE_COLOR_COUNT] {
    use crate::render::palette::get_gradient_stops;

    let stops = get_gradient_stops(palette);
    let mut colors = [RgbColor { r: 0, g: 0, b: 0 }; PALETTE_COLOR_COUNT];

    for (i, color) in colors.iter_mut().enumerate() {
        let t = i as f32 / (PALETTE_COLOR_COUNT - 1) as f32;
        *color = interpolate_gradient(&stops, t);
    }

    colors
}

// ─── Private content builders ─────────────────────────────────────────────────

/// Build the stop selector row: 11 color slots + 1 ALL slot, each 4 chars wide.
/// Returns 48 chars (12 × 4) for centering within INNER_W.
fn build_swatches_str(selected: usize) -> String {
    let mut s = String::with_capacity(48);
    for i in 0..PALETTE_COLOR_COUNT {
        if i == selected {
            s.push_str("");
        } else {
            s.push_str("");
        }
    }
    if selected == PALETTE_COLOR_COUNT {
        s.push_str("");
    } else {
        s.push_str("");
    }
    s
}

/// Build the stop index label row: " 1   2  … 11  ALL", returns 48 chars for centering.
fn build_swatch_labels_str() -> String {
    let mut s = String::with_capacity(48);
    for i in 1..=PALETTE_COLOR_COUNT {
        if i < 10 {
            s.push_str(&format!(" {i}  "));
        } else {
            s.push_str(&format!("{i}  "));
        }
    }
    s.push_str("ALL ");
    s
}

/// Build OKLch slider label (with arrows if active).
fn build_slider_label(is_active: bool, comp: char, value_str: &str) -> String {
    if is_active {
        format!("{} {}", comp, value_str)
    } else {
        format!("  {} {}  ", comp, value_str)
    }
}

/// Build OKLch slider bar (38 chars with ◆ cursor).
fn build_slider_bar(frac: f32) -> String {
    let cursor_pos =
        ((frac.clamp(0.0, 1.0) * (TRACK_LEN - 1) as f32).round() as usize).min(TRACK_LEN - 1);
    (0..TRACK_LEN)
        .map(|i| if i == cursor_pos { '' } else { '' })
        .collect()
}

/// Build per-cell color overrides for the editing overlay.
///
/// Layout (rows are 0-indexed within overlay content):
/// 0  top border
/// 1-2  empty
/// 3  stop selector     ← ◉/○ indicators colored by stop color
/// 4  swatch labels
/// 5  empty
/// 6  separator
/// 7  empty
/// 8  L slider label
/// 9  L slider          ← lightness gradient track
/// 10 empty
/// 11 C slider label
/// 12 C slider          ← chroma gradient track
/// 13 empty
/// 14 H slider label
/// 15 H slider          ← hue rainbow track
/// 16 empty
/// 17 separator
/// 18-24 hint rows
/// 25 empty
/// 26 separator
/// 27 gradient preview strip ← ▄ with fg=color(t), bg=color(t+Δ)
fn build_editor_rich_lines(
    state: &PaletteEditorState,
    lines: &[String],
    oklch: OklchColor,
    text_primary: RgbColor,
    accent: RgbColor,
    panel_bg: RgbColor,
) -> Vec<Vec<RichCell>> {
    let mut rich: Vec<Vec<RichCell>> = lines
        .iter()
        .map(|l| l.chars().map(|c| (c, None, None)).collect())
        .collect();

    let stops: Vec<GradientStop> = state
        .colors
        .iter()
        .enumerate()
        .map(|(i, &color)| GradientStop {
            position: i as f32 / (PALETTE_COLOR_COUNT - 1) as f32,
            color,
        })
        .collect();

    // Line 3: centered stops — shift column offset by +2 for centering
    if rich.len() > rows::STOP_SELECTOR {
        for i in 0..PALETTE_COLOR_COUNT {
            let col = CONTENT_OFFSET + 2 + i * 4 + 1;
            if col < rich[rows::STOP_SELECTOR].len() {
                rich[rows::STOP_SELECTOR][col].1 = Some(state.colors[i]);
            }
        }
        let all_col = CONTENT_OFFSET + 2 + PALETTE_COLOR_COUNT * 4 + 1;
        if all_col < rich[rows::STOP_SELECTOR].len() {
            let all_color = if state.is_all_selected() {
                RgbColor {
                    r: 255,
                    g: 255,
                    b: 255,
                }
            } else {
                RgbColor {
                    r: 140,
                    g: 140,
                    b: 140,
                }
            };
            rich[rows::STOP_SELECTOR][all_col].1 = Some(all_color);
        }
    }

    // Color hint keys (lines 18-24) with accent color.

    // Line 18: "← select →" — accent arrow characters
    if rich.len() > rows::HINT_ARROWS {
        for (c, fg, _) in rich[rows::HINT_ARROWS].iter_mut() {
            if *c == '' || *c == '' {
                *fg = Some(accent);
            }
        }
    }

    // Line 19: "↑ adjust ↓" — accent arrow characters
    if rich.len() > rows::HINT_ADJUST {
        for (c, fg, _) in rich[rows::HINT_ADJUST].iter_mut() {
            if *c == '' || *c == '' {
                *fg = Some(accent);
            }
        }
    }

    // Line 20: "Tab  L → C → H" — accent "Tab" and "→" arrows.
    // Search tab_line directly (char-indexed) to avoid the byte-vs-char mismatch
    // that arises when line_str.find() returns a byte offset: the '│' border glyph
    // is 3 bytes but 1 char, shifting all subsequent byte offsets by +2.
    if rich.len() > rows::HINT_TAB {
        let tab_line = &mut rich[rows::HINT_TAB];
        let tab_pos = (0..tab_line.len().saturating_sub(2)).find(|&i| {
            tab_line[i].0 == 'T' && tab_line[i + 1].0 == 'a' && tab_line[i + 2].0 == 'b'
        });
        if let Some(pos) = tab_pos {
            for col in pos..(pos + 3).min(tab_line.len()) {
                tab_line[col].1 = Some(accent);
            }
        }
        for (c, fg, _) in tab_line.iter_mut() {
            if *c == '' {
                *fg = Some(accent);
            }
        }
    }

    // Lines 21-24: each line is "{key}  {label}" centered independently.
    // Search for the key chars directly in the rich line (char-indexed) to avoid
    // the byte-vs-char offset bug that byte-based string search would introduce.
    let hint_keys = ["r", "Enter", "Ctrl+S", "Esc"];
    for (i, &line_idx) in [21usize, 22, 23, 24].iter().enumerate() {
        if line_idx >= rich.len() {
            continue;
        }
        let key_chars: Vec<char> = hint_keys[i].chars().collect();
        let key_len = key_chars.len();
        let line = &mut rich[line_idx];
        let pos = (0..line.len().saturating_sub(key_len.saturating_sub(1))).find(|&j| {
            key_chars
                .iter()
                .enumerate()
                .all(|(k, &c)| line.get(j + k).map(|(ch, _, _)| *ch == c).unwrap_or(false))
        });
        if let Some(pos) = pos {
            for col in pos..pos + key_len {
                if col < line.len() {
                    line[col].1 = Some(accent);
                }
            }
        }
    }

    // L bar (lightness slider): dark-to-light gradient at current chroma and hue.
    let l_cursor = (oklch.l * (TRACK_LEN - 1) as f32).round() as usize;
    if rich.len() > rows::LIGHTNESS_SLIDER {
        let l_start = CONTENT_OFFSET + 7; // centered offset
        for i in 0..TRACK_LEN {
            let col = l_start + i;
            if col < rich[rows::LIGHTNESS_SLIDER].len() {
                let l = i as f32 / (TRACK_LEN - 1) as f32;
                let color = oklch_to_srgb(l, oklch.c.min(0.15), oklch.h);
                if i == l_cursor {
                    rich[rows::LIGHTNESS_SLIDER][col] = ('', Some(text_primary), Some(color));
                } else {
                    rich[rows::LIGHTNESS_SLIDER][col] = ('', Some(color), Some(panel_bg));
                }
            }
        }
    }

    // C bar (chroma slider): gray-to-vivid gradient at current lightness and hue.
    let c_frac = (oklch.c / MAX_CHROMA).clamp(0.0, 1.0);
    let c_cursor = (c_frac * (TRACK_LEN - 1) as f32).round() as usize;
    if rich.len() > rows::CHROMA_SLIDER {
        let c_start = CONTENT_OFFSET + 7;
        for i in 0..TRACK_LEN {
            let col = c_start + i;
            if col < rich[rows::CHROMA_SLIDER].len() {
                let c = (i as f32 / (TRACK_LEN - 1) as f32) * MAX_CHROMA;
                let color = oklch_to_srgb(oklch.l.max(0.4), c, oklch.h);
                if i == c_cursor {
                    rich[rows::CHROMA_SLIDER][col] = ('', Some(text_primary), Some(color));
                } else {
                    rich[rows::CHROMA_SLIDER][col] = ('', Some(color), Some(panel_bg));
                }
            }
        }
    }

    // H bar (hue slider): rainbow at current lightness and chroma.
    let h_cursor = ((oklch.h / 360.0) * (TRACK_LEN - 1) as f32).round() as usize;
    if rich.len() > rows::HUE_SLIDER {
        let h_start = CONTENT_OFFSET + 7;
        for i in 0..TRACK_LEN {
            let col = h_start + i;
            if col < rich[rows::HUE_SLIDER].len() {
                let h = i as f32 / (TRACK_LEN - 1) as f32 * 360.0;
                let color = oklch_to_srgb(oklch.l.max(0.5), oklch.c.max(0.08), h);
                if i == h_cursor {
                    rich[rows::HUE_SLIDER][col] = ('', Some(text_primary), Some(color));
                } else {
                    rich[rows::HUE_SLIDER][col] = ('', Some(color), Some(panel_bg));
                }
            }
        }
    }

    // Gradient strip
    if rich.len() > rows::GRADIENT_STRIP {
        for i in 0..INNER_W {
            let col = CONTENT_OFFSET + i;
            if col < rich[rows::GRADIENT_STRIP].len() {
                let t = i as f32 / (INNER_W - 1).max(1) as f32;
                let t_next = (t + 1.5 / INNER_W as f32).min(1.0);
                let fg_color = interpolate_gradient(&stops, t);
                let bg_color = interpolate_gradient(&stops, t_next);
                rich[rows::GRADIENT_STRIP][col] = ('', Some(fg_color), Some(bg_color));
            }
        }
    }

    rich
}

// ─── Overlay renderer ────────────────────────────────────────────────────────

/// Overlay renderer for the palette editor.
pub struct PaletteEditorOverlay;

impl PaletteEditorOverlay {
    /// Total width of the overlay in characters (including border and padding).
    /// border(1) + padding.left(1) + INNER_W(52) + padding.right(1) + border(1) = 56
    pub const WIDTH: usize = INNER_W + 4;

    /// Total height of the overlay in characters.
    /// top_border(1) + 27 content rows + bottom_border(1) = 29
    pub const HEIGHT: usize = 29;

    /// Build the overlay for the current editor state.
    pub fn build_overlay(
        state: &PaletteEditorState,
        panel_style: &crate::render::theme::PanelStyle,
        accent: RgbColor,
    ) -> RenderedOverlay {
        match state.mode {
            EditorMode::Editing => Self::build_editing_overlay(state, panel_style, accent),
            EditorMode::SaveDialog => Self::build_save_dialog_overlay(state, panel_style),
            EditorMode::LoadDialog => {
                Self::build_load_dialog_overlay(state, &state.saved_palettes_list)
            }
        }
    }

    fn build_editing_overlay(
        state: &PaletteEditorState,
        panel_style: &crate::render::theme::PanelStyle,
        accent: RgbColor,
    ) -> RenderedOverlay {
        let oklch = state.current_oklch();

        let gradient_str = "".repeat(INNER_W);
        let swatches_str = build_swatches_str(state.selected_color_index);
        let labels_str = build_swatch_labels_str();

        let l_active = state.selected_component == EditorComponent::Lightness;
        let c_active = state.selected_component == EditorComponent::Chroma;
        let h_active = state.selected_component == EditorComponent::Hue;

        let l_label = build_slider_label(l_active, 'L', &format!("{:.3}", oklch.l));
        let l_bar = build_slider_bar(oklch.l);
        let c_label = build_slider_label(c_active, 'C', &format!("{:.3}", oklch.c));
        let c_bar = build_slider_bar((oklch.c / MAX_CHROMA).clamp(0.0, 1.0));
        let h_label = build_slider_label(h_active, 'H', &format!("{:.1}°", oklch.h));
        let h_bar = build_slider_bar(oklch.h / 360.0);

        let first_hint_line = "← select →";
        let second_hint_line = "↑ adjust ↓";
        let tab_hint_line = "Tab  L → C → H";
        let hints = [
            ("r", "reset"),
            ("Enter", "apply"),
            ("Ctrl+S", "save palette"),
            ("Esc", "discard"),
        ];
        // Each line is centered independently as a single text block.
        let key_label_lines: Vec<String> = hints
            .iter()
            .map(|(key, label)| format!("{key}  {label}"))
            .collect();

        let mut overlay = PanelBuilder::new(INNER_W, None)
            .with_padding(Padding::COMPACT)
            .with_title("PALETTE EDITOR")
            .with_title_box()
            .add_empty() // line 1
            .add_empty() // line 2
            .add_single(swatches_str, TextAlignment::Center) // line 3
            .add_single(labels_str, TextAlignment::Center) // line 4
            .add_empty() // line 5
            .add_separator() // line 6
            .add_empty() // line 7
            .add_single(l_label, TextAlignment::Center) // line 8
            .add_single(l_bar, TextAlignment::Center) // line 9
            .add_empty() // line 10
            .add_single(c_label, TextAlignment::Center) // line 11
            .add_single(c_bar, TextAlignment::Center) // line 12
            .add_empty() // line 13
            .add_single(h_label, TextAlignment::Center) // line 14
            .add_single(h_bar, TextAlignment::Center) // line 15
            .add_empty() // line 16
            .add_separator() // line 17
            .add_single(first_hint_line.to_string(), TextAlignment::Center) // line 18
            .add_single(second_hint_line.to_string(), TextAlignment::Center) // line 19
            .add_single(tab_hint_line.to_string(), TextAlignment::Center) // line 20
            .add_single(key_label_lines[0].clone(), TextAlignment::Center) // line 21
            .add_single(key_label_lines[1].clone(), TextAlignment::Center) // line 22
            .add_single(key_label_lines[2].clone(), TextAlignment::Center) // line 23
            .add_single(key_label_lines[3].clone(), TextAlignment::Center) // line 24
            .add_empty() // line 25
            .add_separator() // line 26
            .add_single(gradient_str, TextAlignment::Left) // line 27
            .build_overlay();

        overlay.rich_lines = Some(build_editor_rich_lines(
            state,
            &overlay.lines,
            oklch,
            panel_style.text_primary,
            accent,
            panel_style.bg_color,
        ));
        overlay
    }

    fn build_save_dialog_overlay(
        state: &PaletteEditorState,
        panel_style: &crate::render::theme::PanelStyle,
    ) -> RenderedOverlay {
        const LABEL: &str = "Name: ";
        const FIELD_WIDTH: usize = 25;
        let name_str = format!("{LABEL}{:<FIELD_WIDTH$}", state.save_name_input.value());

        let mut overlay = PanelBuilder::new(38, None)
            .with_padding(Padding::COMPACT)
            .with_title("SAVE PALETTE")
            .with_title_box()
            .add_empty()
            .add_single(name_str, TextAlignment::Left)
            .add_empty()
            .add_single(
                format!("  {}", footer_hints(&[("", "save"), ("esc", "cancel")])),
                TextAlignment::Left,
            )
            .build_overlay();

        // tui_input-backed caret (same helper as the config-save dialog).
        crate::render::ratatui_adapter::stamp_caret(
            &mut overlay,
            LABEL,
            FIELD_WIDTH,
            state.save_name_input.cursor(),
            panel_style,
        );
        overlay
    }

    fn build_load_dialog_overlay(
        state: &PaletteEditorState,
        saved_palettes: &[crate::palette_manager::SavedPalette],
    ) -> RenderedOverlay {
        let mut builder = PanelBuilder::new(38, None)
            .with_padding(Padding::COMPACT)
            .with_title("LOAD PALETTE")
            .with_title_box()
            .add_empty();

        if saved_palettes.is_empty() {
            builder =
                builder.add_single("  No saved palettes yet".to_string(), TextAlignment::Left);
        } else {
            // Hand-rolled scroll window keeps the selection visible, fixing the old
            // take(8) truncation that hid palettes past the 8th when one was selected.
            const MAX_VISIBLE: usize = 8;
            let total = saved_palettes.len();
            let start = crate::render::ratatui_adapter::scroll_start(
                total,
                state.saved_palette_index,
                MAX_VISIBLE,
            );
            let end = (start + MAX_VISIBLE).min(total);
            for (i, palette) in saved_palettes.iter().enumerate().take(end).skip(start) {
                let marker = if i == state.saved_palette_index {
                    ""
                } else {
                    " "
                };
                let truncated = if palette.name.len() > 28 {
                    &palette.name[..28]
                } else {
                    &palette.name
                };
                let entry = format!(" {} {:2}. {}", marker, i + 1, truncated);
                builder = builder.add_single(entry, TextAlignment::Left);
            }
        }

        let hint = if saved_palettes.is_empty() {
            footer_hints(&[("esc", "cancel")])
        } else {
            footer_hints(&[("↑↓", "navigate"), ("", "load"), ("esc", "cancel")])
        };
        builder
            .add_empty()
            .add_single(format!("  {hint}"), TextAlignment::Left)
            .build_overlay()
    }

    /// Calculate the centered position for the overlay.
    ///
    /// Adds 1 to y so the title box drawn at y-1 stays on screen.
    pub fn calculate_position(term_width: usize, term_height: usize) -> (usize, usize) {
        let x = (term_width.saturating_sub(Self::WIDTH)) / 2;
        let y = (term_height.saturating_sub(Self::HEIGHT + 1)) / 2 + 1;
        (x, y)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_adjust_hue_updates_stored_hues() {
        let mut state = PaletteEditorState::new(&Palette::Forest);
        state.selected_color_index = 3;

        let initial_stored_hue = state.stored_hues[3];
        state.adjust_hue(45.0);

        // Stored hue should be updated exactly
        assert!(
            (state.stored_hues[3] - (initial_stored_hue + 45.0) % 360.0).abs() < 0.1,
            "Stored hue should be updated when adjusting hue"
        );

        // Current hue should be close (allowing for 8-bit RGB quantization error)
        let current_hue = state.current_oklch().h;
        let hue_diff = (current_hue - state.stored_hues[3]).abs();
        assert!(
            hue_diff < 5.0,
            "Current hue {} should be close to stored hue {} (diff={})",
            current_hue,
            state.stored_hues[3],
            hue_diff
        );
    }

    #[test]
    fn test_color_navigation() {
        let mut state = PaletteEditorState::new(&Palette::Forest);

        // Starting at ALL (index 11), next goes to 0
        state.select_next_color();
        assert_eq!(state.selected_color_index, 0);

        // Prev from 0 wraps to ALL (11)
        state.select_prev_color();
        assert_eq!(state.selected_color_index, PALETTE_COLOR_COUNT);

        // Prev from ALL (11) goes to 10
        state.select_prev_color();
        assert_eq!(state.selected_color_index, 10);
    }

    #[test]
    fn test_color_navigation_wraps_forward_through_all() {
        let mut state = PaletteEditorState::new(&Palette::Forest);
        // Starting at ALL (index 11), navigate forward through all 12 positions
        // (11 colors + 1 ALL slot) to return to ALL.
        for _ in 0..(PALETTE_COLOR_COUNT + 1) {
            state.select_next_color();
        }
        assert_eq!(state.selected_color_index, PALETTE_COLOR_COUNT); // ALL slot

        // One more wraps back to 0.
        state.select_next_color();
        assert_eq!(state.selected_color_index, 0);
    }

    #[test]
    fn test_is_all_selected() {
        let state = PaletteEditorState::new(&Palette::Forest);
        assert!(state.is_all_selected());

        let mut state2 = PaletteEditorState::new(&Palette::Forest);
        state2.selected_color_index = 0;
        assert!(!state2.is_all_selected());
    }

    #[test]
    fn test_all_selected_adjust_applies_to_all_stops() {
        let mut state = PaletteEditorState::new(&Palette::Forest);
        let original_colors = state.colors;

        state.selected_color_index = PALETTE_COLOR_COUNT; // ALL slot
        state.adjust_hue(90.0);

        assert!(state.is_modified);
        // Every stop should have changed.
        for (i, _) in original_colors.iter().enumerate().take(PALETTE_COLOR_COUNT) {
            assert_ne!(
                state.colors[i], original_colors[i],
                "Stop {} should have changed after ALL hue adjust",
                i
            );
        }
    }

    #[test]
    fn test_average_oklch_calculation() {
        let mut state = PaletteEditorState::new(&Palette::Forest);

        // Set all colors to pure red (high chroma in OKLch).
        for color in state.colors.iter_mut() {
            *color = RgbColor { r: 255, g: 0, b: 0 };
        }

        let avg = state.average_oklch();
        assert!(avg.c > 0.2, "Average chroma of pure red should be high");
        assert!(
            avg.l > 0.4,
            "Average lightness of pure red should be moderate"
        );
    }

    #[test]
    fn test_oklch_adjustment() {
        let mut state = PaletteEditorState::new(&Palette::Forest);

        // Use a mid-range color (moderate chroma) where 8-bit quantization is less severe.
        state.selected_color_index = 0;
        state.colors[0] = RgbColor {
            r: 100,
            g: 150,
            b: 80,
        };
        let original_hue = state.current_oklch().h;

        // Large shift to overcome 8-bit RGB quantization noise.
        state.adjust_hue(45.0);
        assert!(state.is_modified);

        let new_hue = state.current_oklch().h;
        let actual_shift = ((new_hue - original_hue + 540.0) % 360.0) - 180.0;
        assert!(
            (actual_shift - 45.0).abs() < 10.0,
            "hue should shift by ~45°: original={}, new={}, actual_shift={}",
            original_hue,
            new_hue,
            actual_shift
        );
    }

    #[test]
    fn test_chroma_clamping() {
        let mut state = PaletteEditorState::new(&Palette::Forest);

        // Select a single stop to avoid average-based measurement.
        state.selected_color_index = 5;
        state.adjust_chroma(-2.0);
        assert!(
            state.current_oklch().c < 0.02,
            "Chroma should clamp near 0, got {}",
            state.current_oklch().c
        );

        state.adjust_chroma(2.0);
        // After 8-bit RGB roundtrip, chroma may be slightly less than MAX_CHROMA
        // due to gamut clamping, but should be in the high range.
        assert!(
            state.current_oklch().c > 0.15,
            "Chroma should be high after large positive adjustment, got {}",
            state.current_oklch().c
        );
    }

    #[test]
    fn test_reset() {
        let mut state = PaletteEditorState::new(&Palette::Forest);
        let original = state.colors[0];

        state.adjust_hue(45.0);
        assert!(state.is_modified);

        state.reset_to_original();
        assert!(!state.is_modified);
        assert_eq!(state.colors[0], original);
    }

    #[test]
    fn test_component_cycle() {
        assert_eq!(EditorComponent::Lightness.next(), EditorComponent::Chroma);
        assert_eq!(EditorComponent::Chroma.next(), EditorComponent::Hue);
        assert_eq!(EditorComponent::Hue.next(), EditorComponent::Lightness);

        assert_eq!(EditorComponent::Lightness.prev(), EditorComponent::Hue);
        assert_eq!(EditorComponent::Hue.prev(), EditorComponent::Chroma);
        assert_eq!(EditorComponent::Chroma.prev(), EditorComponent::Lightness);
    }

    #[test]
    fn test_build_overlay_produces_lines() {
        let state = PaletteEditorState::new(&Palette::Forest);
        let panel_style = crate::render::theme::GRUVBOX_DARK;
        let accent =
            crate::render::palette::palette_accent_color(&Palette::Forest, false, false, 0.0, None);
        let overlay = PaletteEditorOverlay::build_overlay(&state, &panel_style, accent);
        assert!(!overlay.lines.is_empty());
        for (i, line) in overlay.lines.iter().enumerate() {
            assert_eq!(
                line.chars().count(),
                PaletteEditorOverlay::WIDTH,
                "Line {} has wrong width: {} ('{}')",
                i,
                line.chars().count(),
                line
            );
        }
    }

    #[test]
    fn test_build_overlay_height() {
        let state = PaletteEditorState::new(&Palette::Forest);
        let panel_style = crate::render::theme::GRUVBOX_DARK;
        let accent =
            crate::render::palette::palette_accent_color(&Palette::Forest, false, false, 0.0, None);
        let overlay = PaletteEditorOverlay::build_overlay(&state, &panel_style, accent);
        assert_eq!(overlay.lines.len(), PaletteEditorOverlay::HEIGHT);
    }

    #[test]
    fn test_swatches_str_width() {
        let s = build_swatches_str(0);
        assert_eq!(s.chars().count(), 48); // 12 × 4 for centering
    }

    #[test]
    fn test_swatches_str_all_selected_width() {
        let s = build_swatches_str(PALETTE_COLOR_COUNT); // ALL slot
        assert_eq!(s.chars().count(), 48);
    }

    #[test]
    fn test_swatch_labels_str_width() {
        let s = build_swatch_labels_str();
        assert_eq!(s.chars().count(), 48);
    }

    fn build_hex_str(rgb: RgbColor) -> String {
        format!("#{:02x}{:02x}{:02x}", rgb.r, rgb.g, rgb.b)
    }

    #[test]
    fn test_hex_str_width() {
        let rgb = RgbColor {
            r: 255,
            g: 128,
            b: 0,
        };
        let s = build_hex_str(rgb);
        assert_eq!(s.chars().count(), 7); // #rrggbb
    }

    #[test]
    fn test_slider_label_width() {
        let s = build_slider_label(true, 'H', "180.0°");
        assert!(s.chars().count() > 0);
    }

    #[test]
    fn test_slider_bar_width() {
        let s = build_slider_bar(0.5);
        assert_eq!(s.chars().count(), TRACK_LEN);
    }

    #[test]
    fn test_slider_bar_cursor_position() {
        let s = build_slider_bar(0.0);
        assert!(s.starts_with(''));
        let s = build_slider_bar(1.0);
        assert!(s.ends_with(''));
    }

    #[test]
    fn test_build_overlay_all_selected() {
        let mut state = PaletteEditorState::new(&Palette::Forest);
        state.selected_color_index = PALETTE_COLOR_COUNT; // ALL slot
        let panel_style = crate::render::theme::GRUVBOX_DARK;
        let accent =
            crate::render::palette::palette_accent_color(&Palette::Forest, false, false, 0.0, None);
        let overlay = PaletteEditorOverlay::build_overlay(&state, &panel_style, accent);
        assert_eq!(overlay.lines.len(), PaletteEditorOverlay::HEIGHT);
        for (i, line) in overlay.lines.iter().enumerate() {
            assert_eq!(
                line.chars().count(),
                PaletteEditorOverlay::WIDTH,
                "Line {} has wrong width in ALL mode",
                i
            );
        }
    }

    #[test]
    fn test_chroma_zero_preserves_hue_single_color() {
        // Regression test: when chroma goes to 0 and back, hue should be preserved
        let mut state = PaletteEditorState::new(&Palette::Forest);

        // Select a single color with a non-zero hue (not grayscale)
        state.selected_color_index = 5;
        let initial_hue = state.current_oklch().h;

        // Verify we have a valid initial hue (not NaN and not near 0/red)
        assert!(
            initial_hue > 10.0,
            "Initial hue should be non-red for this test, got {}",
            initial_hue
        );

        // Reduce chroma to 0 (monochrome)
        state.adjust_chroma(-2.0);
        assert!(
            state.current_oklch().c < 0.02,
            "Chroma should be near 0, got {}",
            state.current_oklch().c
        );

        // Hue should still be preserved in stored_hues
        assert!(
            (state.stored_hues[5] - initial_hue).abs() < 1.0,
            "Stored hue should be preserved when chroma=0, stored={}, initial={}",
            state.stored_hues[5],
            initial_hue
        );

        // Increase chroma back
        state.adjust_chroma(0.1);

        // Hue should be restored, not become 0 (red)
        let restored_hue = state.current_oklch().h;
        assert!(
            restored_hue > 10.0,
            "Restored hue should not be red (0°), got {}. Hue was not preserved during chroma=0 transition!",
            restored_hue
        );
    }

    #[test]
    fn test_chroma_zero_preserves_hue_all_selected() {
        // Test the ALL selection mode with chroma=0 transition
        let mut state = PaletteEditorState::new(&Palette::Forest);

        // Store initial average hue
        let _initial_avg_hue = state.current_oklch().h;

        // Reduce chroma to 0 for all colors
        state.adjust_chroma(-2.0);

        // Verify chroma is near 0
        assert!(
            state.current_oklch().c < 0.02,
            "Average chroma should be near 0"
        );

        // Increase chroma back
        state.adjust_chroma(0.15);

        // The average hue should not have become 0 (red)
        let restored_hue = state.current_oklch().h;
        assert!(
            restored_hue > 20.0 || restored_hue < 340.0,
            "Restored average hue should not be near red (0°), got {}. Stored hues were not preserved!",
            restored_hue
        );
    }

    #[test]
    fn test_stored_hues_initialized_correctly() {
        let state = PaletteEditorState::new(&Palette::Forest);

        // Verify stored hues match the actual hues of the palette colors
        for (i, &color) in state.colors.iter().enumerate() {
            let oklch = srgb_to_oklch(color);
            let expected_hue = if oklch.h.is_nan() { 0.0 } else { oklch.h };
            assert!(
                (state.stored_hues[i] - expected_hue).abs() < 0.1,
                "Stored hue {} should match actual hue {} for color {}",
                state.stored_hues[i],
                expected_hue,
                i
            );
        }
    }

    #[test]
    fn test_reset_restores_stored_hues() {
        let mut state = PaletteEditorState::new(&Palette::Forest);
        let initial_stored_hues = state.stored_hues;

        // Modify hues
        state.adjust_hue(90.0);

        // Reset
        state.reset_to_original();

        // Stored hues should be restored
        for (i, &initial_hue) in initial_stored_hues
            .iter()
            .enumerate()
            .take(PALETTE_COLOR_COUNT)
        {
            assert!(
                (state.stored_hues[i] - initial_hue).abs() < 0.1,
                "Stored hue {} should be reset to original",
                i
            );
        }
    }

    #[test]
    fn save_dialog_renders_caret() {
        let mut state = PaletteEditorState::new(&Palette::Forest);
        state.mode = EditorMode::SaveDialog;
        state.save_name_input = tui_input::Input::new("abc".to_string());
        let style = crate::render::theme::PanelStyle::default();
        let overlay =
            PaletteEditorOverlay::build_overlay(&state, &style, RgbColor::new(255, 128, 0));
        let text = overlay.lines.join("\n");
        assert!(text.contains("Name: abc"), "field text missing:\n{text}");
        let rich = overlay
            .rich_lines
            .expect("save dialog needs caret rich_lines");
        let caret = rich
            .iter()
            .flatten()
            .filter(|c| c.2 == Some(style.accent_active))
            .count();
        assert_eq!(caret, 1, "expected exactly one caret cell");
    }

    #[test]
    fn load_dialog_keeps_selection_visible() {
        // 15 palettes, select the last: the old take(8) hid it; scroll_start windows to it.
        let mut state = PaletteEditorState::new(&Palette::Forest);
        state.mode = EditorMode::LoadDialog;
        state.saved_palettes_list = (0..15)
            .map(|i| palette_manager::SavedPalette::new(format!("pal{i:02}"), state.colors))
            .collect();
        state.saved_palette_index = 14;
        let style = crate::render::theme::PanelStyle::default();
        let overlay =
            PaletteEditorOverlay::build_overlay(&state, &style, RgbColor::new(255, 128, 0));
        let text = overlay.lines.join("\n");
        assert!(
            text.contains("pal14"),
            "selected last palette must stay visible (old take(8) bug):\n{text}"
        );
    }
}