tui-spinner 0.2.3

Customizable animated spinner widgets for Ratatui — braille arcs, bouncing bars, rotating glyphs, and symbol styles
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
//! Rectangle braille-arc bouncing spinner.
//!
//! A braille or symbol-based loading bar: every character cell is filled with a
//! glyph; a bright arc window slides left-to-right (and bounces) over
//! a dimmer background track.
//!
//! Set [`BarSpinner::width`] to `0` (the default) to fill the
//! available terminal width automatically.
//!
//! ## Visual
//!
//! ```text
//! ⣀⣀⣀⣀⠉⠛⠿⣿⣿⣿⣿⣿⣿⠿⠛⠉⣀⣀⣀⣀⣀⣀⣀⣀
//! ```
//!
//! The outer-edge columns of the arc (`⠉ ⠛ ⠿`) taper from a short
//! top-row glyph up to full density, giving a smooth gradient.
//! The dim background track uses `⣀` (bottom-two-dot rail).
//!
//! ## How it works
//!
//! 1. A `width × height` character grid is rendered; arc columns use the
//!    full-dot glyph `⣿` in `arc_color`, dim columns use `⣀` in `dim_color`.
//! 2. The three outermost columns on each arc edge use the fade ramp
//!    `⠉ ⠛ ⠿` so the arc blends into the track.
//! 3. The arc window advances one column per step and reverses at each end.

use ratatui::buffer::Buffer;
use ratatui::layout::{Alignment, Rect};
use ratatui::style::{Color, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Paragraph, Widget};

use crate::Spin;

// ── Braille glyph constants ───────────────────────────────────────────────────

/// Fade ramp for arc edges — outermost (index 0) to innermost (index 3).
///
/// ```text
/// ⠉  0x09   dots 1,4       — top row only
/// ⠛  0x1B   dots 1,2,4,5   — top two rows
/// ⠿  0x3F   dots 1–6       — top three rows
/// ⣿  0xFF   dots 1–8       — full
/// ```
const FADE: [u8; 4] = [0x09, 0x1B, 0x3F, 0xFF];

/// Braille byte for the dim background track.
///
/// `⣀` (0xC0) — bottom two dots only — gives a subtle rail behind the arc.
const DIM_BYTE: u8 = 0xC0;

// ── Track style ───────────────────────────────────────────────────────────────

/// Controls the appearance of the dim background track behind the bouncing arc.
///
/// | Variant | Byte | Glyph | Effect |
/// |---------|------|-------|--------|
/// | `Rail`  | `0xC0` | `⣀` | Bottom-two-dot baseline — subtle, default |
/// | `Full`  | `0xFF` | `⣿` | Full-density track in `dim_color` |
/// | `Empty` | `0x00` | `⠀` | Invisible — arc floats on empty space |
/// | `Custom(u8)` | any | any braille | User-defined braille byte |
///
/// # Examples
///
/// ```
/// use tui_spinner::{BarSpinner, BarTrack};
///
/// let rail  = BarSpinner::new(0).track(BarTrack::Rail);    // ⣀ default
/// let solid = BarSpinner::new(0).track(BarTrack::Full);    // ⣿ solid track
/// let float = BarSpinner::new(0).track(BarTrack::Empty);   // ⠀ no track
/// let dot   = BarSpinner::new(0).track(BarTrack::Custom(0x09)); // ⠉ top-row
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BarTrack {
    /// `⣀` (0xC0) — bottom-two-dot rail, subtle baseline (default).
    #[default]
    Rail,
    /// `⣿` (0xFF) — full-density track in `dim_color`.
    Full,
    /// `⠀` (0x00) — invisible background; the arc floats on empty space.
    Empty,
    /// Any custom braille byte.
    Custom(u8),
}

impl BarTrack {
    fn byte(self) -> u8 {
        match self {
            Self::Rail => DIM_BYTE,
            Self::Full => 0xFF,
            Self::Empty => 0x00,
            Self::Custom(b) => b,
        }
    }
}

// ── Symbol style ─────────────────────────────────────────────────────────────

/// Selects the glyph set used for the arc and background track.
///
/// [`Braille`](BarStyle::Braille) (the default) uses braille bytes and
/// supports the full `fade_width` density ramp.  All other variants use a
/// single Unicode character for the arc and one for the track, with no
/// intermediate fade.
///
/// | Variant   | Arc | Track | Notes |
/// |-----------|-----|-------|-------|
/// | `Braille` | `⣿` | `⣀`  | Braille density fade (default) |
/// | `Block`   | `█` | `░`   | Solid / light block |
/// | `Shade`   | `▓` | `░`   | Dark shade / light block |
/// | `Dot`     | `●` | `·`   | Filled / middle dot |
/// | `Diamond` | `◆` | `◇`   | Filled / open diamond |
/// | `Square`  | `■` | `□`   | Filled / open square |
/// | `Star`    | `★` | `☆` | Filled / outline star             |
/// | `Heart`   | `♥` | `♡` | Filled / outline heart            |
/// | `Arrow`   | `▶` | `▷` | Solid / outline right triangle    |
/// | `Circle`  | `◉` | `○` | Fisheye / open circle             |
/// | `Spark`   | `✦` | `✧` | Black / white four-pointed star   |
/// | `Cross`    | `✚` | `✛` | Heavy / open-centre cross         |
/// | `Progress` | `▰` | `▱` | Bold progress-bar segments |
/// | `Thick`    | `━` | `─` | Heavy / thin horizontal line |
/// | `Wave`     | `≈` | `˜` | Wave / tilde |
/// | `Pip`      | `▪` | `·` | Small square / middle dot |
///
/// # Examples
///
/// ```
/// use tui_spinner::{BarSpinner, BarStyle};
///
/// let braille = BarSpinner::new(0);                                    // default
/// let block   = BarSpinner::new(0).bar_style(BarStyle::Block);
/// let dot     = BarSpinner::new(0).bar_style(BarStyle::Dot);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BarStyle {
    /// Dense braille glyphs with a smooth density-gradient fade (default).
    ///
    /// Respects `arc_char`, `track`, and `fade_width` settings.
    #[default]
    Braille,
    /// Solid block — `█` arc, `░` track.
    Block,
    /// Shade blocks — `▓` arc, `░` track.
    Shade,
    /// Filled / middle dot — `●` arc, `·` track.
    Dot,
    /// Filled / open diamond — `◆` arc, `◇` track.
    Diamond,
    /// Filled / open square — `■` arc, `□` track.
    Square,
    /// Filled / outline star — `★` arc, `☆` track.
    Star,
    /// Filled / outline heart — `♥` arc, `♡` track.
    Heart,
    /// Solid / outline right-pointing triangle — `▶` arc, `▷` track.
    Arrow,
    /// Fisheye / open circle — `◉` arc, `○` track.
    Circle,
    /// Black / white four-pointed star — `✦` arc, `✧` track.
    Spark,
    /// Heavy Greek cross / open-centre cross — `✚` arc, `✛` track.
    Cross,
    /// Bold progress-bar segments — `▰` arc, `▱` track.
    Progress,
    /// Heavy / thin horizontal line — `━` arc, `─` track.
    Thick,
    /// Wave / tilde — `≈` arc, `˜` track.
    Wave,
    /// Small square / middle dot — `▪` arc, `·` track.
    Pip,
}

impl BarStyle {
    /// Returns `Some((arc_char, track_char))` for symbol styles, or `None`
    /// for [`BarStyle::Braille`] (which uses the existing braille rendering).
    pub(crate) fn chars(self) -> Option<(char, char)> {
        match self {
            Self::Braille => None,
            Self::Block => Some(('', '')),
            Self::Shade => Some(('', '')),
            Self::Dot => Some(('', '·')),
            Self::Diamond => Some(('', '')),
            Self::Square => Some(('', '')),
            Self::Star => Some(('', '')),
            Self::Heart => Some(('', '')),
            Self::Arrow => Some(('', '')),
            Self::Circle => Some(('', '')),
            Self::Spark => Some(('', '')),
            Self::Cross => Some(('', '')),
            Self::Progress => Some(('', '')),
            Self::Thick => Some(('', '')),
            Self::Wave => Some(('', '˜')),
            Self::Pip => Some(('', '·')),
        }
    }
}

// ── Motion mode ───────────────────────────────────────────────────────────────

/// Controls how the arc behaves when it reaches the edge of the bar.
///
/// | Variant  | Behaviour |
/// |----------|-----------|
/// | `Bounce` | Reverses at each edge — classic ping-pong (default) |
/// | `Loop`   | Wraps around: when the arc exits one edge it re-enters from the other |
///
/// Combined with [`Spin`], `Loop` produces a continuous sweep:
/// - `Spin::Clockwise` + `Loop` → sweeps left → right endlessly
/// - `Spin::CounterClockwise` + `Loop` → sweeps right → left endlessly
///
/// # Examples
///
/// ```
/// use tui_spinner::{BarSpinner, BarMotion, Spin};
///
/// // Default ping-pong
/// let bounce = BarSpinner::new(0).motion(BarMotion::Bounce);
///
/// // Continuous left-to-right sweep
/// let sweep = BarSpinner::new(0).spin(Spin::Clockwise).motion(BarMotion::Loop);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BarMotion {
    /// Reverse at each edge — ping-pong (default).
    #[default]
    Bounce,
    /// Wrap around: exit one edge and re-enter from the other.
    Loop,
}

// ── Engine ────────────────────────────────────────────────────────────────────

/// Map an edge distance to the appropriate [`FADE`] byte.
///
/// - `fade_width = 0` → no ramp; all arc cells use `arc_byte`.
/// - `fade_width = 1` → only the outermost column fades.
/// - `fade_width = 3` → default three-column ramp (`⠉ ⠛ ⠿ → arc_byte`).
#[inline]
fn fade_byte(from_edge: usize, fade_width: usize, arc_byte: u8) -> u8 {
    if fade_width == 0 || from_edge >= fade_width {
        arc_byte
    } else {
        FADE[(from_edge * 3).div_ceil(fade_width).min(2)]
    }
}

/// Internal bounce engine operating in **character-column** space.
///
/// All positions are whole character columns, so there are never any
/// sub-character boundary artefacts.
struct RectEngine {
    char_w: usize,
    char_h: usize,
    /// Width of the bright window in character columns.
    arc_cols: usize,
    /// Leftmost character column of the bright window.
    anchor: usize,
    going_forward: bool,
    motion: BarMotion,
}

impl RectEngine {
    fn build(
        char_w: usize,
        char_h: usize,
        arc_width: usize,
        spin: Spin,
        motion: BarMotion,
    ) -> Self {
        let char_w = char_w.max(3);
        let char_h = char_h.max(1);

        // Arc width: explicit value, or auto (~⅓ of bar, min 4 so fade shows).
        let arc_cols = if arc_width > 0 {
            arc_width.min(char_w.saturating_sub(1))
        } else {
            char_w.div_ceil(3).max(4)
        };

        let going_forward = matches!(spin, Spin::Clockwise);
        let anchor = if going_forward {
            0
        } else {
            char_w.saturating_sub(arc_cols)
        };

        Self {
            char_w,
            char_h,
            arc_cols,
            anchor,
            going_forward,
            motion,
        }
    }

    /// Advance one step, reversing or wrapping at each edge.
    fn walk(&mut self) {
        match self.motion {
            BarMotion::Bounce => {
                let max_anchor = self.char_w.saturating_sub(self.arc_cols);
                if self.going_forward {
                    if self.anchor < max_anchor {
                        self.anchor += 1;
                    } else {
                        self.going_forward = false;
                    }
                } else if self.anchor > 0 {
                    self.anchor -= 1;
                } else {
                    self.going_forward = true;
                }
            }
            BarMotion::Loop => {
                // Anchor travels the full 0..char_w range modularly.
                // render_lines uses (ci - anchor) % char_w to detect the arc,
                // so the glyph phases in at the leading edge while phasing out
                // at the trailing edge in the same frame.
                if self.going_forward {
                    self.anchor = (self.anchor + 1) % self.char_w;
                } else {
                    self.anchor = (self.anchor + self.char_w - 1) % self.char_w;
                }
            }
        }
    }

    /// Render the current frame as styled [`Line`]s.
    fn render_lines(
        &self,
        arc_color: Color,
        dim_color: Color,
        fade_width: usize,
        track_byte: u8,
        arc_byte: u8,
        style_chars: Option<(char, char)>,
    ) -> Vec<Line<'static>> {
        let char_w = self.char_w;
        let arc_cols = self.arc_cols;

        (0..self.char_h)
            .map(|_| {
                let spans: Vec<Span<'static>> = (0..char_w)
                    .map(|ci| {
                        // Determine whether this column is inside the arc and,
                        // if so, its distance from the nearer arc edge.
                        let (in_arc, from_edge) = match self.motion {
                            BarMotion::Bounce => {
                                let arc_end = self.anchor + arc_cols;
                                if ci >= self.anchor && ci < arc_end {
                                    let fe = (ci - self.anchor).min(arc_end - 1 - ci);
                                    (true, fe)
                                } else {
                                    (false, 0)
                                }
                            }
                            BarMotion::Loop => {
                                // Modular offset: how far past `anchor` is `ci`?
                                // This correctly handles the wrap-around case where
                                // part of the arc is near the right edge and part
                                // has already reappeared at the left edge.
                                let offset = (ci + char_w - self.anchor) % char_w;
                                if offset < arc_cols {
                                    let fe = offset.min(arc_cols - 1 - offset);
                                    (true, fe)
                                } else {
                                    (false, 0)
                                }
                            }
                        };

                        let (ch, color) = if let Some((arc_ch, track_ch)) = style_chars {
                            if in_arc {
                                (arc_ch, arc_color)
                            } else {
                                (track_ch, dim_color)
                            }
                        } else if in_arc {
                            let byte = fade_byte(from_edge, fade_width, arc_byte);
                            let ch = char::from_u32(0x2800 + u32::from(byte)).unwrap_or('\u{2800}');
                            (ch, arc_color)
                        } else {
                            let ch = char::from_u32(0x2800 + u32::from(track_byte))
                                .unwrap_or('\u{2800}');
                            (ch, dim_color)
                        };

                        Span::styled(ch.to_string(), Style::default().fg(color))
                    })
                    .collect();
                Line::from(spans)
            })
            .collect()
    }
}

// ── Public widget ─────────────────────────────────────────────────────────────

/// A Zed / Claude-style braille loading bar that **bounces** left and right.
///
/// Every character cell in the bar is a braille glyph.  A bright arc window
/// slides across and reverses at each end; the arc edges fade through a
/// density ramp (`⠉ ⠛ ⠿ ⣿`) for a soft comet-glow look.  The dim
/// background uses `⣀` (a two-dot rail) so the full bar extent is visible
/// without competing with the arc.
///
/// # Width
///
/// Leave [`width`](BarSpinner::width) at its default **`0`** to fill
/// the available area automatically (most common usage).  Set it to a fixed
/// positive value if you need a predetermined size.
///
/// # Examples
///
/// ```no_run
/// use ratatui::style::Color;
/// use ratatui::Frame;
/// use ratatui::layout::Rect;
/// use tui_spinner::{BarSpinner, BarTrack, Spin};
///
/// fn draw(frame: &mut Frame, area: Rect, tick: u64) {
///     // Fills the full width of `area` — typical Zed/Claude style.
///     frame.render_widget(
///         BarSpinner::new(tick)
///             .arc_color(Color::Cyan)
///             .dim_color(Color::DarkGray),
///         area,
///     );
/// }
/// ```
///
/// # Field Defaults
///
/// | Field           | Default                     |
/// |-----------------|-----------------------------||
/// | `track`         | [`BarTrack::Rail`]          |
/// | `fade_width`    | `3`                         |
/// | `arc_byte`      | `0xFF` (`⣿`)               |
/// | `bar_style`     | [`BarStyle::Braille`]       |
/// | `motion`        | [`BarMotion::Bounce`]       |
#[derive(Debug, Clone)]
pub struct BarSpinner<'a> {
    tick: u64,
    /// `0` = fill available area; positive = fixed column count.
    width: usize,
    /// Height in character rows (minimum 1).
    height: usize,
    /// Explicit arc width in character columns (`0` = auto ~⅓ of bar).
    arc_width: usize,
    /// Starting direction before the first bounce.
    spin: Spin,
    /// Ticks held per animation step (higher = slower).
    ticks_per_step: u64,
    /// Colour of the bright arc glyph.
    arc_color: Color,
    /// Colour of the dim background track glyph.
    dim_color: Color,
    /// Background track style (default [`BarTrack::Rail`]).
    track: BarTrack,
    /// Fade ramp width in character columns (default 3; 0 = sharp cutoff).
    fade_width: usize,
    /// Braille byte used for the fully-lit arc centre cells (default `0xFF` = `⣿`).
    arc_byte: u8,
    /// Symbol style for arc and track glyphs (default [`BarStyle::Braille`]).
    bar_style: BarStyle,
    /// Arc motion mode (default [`BarMotion::Bounce`]).
    motion: BarMotion,
    block: Option<Block<'a>>,
    style: Style,
    alignment: Alignment,
}

impl<'a> BarSpinner<'a> {
    // ── Presets ───────────────────────────────────────────────────────────────

    /// **Zed-style** preset — 1 row, cyan arc, subtle Rail track, clockwise.
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    /// let s = BarSpinner::zed(42);
    /// ```
    #[must_use]
    pub fn zed(tick: u64) -> Self {
        Self::new(tick)
            .height(1)
            .arc_color(Color::Cyan)
            .dim_color(Color::DarkGray)
    }

    /// **Claude-style** preset — 2 rows, warm-orange arc, Rail track, clockwise.
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    /// let s = BarSpinner::claude(42);
    /// ```
    #[must_use]
    pub fn claude(tick: u64) -> Self {
        Self::new(tick)
            .height(2)
            .arc_color(Color::Rgb(255, 165, 0))
            .dim_color(Color::DarkGray)
    }

    /// **Minimal** preset — 1 row, white arc, Empty track (arc floats on space).
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    /// let s = BarSpinner::minimal(42);
    /// ```
    #[must_use]
    pub fn minimal(tick: u64) -> Self {
        Self::new(tick)
            .height(1)
            .arc_color(Color::White)
            .dim_color(Color::Black)
            .track(BarTrack::Empty)
    }

    /// **Solid** preset — 1 row, cyan arc, Full track, sharp zero-fade edges.
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    /// let s = BarSpinner::solid(42);
    /// ```
    #[must_use]
    pub fn solid(tick: u64) -> Self {
        Self::new(tick)
            .height(1)
            .arc_color(Color::Cyan)
            .dim_color(Color::DarkGray)
            .track(BarTrack::Full)
            .fade_width(0)
    }

    /// Creates a new [`BarSpinner`] with defaults:
    /// auto-width, 1-row height, clockwise start, cyan arc, dark-gray track,
    /// 1 tick per step, auto arc width.
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    ///
    /// let spinner = BarSpinner::new(42);
    /// ```
    #[must_use]
    pub fn new(tick: u64) -> Self {
        Self {
            tick,
            width: 0,
            height: 1,
            arc_width: 0,
            spin: Spin::Clockwise,
            ticks_per_step: 1,
            arc_color: Color::Cyan,
            dim_color: Color::DarkGray,
            track: BarTrack::Rail,
            fade_width: 3,
            arc_byte: 0xFF,
            bar_style: BarStyle::Braille,
            motion: BarMotion::Bounce,
            block: None,
            style: Style::default(),
            alignment: Alignment::Left,
        }
    }

    /// Sets the fixed width in character columns.
    ///
    /// Pass **`0`** (the default) to fill the available area width
    /// automatically.
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    ///
    /// let fixed = BarSpinner::new(0).width(24);
    /// let auto  = BarSpinner::new(0).width(0); // fills area
    /// ```
    #[must_use]
    pub fn width(mut self, w: usize) -> Self {
        self.width = w;
        self
    }

    /// Sets the height in character rows (minimum 1, default 1).
    ///
    /// Use `1` for a thin Zed-style bar or `2`–`3` for a thicker
    /// Claude-style block.
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    ///
    /// let thick = BarSpinner::new(0).height(2);
    /// ```
    #[must_use]
    pub fn height(mut self, h: usize) -> Self {
        self.height = h.max(1);
        self
    }

    /// Sets the arc width in character columns (`0` = auto ~⅓ of bar).
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    ///
    /// let narrow = BarSpinner::new(0).arc_width(6);
    /// let wide   = BarSpinner::new(0).arc_width(20);
    /// ```
    #[must_use]
    pub fn arc_width(mut self, w: usize) -> Self {
        self.arc_width = w;
        self
    }

    /// Sets the starting direction before the first bounce
    /// (default: [`Spin::Clockwise`] = starts moving right).
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::{BarSpinner, Spin};
    ///
    /// let rtl = BarSpinner::new(0).spin(Spin::CounterClockwise);
    /// ```
    #[must_use]
    pub const fn spin(mut self, spin: Spin) -> Self {
        self.spin = spin;
        self
    }

    /// Sets how many ticks each arc position is held (default 1; higher = slower).
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    ///
    /// let slow = BarSpinner::new(0).ticks_per_step(3);
    /// ```
    #[must_use]
    pub fn ticks_per_step(mut self, n: u64) -> Self {
        self.ticks_per_step = n.max(1);
        self
    }

    /// Sets the colour of the bright arc glyph (default: [`Color::Cyan`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use ratatui::style::Color;
    /// use tui_spinner::BarSpinner;
    ///
    /// let spinner = BarSpinner::new(0).arc_color(Color::LightBlue);
    /// ```
    #[must_use]
    pub const fn arc_color(mut self, color: Color) -> Self {
        self.arc_color = color;
        self
    }

    /// Sets the colour of the dim background track (default: [`Color::DarkGray`]).
    ///
    /// Set to the terminal background colour (e.g. [`Color::Black`]) to hide
    /// the track so only the glowing arc is visible.
    ///
    /// # Examples
    ///
    /// ```
    /// use ratatui::style::Color;
    /// use tui_spinner::BarSpinner;
    ///
    /// // Visible track
    /// let with_track    = BarSpinner::new(0).dim_color(Color::DarkGray);
    /// // Arc floats on empty space
    /// let no_track      = BarSpinner::new(0).dim_color(Color::Black);
    /// ```
    #[must_use]
    pub const fn dim_color(mut self, color: Color) -> Self {
        self.dim_color = color;
        self
    }

    /// Sets both `arc_color` and `dim_color` in one call.
    ///
    /// Equivalent to `.arc_color(arc).dim_color(dim)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ratatui::style::Color;
    /// use tui_spinner::BarSpinner;
    ///
    /// let s = BarSpinner::new(0).with_colors(Color::Cyan, Color::DarkGray);
    /// ```
    #[must_use]
    pub fn with_colors(mut self, arc_color: Color, dim_color: Color) -> Self {
        self.arc_color = arc_color;
        self.dim_color = dim_color;
        self
    }

    /// Sets the background track style (default [`BarTrack::Rail`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::{BarSpinner, BarTrack};
    ///
    /// let solid = BarSpinner::new(0).track(BarTrack::Full);
    /// let float = BarSpinner::new(0).track(BarTrack::Empty);
    /// ```
    #[must_use]
    pub fn track(mut self, track: BarTrack) -> Self {
        self.track = track;
        self
    }

    /// Sets the arc fade-ramp width in character columns (default `3`).
    ///
    /// `0` = sharp cutoff — the arc edge is a hard boundary.
    /// `1`–`3` = progressively softer gradient (default `3` gives `⠉ ⠛ ⠿ ⣿`).
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    ///
    /// let sharp = BarSpinner::new(0).fade_width(0);
    /// let soft  = BarSpinner::new(0).fade_width(3); // default
    /// ```
    #[must_use]
    pub fn fade_width(mut self, w: usize) -> Self {
        self.fade_width = w;
        self
    }

    /// Sets the braille byte for the fully-lit arc centre cells (default `0xFF` = `⣿`).
    ///
    /// Use any braille byte to change the arc density.  The fade ramp always
    /// starts from `⠉` and tapers *up to* this value.
    ///
    /// | Example byte | Glyph | Dots |
    /// |---|---|---|
    /// | `0xFF` | `⣿` | 8 — full (default) |
    /// | `0x7F` | `⡿` | 7 |
    /// | `0x3F` | `⠿` | 6 |
    /// | `0x1B` | `⠛` | 4 |
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    ///
    /// let light = BarSpinner::new(0).arc_char(0x3F); // ⠿ lighter arc
    /// ```
    #[must_use]
    pub fn arc_char(mut self, byte: u8) -> Self {
        self.arc_byte = byte;
        self
    }

    /// Sets the glyph style for the arc and background track
    /// (default [`BarStyle::Braille`]).
    ///
    /// Symbol styles (`Block`, `Shade`, `Dot`, `Diamond`, `Square`) use a
    /// single Unicode character for the arc and one for the track.  They
    /// ignore `arc_char`, `track`, and `fade_width`.
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::{BarSpinner, BarStyle};
    ///
    /// let block = BarSpinner::new(0).bar_style(BarStyle::Block);
    /// let dot   = BarSpinner::new(0).bar_style(BarStyle::Dot);
    /// ```
    #[must_use]
    pub fn bar_style(mut self, style: BarStyle) -> Self {
        self.bar_style = style;
        self
    }

    /// Sets the arc motion mode (default [`BarMotion::Bounce`]).
    ///
    /// - [`BarMotion::Bounce`] — reverses at each edge (ping-pong).
    /// - [`BarMotion::Loop`] — wraps around; use with [`Spin`] to set the sweep direction.
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::{BarSpinner, BarMotion, Spin};
    ///
    /// // Continuous left-to-right sweep
    /// let sweep = BarSpinner::new(0)
    ///     .spin(Spin::Clockwise)
    ///     .motion(BarMotion::Loop);
    /// ```
    #[must_use]
    pub fn motion(mut self, motion: BarMotion) -> Self {
        self.motion = motion;
        self
    }

    /// Wraps the spinner in a [`Block`].
    ///
    /// # Examples
    ///
    /// ```
    /// use ratatui::widgets::Block;
    /// use tui_spinner::BarSpinner;
    ///
    /// let spinner = BarSpinner::new(0)
    ///     .block(Block::bordered().title("Loading…"));
    /// ```
    #[must_use]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Sets the base style applied to the widget area.
    #[must_use]
    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
        self.style = style.into();
        self
    }

    /// Sets the horizontal alignment of the rendered output (default: left).
    #[must_use]
    pub const fn alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Returns the explicit rendered size `(cols, rows)`, or `None` when the
    /// width is set to auto (`0`).
    ///
    /// # Examples
    ///
    /// ```
    /// use tui_spinner::BarSpinner;
    ///
    /// assert_eq!(
    ///     BarSpinner::new(0).width(20).height(2).char_size(),
    ///     Some((20, 2))
    /// );
    /// assert_eq!(BarSpinner::new(0).char_size(), None);
    /// ```
    #[must_use]
    pub fn char_size(&self) -> Option<(usize, usize)> {
        if self.width == 0 {
            None
        } else {
            Some((self.width.max(3), self.height.max(1)))
        }
    }

    fn build_lines(&self, actual_width: usize) -> Vec<Line<'static>> {
        let w = actual_width.max(3);
        let mut engine = RectEngine::build(w, self.height, self.arc_width, self.spin, self.motion);

        #[allow(clippy::cast_possible_truncation)]
        let steps = (self.tick / self.ticks_per_step) as usize;
        for _ in 0..steps {
            engine.walk();
        }

        engine.render_lines(
            self.arc_color,
            self.dim_color,
            self.fade_width,
            self.track.byte(),
            self.arc_byte,
            self.bar_style.chars(),
        )
    }
}

// ── Trait impls ───────────────────────────────────────────────────────────────

impl_styled_for!(BarSpinner<'_>);

impl_widget_via_ref!(BarSpinner<'_>);

impl Widget for &BarSpinner<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        if area.area() == 0 {
            return;
        }

        buf.set_style(area, self.style);

        let inner_area = self.block.as_ref().map_or(area, |b| {
            let inner = b.inner(area);
            Widget::render(b.clone(), area, buf);
            inner
        });

        if inner_area.area() == 0 {
            return;
        }

        // Resolve width: explicit fixed value, or fill available area.
        let actual_width = if self.width == 0 {
            inner_area.width as usize
        } else {
            self.width
        };

        let lines = self.build_lines(actual_width);
        Paragraph::new(lines)
            .alignment(self.alignment)
            .render(inner_area, buf);
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::{backend::TestBackend, Terminal};

    // ── Engine: construction ──────────────────────────────────────────────────

    #[test]
    fn engine_builds_without_panic() {
        for w in 3..=30usize {
            for h in 1..=5usize {
                for spin in [Spin::Clockwise, Spin::CounterClockwise] {
                    let _ = RectEngine::build(w, h, 0, spin, BarMotion::Bounce);
                }
            }
        }
    }

    #[test]
    fn engine_walk_does_not_panic() {
        let mut e = RectEngine::build(20, 1, 0, Spin::Clockwise, BarMotion::Bounce);
        for _ in 0..1000 {
            e.walk();
        }
    }

    #[test]
    fn engine_anchor_stays_in_bounds() {
        let mut e = RectEngine::build(20, 1, 0, Spin::Clockwise, BarMotion::Bounce);
        let max_anchor = e.char_w.saturating_sub(e.arc_cols);
        for _ in 0..500 {
            e.walk();
            assert!(
                e.anchor <= max_anchor,
                "anchor={} exceeds max={max_anchor}",
                e.anchor
            );
        }
    }

    #[test]
    fn engine_bounces_direction() {
        let mut e = RectEngine::build(20, 1, 0, Spin::Clockwise, BarMotion::Bounce);
        assert!(e.going_forward, "should start going forward (CW)");

        // Walk until direction reverses to backward.
        let mut reversed = false;
        for _ in 0..100 {
            e.walk();
            if !e.going_forward {
                reversed = true;
                break;
            }
        }
        assert!(reversed, "engine never reversed to backward");

        // Walk until it reverses back to forward.
        let mut re_reversed = false;
        for _ in 0..100 {
            e.walk();
            if e.going_forward {
                re_reversed = true;
                break;
            }
        }
        assert!(re_reversed, "engine never reversed back to forward");
    }

    #[test]
    fn cw_starts_at_left_ccw_at_right() {
        let cw = RectEngine::build(20, 1, 0, Spin::Clockwise, BarMotion::Bounce);
        let ccw = RectEngine::build(20, 1, 0, Spin::CounterClockwise, BarMotion::Bounce);
        assert_eq!(cw.anchor, 0, "CW should start at column 0");
        assert!(
            ccw.anchor > 0,
            "CCW should start at the right (anchor={})",
            ccw.anchor
        );
        assert!(cw.going_forward);
        assert!(!ccw.going_forward);
    }

    // ── Fade ramp ─────────────────────────────────────────────────────────────

    #[test]
    fn arc_edges_use_fade_bytes() {
        // Build a wide engine so there is a full-density centre.
        let e = RectEngine::build(20, 1, 12, Spin::Clockwise, BarMotion::Bounce);
        let lines = e.render_lines(Color::Cyan, Color::DarkGray, 3, DIM_BYTE, 0xFF, None);
        assert_eq!(lines.len(), 1);
        let spans = &lines[0].spans;

        // The outermost arc column (index anchor+0) should be FADE[0] = 0x09.
        let outer = char::from_u32(0x2800 + u32::from(FADE[0])).unwrap();
        assert_eq!(
            spans[e.anchor].content.chars().next(),
            Some(outer),
            "outermost arc edge should be FADE[0]"
        );

        // The centre arc column (index anchor + arc_cols/2) should be FADE[3] = 0xFF.
        let centre_idx = e.anchor + e.arc_cols / 2;
        let full = char::from_u32(0x2800 + u32::from(FADE[3])).unwrap();
        assert_eq!(
            spans[centre_idx].content.chars().next(),
            Some(full),
            "arc centre should be full density FADE[3]"
        );
    }

    #[test]
    fn dim_columns_use_dim_byte() {
        let e = RectEngine::build(20, 1, 6, Spin::Clockwise, BarMotion::Bounce);
        let lines = e.render_lines(Color::Cyan, Color::DarkGray, 3, DIM_BYTE, 0xFF, None);
        let spans = &lines[0].spans;
        let dim_char = char::from_u32(0x2800 + u32::from(DIM_BYTE)).unwrap();
        // Columns before the arc anchor should all be DIM_BYTE.
        for i in 0..e.anchor {
            assert_eq!(
                spans[i].content.chars().next(),
                Some(dim_char),
                "column {i} should be dim"
            );
        }
    }

    // ── Widget output ─────────────────────────────────────────────────────────

    #[test]
    fn build_lines_height_matches() {
        for h in 1..=5usize {
            let lines = BarSpinner::new(0).width(20).height(h).build_lines(20);
            assert_eq!(lines.len(), h, "height={h}");
        }
    }

    #[test]
    fn build_lines_width_matches() {
        let w = 24usize;
        let lines = BarSpinner::new(0).width(w).height(1).build_lines(w);
        assert_eq!(lines[0].spans.len(), w, "each line should have {w} spans");
    }

    #[test]
    fn different_ticks_produce_different_output() {
        let a = BarSpinner::new(0).width(20).height(1).build_lines(20);
        let b = BarSpinner::new(8).width(20).height(1).build_lines(20);
        assert_ne!(a, b, "tick=0 and tick=8 should differ");
    }

    #[test]
    fn cw_and_ccw_differ_at_same_tick() {
        let cw = BarSpinner::new(5)
            .width(20)
            .height(1)
            .spin(Spin::Clockwise)
            .build_lines(20);
        let ccw = BarSpinner::new(5)
            .width(20)
            .height(1)
            .spin(Spin::CounterClockwise)
            .build_lines(20);
        assert_ne!(cw, ccw, "CW and CCW should differ at the same tick");
    }

    #[test]
    fn ticks_per_step_slows_animation() {
        let fast = BarSpinner::new(10)
            .width(20)
            .height(1)
            .ticks_per_step(1)
            .build_lines(20);
        let slow = BarSpinner::new(10)
            .width(20)
            .height(1)
            .ticks_per_step(5)
            .build_lines(20);
        assert_ne!(
            fast, slow,
            "different speeds should produce different output"
        );
    }

    #[test]
    fn arc_width_override_respected() {
        let e = RectEngine::build(20, 1, 7, Spin::Clockwise, BarMotion::Bounce);
        assert_eq!(e.arc_cols, 7);
    }

    // ── Widget rendering ──────────────────────────────────────────────────────

    #[test]
    fn widget_renders_without_panic() {
        let backend = TestBackend::new(40, 3);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                frame.render_widget(BarSpinner::new(42), frame.area());
            })
            .unwrap();
    }

    #[test]
    fn widget_fixed_width_renders_without_panic() {
        let backend = TestBackend::new(40, 3);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                frame.render_widget(BarSpinner::new(42).width(24).height(2), frame.area());
            })
            .unwrap();
    }

    #[test]
    fn widget_zero_area_no_panic() {
        let backend = TestBackend::new(0, 0);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                frame.render_widget(BarSpinner::new(0), frame.area());
            })
            .unwrap();
    }

    #[test]
    fn char_size_fixed_width() {
        let s = BarSpinner::new(0).width(20).height(2);
        assert_eq!(s.char_size(), Some((20, 2)));
    }

    #[test]
    fn char_size_auto_width_is_none() {
        let s = BarSpinner::new(0); // width = 0 = auto
        assert_eq!(s.char_size(), None);
    }

    #[test]
    fn char_size_clamps_minimum() {
        let s = BarSpinner::new(0).width(1).height(0);
        if let Some((w, h)) = s.char_size() {
            assert!(w >= 3, "width clamped to at least 3");
            assert!(h >= 1, "height clamped to at least 1");
        }
    }

    // ── Builder chain ─────────────────────────────────────────────────────────

    #[test]
    fn builder_chain() {
        use ratatui::widgets::Block;
        let s = BarSpinner::new(0)
            .width(24)
            .height(2)
            .arc_width(8)
            .spin(Spin::CounterClockwise)
            .ticks_per_step(3)
            .arc_color(Color::Blue)
            .dim_color(Color::Black)
            .block(Block::bordered())
            .alignment(Alignment::Center);
        assert_eq!(s.width, 24);
        assert_eq!(s.height, 2);
        assert_eq!(s.arc_width, 8);
        assert!(matches!(s.spin, Spin::CounterClockwise));
        assert_eq!(s.ticks_per_step, 3);
        assert_eq!(s.arc_color, Color::Blue);
        assert_eq!(s.dim_color, Color::Black);
    }

    #[test]
    fn arc_char_changes_centre_byte() {
        let e = RectEngine::build(20, 1, 10, Spin::Clockwise, BarMotion::Bounce);
        // Default arc_byte = 0xFF → centre cell is ⣿
        let lines_default = e.render_lines(Color::Cyan, Color::DarkGray, 3, DIM_BYTE, 0xFF, None);
        // Custom arc_byte = 0x3F → centre cell is ⠿
        let lines_custom = e.render_lines(Color::Cyan, Color::DarkGray, 3, DIM_BYTE, 0x3F, None);
        assert_ne!(
            lines_default, lines_custom,
            "different arc_byte produces different output"
        );
        // The centre span in lines_custom should be ⠿ (U+283F)
        let centre_idx = e.anchor + e.arc_cols / 2;
        let centre_char = lines_custom[0].spans[centre_idx]
            .content
            .chars()
            .next()
            .unwrap();
        assert_eq!(
            centre_char, '\u{283F}',
            "centre cell should be ⠿ when arc_byte=0x3F"
        );
    }

    #[test]
    fn preset_zed_defaults() {
        let s = BarSpinner::zed(0);
        assert_eq!(s.height, 1);
        assert_eq!(s.arc_color, Color::Cyan);
    }

    #[test]
    fn preset_solid_has_full_track_and_zero_fade() {
        let s = BarSpinner::solid(0);
        assert_eq!(s.track, BarTrack::Full);
        assert_eq!(s.fade_width, 0);
    }

    #[test]
    fn track_and_fade_width_builder() {
        let s = BarSpinner::new(0).track(BarTrack::Full).fade_width(0);
        assert_eq!(s.track, BarTrack::Full);
        assert_eq!(s.fade_width, 0);

        // Sharp fade: every arc cell should show full density (FADE[3] = 0xFF).
        let lines = s.width(12).build_lines(12);
        // All spans should be ⣿ (U+28FF) in arc_color OR ⣿ in dim_color (Full track).
        for line in &lines {
            for span in &line.spans {
                let ch = span.content.chars().next().unwrap();
                assert_eq!(ch, '\u{28FF}', "sharp fade + Full track → every cell is ⣿");
            }
        }
    }

    // ── with_colors convenience ────────────────────────────────────────────────

    #[test]
    fn with_colors_sets_both() {
        use ratatui::style::Color;
        let s = BarSpinner::new(0).with_colors(Color::Red, Color::Blue);
        assert_eq!(s.arc_color, Color::Red);
        assert_eq!(s.dim_color, Color::Blue);
    }

    // ── Arc width clamping ────────────────────────────────────────────────────

    #[test]
    fn arc_width_larger_than_bar_is_clamped() {
        // arc_width > char_w should be clamped to char_w - 1 inside the engine.
        let e = RectEngine::build(10, 1, 99, Spin::Clockwise, BarMotion::Bounce);
        assert!(e.arc_cols < e.char_w, "arc_cols must be < char_w");
    }

    #[test]
    fn arc_width_zero_uses_auto() {
        let e = RectEngine::build(30, 1, 0, Spin::Clockwise, BarMotion::Bounce);
        assert!(e.arc_cols >= 4, "auto arc should be at least 4 cols");
        assert!(e.arc_cols < e.char_w);
    }

    // ── Loop wraps correctly across the full range ────────────────────────────

    #[test]
    fn loop_all_columns_lit_over_full_cycle() {
        let width = 12usize;
        let arc_cols = 4usize;
        let mut e = RectEngine::build(width, 1, arc_cols, Spin::Clockwise, BarMotion::Loop);
        let mut ever_lit = vec![false; width];

        // Walk one full cycle (char_w steps) and record which columns are lit.
        for _ in 0..width {
            let lines = e.render_lines(
                ratatui::style::Color::Cyan,
                ratatui::style::Color::DarkGray,
                3,
                DIM_BYTE,
                0xFF,
                None,
            );
            for (ci, span) in lines[0].spans.iter().enumerate() {
                if span.style.fg == Some(ratatui::style::Color::Cyan) {
                    ever_lit[ci] = true;
                }
            }
            e.walk();
        }

        // Every column should have been lit at least once.
        for (ci, &lit) in ever_lit.iter().enumerate() {
            assert!(lit, "column {ci} was never lit during a full Loop cycle");
        }
    }

    // ── BarStyle produces expected characters ─────────────────────────────────

    #[test]
    fn non_braille_style_chars_match_declaration() {
        for (style, expected_arc, expected_track) in [
            (BarStyle::Block, '\u{2588}', '\u{2591}'),
            (BarStyle::Dot, '\u{25CF}', '\u{00B7}'),
            (BarStyle::Star, '\u{2605}', '\u{2606}'),
            (BarStyle::Progress, '\u{25B0}', '\u{25B1}'),
        ] {
            let Some((arc, track)) = style.chars() else {
                panic!("{style:?} should have char pair");
            };
            assert_eq!(arc, expected_arc, "{style:?} arc char mismatch");
            assert_eq!(track, expected_track, "{style:?} track char mismatch");
        }
    }

    #[test]
    fn bar_style_block_produces_non_braille_chars() {
        let lines = BarSpinner::new(0)
            .width(20)
            .bar_style(BarStyle::Block)
            .build_lines(20);
        // Every character should be either █ or ░
        for line in &lines {
            for span in &line.spans {
                let ch = span.content.chars().next().unwrap();
                assert!(
                    ch == '' || ch == '',
                    "Block style: unexpected char U+{:04X}",
                    ch as u32
                );
            }
        }
    }

    #[test]
    fn all_non_braille_styles_have_char_pairs() {
        let styles = [
            BarStyle::Block,
            BarStyle::Shade,
            BarStyle::Dot,
            BarStyle::Diamond,
            BarStyle::Square,
            BarStyle::Star,
            BarStyle::Heart,
            BarStyle::Arrow,
            BarStyle::Circle,
            BarStyle::Spark,
            BarStyle::Cross,
            BarStyle::Progress,
            BarStyle::Thick,
            BarStyle::Wave,
            BarStyle::Pip,
        ];
        for style in styles {
            assert!(style.chars().is_some(), "{style:?} should have a char pair");
        }
        assert!(BarStyle::Braille.chars().is_none());
    }

    #[test]
    fn bar_style_builder() {
        let s = BarSpinner::new(0).bar_style(BarStyle::Dot);
        assert_eq!(s.bar_style, BarStyle::Dot);
    }

    // ── BarMotion ──────────────────────────────────────────────────────────────────

    #[test]
    fn loop_motion_wraps_at_right_edge() {
        let mut e = RectEngine::build(20, 1, 4, Spin::Clockwise, BarMotion::Loop);
        // Loop anchor travels 0..char_w modularly (not 0..char_w-arc_cols).
        let last = e.char_w - 1;
        for _ in 0..200 {
            if e.anchor == last {
                break;
            }
            e.walk();
        }
        assert_eq!(e.anchor, last, "anchor should reach char_w-1");
        e.walk();
        assert_eq!(e.anchor, 0, "Loop CW should wrap to 0");
        assert!(e.going_forward, "Loop must not flip direction");
    }

    #[test]
    fn loop_motion_wraps_at_left_edge_ccw() {
        let mut e = RectEngine::build(20, 1, 4, Spin::CounterClockwise, BarMotion::Loop);
        // CCW starts at char_w - arc_cols; walk it to 0.
        for _ in 0..200 {
            if e.anchor == 0 {
                break;
            }
            e.walk();
        }
        assert_eq!(e.anchor, 0);
        e.walk();
        assert_eq!(e.anchor, e.char_w - 1, "CCW Loop should wrap to char_w-1");
        assert!(!e.going_forward);
    }

    #[test]
    fn bounce_still_reverses() {
        let mut e = RectEngine::build(20, 1, 4, Spin::Clockwise, BarMotion::Bounce);
        let max = e.char_w - e.arc_cols;
        for _ in 0..100 {
            if e.anchor == max {
                break;
            }
            e.walk();
        }
        e.walk();
        assert!(!e.going_forward, "Bounce must reverse at max_anchor");
    }

    #[test]
    fn motion_builder() {
        let s = BarSpinner::new(0).motion(BarMotion::Loop);
        assert_eq!(s.motion, BarMotion::Loop);
    }
}