ftui-core 0.4.0

Terminal lifecycle, capabilities, and event parsing for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Hover jitter stabilization using CUSUM change-point detection.
//!
//! Eliminates hover flicker when the pointer jitters around widget boundaries
//! while maintaining responsiveness for intentional target changes.
//!
//! # Algorithm
//!
//! The stabilizer uses a simplified CUSUM (Cumulative Sum) change-point detector:
//!
//! - Track signed distance `d_t` to current target boundary (positive = inside)
//! - Compute cumulative sum: `S_t = max(0, S_{t-1} + d_t - k)` where `k` is drift allowance
//! - Switch target only when `S_t > h` (threshold) indicating strong evidence of intent
//!
//! A hysteresis band around boundaries prevents oscillation from single-cell jitter.
//!
//! # Invariants
//!
//! 1. Hover target only changes when evidence exceeds threshold
//! 2. Single-cell jitter sequences do not cause target flicker
//! 3. Intentional crossing (steady motion) triggers switch within ~2 frames
//! 4. No measurable overhead (<2%) on hit-test pipeline
//!
//! # Failure Modes
//!
//! - If hit-test returns None consistently, stabilizer holds last known target
//! - If threshold is too high, responsiveness degrades (tune via config)
//! - If drift allowance is too low, jitter causes accumulation (tune k parameter)
//!
//! # Evidence Ledger
//!
//! In debug mode, the stabilizer logs:
//! - CUSUM score at each update
//! - Hysteresis state (inside band vs. outside)
//! - Target switch events with evidence values

use web_time::{Duration, Instant};

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration for hover jitter stabilization.
#[derive(Debug, Clone)]
pub struct HoverStabilizerConfig {
    /// CUSUM drift allowance `k`. Higher = more tolerant of boundary oscillation.
    /// Default: 0.5 (normalized distance units)
    pub drift_allowance: f32,

    /// CUSUM detection threshold `h`. Switch target when cumulative score exceeds this.
    /// Default: 2.0 (equivalent to ~2-3 frames of consistent crossing signal)
    pub detection_threshold: f32,

    /// Hysteresis band width in cells. Pointer must move this far past boundary
    /// before the boundary crossing is considered definitive.
    /// Default: 1 cell
    pub hysteresis_cells: u16,

    /// Decay rate for CUSUM score when pointer is inside current target.
    /// Prevents lingering switch intent from stale history.
    /// Default: 0.1 per frame
    pub decay_rate: f32,

    /// Maximum duration to hold a target when no hit updates arrive.
    /// After this, target resets to None.
    /// Default: 500ms
    pub hold_timeout: Duration,
}

impl Default for HoverStabilizerConfig {
    fn default() -> Self {
        Self {
            drift_allowance: 0.5,
            detection_threshold: 2.0,
            hysteresis_cells: 1,
            decay_rate: 0.1,
            hold_timeout: Duration::from_millis(500),
        }
    }
}

// ---------------------------------------------------------------------------
// Candidate tracking
// ---------------------------------------------------------------------------

/// Tracks a potential new hover target and its CUSUM evidence.
#[derive(Debug, Clone)]
struct CandidateTarget {
    /// The potential new target ID.
    target_id: u64,
    /// Cumulative sum evidence score.
    cusum_score: f32,
    /// Last position where this candidate was observed.
    last_pos: (u16, u16),
}

// ---------------------------------------------------------------------------
// HoverStabilizer
// ---------------------------------------------------------------------------

/// Stateful hover stabilizer that prevents jitter-induced target flicker.
///
/// Feed hit-test results via [`update`](HoverStabilizer::update) and read
/// the stabilized target from [`current_target`](HoverStabilizer::current_target).
#[derive(Debug)]
pub struct HoverStabilizer {
    config: HoverStabilizerConfig,

    /// Current stabilized hover target (None = no hover).
    current_target: Option<u64>,

    /// Position when current target was established.
    current_target_pos: Option<(u16, u16)>,

    /// Timestamp of last update.
    last_update: Option<Instant>,

    /// Candidate target being evaluated for switch.
    candidate: Option<CandidateTarget>,

    /// Diagnostic: total switch events.
    switches: u64,
}

impl HoverStabilizer {
    /// Create a new hover stabilizer with the given configuration.
    #[must_use]
    pub fn new(config: HoverStabilizerConfig) -> Self {
        Self {
            config,
            current_target: None,
            current_target_pos: None,
            last_update: None,
            candidate: None,
            switches: 0,
        }
    }

    /// Update the stabilizer with a new hit-test result.
    ///
    /// # Arguments
    ///
    /// - `hit_target`: The raw hit-test target ID (None = no hit)
    /// - `pos`: Current pointer position
    /// - `now`: Current timestamp
    ///
    /// # Returns
    ///
    /// The stabilized hover target, which may differ from `hit_target` to
    /// prevent jitter-induced flicker.
    pub fn update(
        &mut self,
        hit_target: Option<u64>,
        pos: (u16, u16),
        now: Instant,
    ) -> Option<u64> {
        // Check for hold timeout
        if let Some(last) = self.last_update
            && now.saturating_duration_since(last) > self.config.hold_timeout
        {
            self.reset();
        }
        self.last_update = Some(now);

        // No current target: adopt immediately
        if self.current_target.is_none() {
            if hit_target.is_some() {
                self.current_target = hit_target;
                self.current_target_pos = Some(pos);
                self.switches += 1;
            }
            return self.current_target;
        }

        let current = self
            .current_target
            .expect("current_target guaranteed by is_none early return");

        // Same target: decay any candidate and return stable
        if hit_target == Some(current) {
            self.decay_candidate();
            self.current_target_pos = Some(pos);
            return self.current_target;
        }

        // Different target (or None): evaluate with CUSUM
        let candidate_id = hit_target.unwrap_or(u64::MAX); // Use sentinel for None

        // Compute signed distance to current target position
        let distance = self.compute_distance_signal(pos);

        self.update_candidate(candidate_id, distance, pos);

        // Check if candidate evidence exceeds threshold
        if let Some(ref cand) = self.candidate
            && cand.cusum_score >= self.config.detection_threshold
            && self.past_hysteresis_band(pos)
        {
            // Switch target
            self.current_target = if candidate_id == u64::MAX {
                None
            } else {
                Some(candidate_id)
            };
            self.current_target_pos = Some(pos);
            self.candidate = None;
            self.switches += 1;
        }

        self.current_target
    }

    /// Get the current stabilized hover target.
    #[inline]
    #[must_use]
    pub fn current_target(&self) -> Option<u64> {
        self.current_target
    }

    /// Reset all state to initial.
    pub fn reset(&mut self) {
        self.current_target = None;
        self.current_target_pos = None;
        self.last_update = None;
        self.candidate = None;
    }

    /// Get the number of target switches (diagnostic).
    #[inline]
    #[must_use]
    pub fn switch_count(&self) -> u64 {
        self.switches
    }

    /// Get a reference to the current configuration.
    #[inline]
    #[must_use]
    pub fn config(&self) -> &HoverStabilizerConfig {
        &self.config
    }

    /// Update the configuration.
    pub fn set_config(&mut self, config: HoverStabilizerConfig) {
        self.config = config;
    }

    // -----------------------------------------------------------------------
    // Internal helpers
    // -----------------------------------------------------------------------

    /// Compute distance signal for CUSUM update.
    ///
    /// Returns positive value when moving away from current target (toward boundary exit),
    /// negative when inside target area.
    fn compute_distance_signal(&self, pos: (u16, u16)) -> f32 {
        let Some(target_pos) = self.current_target_pos else {
            return 1.0; // No reference point: signal exit
        };

        // Manhattan distance from target position
        let dx = (pos.0 as i32 - target_pos.0 as i32).abs();
        let dy = (pos.1 as i32 - target_pos.1 as i32).abs();
        let manhattan = (dx + dy) as f32;

        // Normalize by hysteresis band
        let hysteresis = self.config.hysteresis_cells.max(1) as f32;

        // Positive = outside hysteresis band (moving away)
        // Negative = inside hysteresis band (stable)
        (manhattan - hysteresis) / hysteresis
    }

    /// Update CUSUM for candidate target.
    fn update_candidate(&mut self, candidate_id: u64, distance_signal: f32, pos: (u16, u16)) {
        let k = self.config.drift_allowance;

        match &mut self.candidate {
            Some(cand) if cand.target_id == candidate_id => {
                // Same candidate: accumulate evidence
                // S_t = max(0, S_{t-1} + d_t - k)
                cand.cusum_score = (cand.cusum_score + distance_signal - k).max(0.0);
                cand.last_pos = pos;
            }
            _ => {
                // New candidate: start fresh
                let initial_score = (distance_signal - k).max(0.0);
                self.candidate = Some(CandidateTarget {
                    target_id: candidate_id,
                    cusum_score: initial_score,
                    last_pos: pos,
                });
            }
        }
    }

    /// Decay candidate evidence when pointer returns to current target.
    fn decay_candidate(&mut self) {
        if let Some(ref mut cand) = self.candidate {
            cand.cusum_score *= 1.0 - self.config.decay_rate;
            if cand.cusum_score < 0.01 {
                self.candidate = None;
            }
        }
    }

    /// Check if current position is past the hysteresis band.
    fn past_hysteresis_band(&self, pos: (u16, u16)) -> bool {
        let Some(target_pos) = self.current_target_pos else {
            return true; // No reference: allow switch
        };

        let dx = (pos.0 as i32 - target_pos.0 as i32).unsigned_abs();
        let dy = (pos.1 as i32 - target_pos.1 as i32).unsigned_abs();
        let manhattan = dx + dy;

        manhattan > u32::from(self.config.hysteresis_cells)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn now() -> Instant {
        Instant::now()
    }

    fn stabilizer() -> HoverStabilizer {
        HoverStabilizer::new(HoverStabilizerConfig::default())
    }

    // --- Basic functionality tests ---

    #[test]
    fn initial_state_is_none() {
        let stab = stabilizer();
        assert!(stab.current_target().is_none());
        assert_eq!(stab.switch_count(), 0);
    }

    #[test]
    fn first_hit_adopted_immediately() {
        let mut stab = stabilizer();
        let t = now();

        let target = stab.update(Some(42), (10, 10), t);
        assert_eq!(target, Some(42));
        assert_eq!(stab.current_target(), Some(42));
        assert_eq!(stab.switch_count(), 1);
    }

    #[test]
    fn same_target_stays_stable() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);
        stab.update(Some(42), (10, 11), t);
        stab.update(Some(42), (11, 10), t);

        assert_eq!(stab.current_target(), Some(42));
        assert_eq!(stab.switch_count(), 1); // Only initial adoption
    }

    #[test]
    fn jitter_does_not_switch() {
        let mut stab = stabilizer();
        let t = now();

        // Establish target
        stab.update(Some(42), (10, 10), t);

        // Jitter: alternate between targets at boundary
        for i in 0..10 {
            let target = if i % 2 == 0 { Some(99) } else { Some(42) };
            stab.update(target, (10, 10 + (i % 2)), t);
        }

        // Should still be on original target due to CUSUM not accumulating
        assert_eq!(stab.current_target(), Some(42));
    }

    #[test]
    fn sustained_crossing_triggers_switch() {
        let mut stab = stabilizer();
        let t = now();

        // Establish target at (10, 10)
        stab.update(Some(42), (10, 10), t);

        // Move steadily away to new target
        // Need to exceed threshold + hysteresis
        for i in 1..=5 {
            stab.update(Some(99), (10, 10 + i * 2), t);
        }

        // Should have switched to new target
        assert_eq!(stab.current_target(), Some(99));
        assert!(stab.switch_count() >= 2);
    }

    #[test]
    fn reset_clears_all_state() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);
        stab.reset();

        assert!(stab.current_target().is_none());
    }

    // --- CUSUM algorithm tests ---

    #[test]
    fn cusum_accumulates_on_consistent_signal() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            detection_threshold: 3.0,
            hysteresis_cells: 0, // Disable hysteresis for this test
            ..Default::default()
        });
        let t = now();

        // Establish target
        stab.update(Some(42), (10, 10), t);

        // Consistent move away
        stab.update(Some(99), (15, 10), t);
        stab.update(Some(99), (20, 10), t);
        stab.update(Some(99), (25, 10), t);

        // Should have accumulated enough to switch
        assert_eq!(stab.current_target(), Some(99));
    }

    #[test]
    fn cusum_resets_on_return() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Briefly move away
        stab.update(Some(99), (12, 10), t);

        // Return to original target
        stab.update(Some(42), (10, 10), t);
        stab.update(Some(42), (10, 10), t);
        stab.update(Some(42), (10, 10), t);

        // Should still be on original (candidate decayed)
        assert_eq!(stab.current_target(), Some(42));
    }

    // --- Hysteresis tests ---

    #[test]
    fn hysteresis_prevents_boundary_oscillation() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hysteresis_cells: 2,
            detection_threshold: 0.5, // Low threshold to test hysteresis
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Move just past boundary but within hysteresis
        stab.update(Some(99), (11, 10), t);
        assert_eq!(stab.current_target(), Some(42));

        // Move beyond hysteresis band (>2 cells)
        stab.update(Some(99), (13, 10), t);
        stab.update(Some(99), (14, 10), t);
        stab.update(Some(99), (15, 10), t);

        // Now should switch
        assert_eq!(stab.current_target(), Some(99));
    }

    // --- Timeout tests ---

    #[test]
    fn timeout_resets_target() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hold_timeout: Duration::from_millis(100),
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);
        assert_eq!(stab.current_target(), Some(42));

        // Update after timeout
        let later = t + Duration::from_millis(200);
        stab.update(Some(99), (20, 20), later);

        // Should have reset and adopted new target
        assert_eq!(stab.current_target(), Some(99));
    }

    // --- None target tests ---

    #[test]
    fn transition_to_none_with_evidence() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hysteresis_cells: 0,
            detection_threshold: 1.0,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Move away with no target
        for i in 1..=5 {
            stab.update(None, (10 + i * 3, 10), t);
        }

        // Should eventually transition to None
        assert!(stab.current_target().is_none());
    }

    // --- Property tests ---

    #[test]
    fn jitter_stability_rate() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // 100 jitter oscillations
        let mut stable_count = 0;
        for i in 0..100 {
            let target = if i % 2 == 0 { Some(99) } else { Some(42) };
            stab.update(target, (10, 10), t);
            if stab.current_target() == Some(42) {
                stable_count += 1;
            }
        }

        // Should maintain >99% stability under jitter
        assert!(stable_count >= 99, "Stable count: {}", stable_count);
    }

    #[test]
    fn crossing_detection_latency() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hysteresis_cells: 1,
            detection_threshold: 1.5,
            drift_allowance: 0.3,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Count frames until switch during steady motion
        let mut frames = 0;
        for i in 1..=10 {
            stab.update(Some(99), (10, 10 + i * 2), t);
            frames += 1;
            if stab.current_target() == Some(99) {
                break;
            }
        }

        // Should switch within 3 frames
        assert!(frames <= 3, "Switch took {} frames", frames);
    }

    // --- Config tests ---

    #[test]
    fn config_getter_and_setter() {
        let mut stab = stabilizer();

        assert_eq!(stab.config().detection_threshold, 2.0);

        stab.set_config(HoverStabilizerConfig {
            detection_threshold: 5.0,
            ..Default::default()
        });

        assert_eq!(stab.config().detection_threshold, 5.0);
    }

    #[test]
    fn default_config_values() {
        let config = HoverStabilizerConfig::default();
        assert_eq!(config.drift_allowance, 0.5);
        assert_eq!(config.detection_threshold, 2.0);
        assert_eq!(config.hysteresis_cells, 1);
        assert_eq!(config.decay_rate, 0.1);
        assert_eq!(config.hold_timeout, Duration::from_millis(500));
    }

    // --- Debug format test ---

    #[test]
    fn debug_format() {
        let stab = stabilizer();
        let dbg = format!("{:?}", stab);
        assert!(dbg.contains("HoverStabilizer"));
    }

    #[test]
    fn switch_count_preserved_after_reset() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);
        assert_eq!(stab.switch_count(), 1);

        stab.reset();
        // switch count is NOT cleared by reset (it's a diagnostic counter)
        assert_eq!(stab.switch_count(), 1);
        assert!(stab.current_target().is_none());
    }

    #[test]
    fn none_hit_when_no_current_target() {
        let mut stab = stabilizer();
        let t = now();

        // Update with None when no target established
        let target = stab.update(None, (10, 10), t);
        assert_eq!(target, None);
        assert_eq!(stab.switch_count(), 0);
    }

    #[test]
    fn config_clone() {
        let config = HoverStabilizerConfig::default();
        let cloned = config.clone();
        assert_eq!(cloned.drift_allowance, config.drift_allowance);
        assert_eq!(cloned.detection_threshold, config.detection_threshold);
        assert_eq!(cloned.hysteresis_cells, config.hysteresis_cells);
    }

    // ── Edge-case: Config ────────────────────────────────────────────

    #[test]
    fn config_debug_format() {
        let config = HoverStabilizerConfig::default();
        let dbg = format!("{:?}", config);
        assert!(dbg.contains("HoverStabilizerConfig"));
        assert!(dbg.contains("drift_allowance"));
    }

    #[test]
    fn config_zero_hysteresis() {
        let config = HoverStabilizerConfig {
            hysteresis_cells: 0,
            ..Default::default()
        };
        assert_eq!(config.hysteresis_cells, 0);
    }

    #[test]
    fn config_zero_hold_timeout() {
        let config = HoverStabilizerConfig {
            hold_timeout: Duration::ZERO,
            ..Default::default()
        };
        assert_eq!(config.hold_timeout, Duration::ZERO);
    }

    // ── Edge-case: HoverStabilizer creation ──────────────────────────

    #[test]
    fn new_with_custom_config() {
        let config = HoverStabilizerConfig {
            drift_allowance: 1.0,
            detection_threshold: 10.0,
            hysteresis_cells: 5,
            decay_rate: 0.5,
            hold_timeout: Duration::from_secs(2),
        };
        let stab = HoverStabilizer::new(config);
        assert!(stab.current_target().is_none());
        assert_eq!(stab.switch_count(), 0);
        assert_eq!(stab.config().drift_allowance, 1.0);
        assert_eq!(stab.config().detection_threshold, 10.0);
        assert_eq!(stab.config().hysteresis_cells, 5);
    }

    // ── Edge-case: Reset behavior ────────────────────────────────────

    #[test]
    fn reset_then_adopt_new_target() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);
        assert_eq!(stab.current_target(), Some(42));

        stab.reset();
        assert!(stab.current_target().is_none());

        // New target should be adopted immediately after reset
        let target = stab.update(Some(99), (20, 20), t);
        assert_eq!(target, Some(99));
        assert_eq!(stab.switch_count(), 2); // original + re-adopt
    }

    #[test]
    fn multiple_resets_are_idempotent() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);
        stab.reset();
        stab.reset();
        stab.reset();

        assert!(stab.current_target().is_none());
        // switch count preserved across all resets
        assert_eq!(stab.switch_count(), 1);
    }

    // ── Edge-case: Timeout boundary ──────────────────────────────────

    #[test]
    fn exactly_at_timeout_does_not_reset() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hold_timeout: Duration::from_millis(100),
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Update at exactly the timeout duration (not beyond)
        let at_boundary = t + Duration::from_millis(100);
        let target = stab.update(Some(42), (10, 10), at_boundary);
        // At boundary (duration_since == hold_timeout), > check means no reset
        assert_eq!(target, Some(42));
    }

    #[test]
    fn just_past_timeout_resets() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hold_timeout: Duration::from_millis(100),
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Update just past the timeout
        let past = t + Duration::from_millis(101);
        let target = stab.update(Some(99), (20, 20), past);
        // Should have reset and adopted new target
        assert_eq!(target, Some(99));
    }

    #[test]
    fn timeout_then_none_hit() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hold_timeout: Duration::from_millis(50),
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        let later = t + Duration::from_millis(100);
        let target = stab.update(None, (10, 10), later);
        // Should reset and then None hit means no target
        assert_eq!(target, None);
    }

    // ── Edge-case: Position boundaries ───────────────────────────────

    #[test]
    fn position_at_origin() {
        let mut stab = stabilizer();
        let t = now();

        let target = stab.update(Some(1), (0, 0), t);
        assert_eq!(target, Some(1));
    }

    #[test]
    fn position_at_u16_max() {
        let mut stab = stabilizer();
        let t = now();

        let target = stab.update(Some(1), (u16::MAX, u16::MAX), t);
        assert_eq!(target, Some(1));
        assert_eq!(stab.current_target(), Some(1));
    }

    #[test]
    fn same_position_different_targets_no_switch() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Same position, different target — distance signal is 0
        // So CUSUM score stays low (0 - k < 0 → clamped to 0)
        for _ in 0..20 {
            stab.update(Some(99), (10, 10), t);
        }

        // Within hysteresis band (distance = 0), should not switch
        assert_eq!(stab.current_target(), Some(42));
    }

    // ── Edge-case: Multiple sequential targets ───────────────────────

    #[test]
    fn candidate_resets_on_new_third_target() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hysteresis_cells: 0,
            detection_threshold: 5.0, // High threshold
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Start building evidence for target 99
        stab.update(Some(99), (15, 10), t);
        stab.update(Some(99), (20, 10), t);

        // Switch to target 77 (candidate should reset for new target)
        stab.update(Some(77), (25, 10), t);
        stab.update(Some(77), (30, 10), t);
        stab.update(Some(77), (35, 10), t);
        stab.update(Some(77), (40, 10), t);
        stab.update(Some(77), (45, 10), t);

        // Should eventually switch to 77 (not 99)
        assert!(
            stab.current_target() == Some(77) || stab.current_target() == Some(42),
            "target should be 77 or still 42, got {:?}",
            stab.current_target()
        );
    }

    // ── Edge-case: High/low detection threshold ──────────────────────

    #[test]
    fn very_high_threshold_prevents_switching() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            detection_threshold: 100_000.0,
            hysteresis_cells: 0,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Large movements but CUSUM accumulation (~2070) << threshold (100_000)
        for i in 1..=20 {
            stab.update(Some(99), (10, 10 + i * 10), t);
        }

        // Still on original target
        assert_eq!(stab.current_target(), Some(42));
    }

    #[test]
    fn very_low_threshold_allows_quick_switch() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            detection_threshold: 0.01,
            hysteresis_cells: 0,
            drift_allowance: 0.0,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Single frame at distance should be enough
        stab.update(Some(99), (15, 10), t);

        assert_eq!(stab.current_target(), Some(99));
        assert_eq!(stab.switch_count(), 2);
    }

    // ── Edge-case: Decay rate extremes ───────────────────────────────

    #[test]
    fn decay_rate_zero_no_decay() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            decay_rate: 0.0,
            detection_threshold: 100.0, // Very high to prevent immediate switch
            hysteresis_cells: 0,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Build some evidence
        stab.update(Some(99), (20, 10), t);
        stab.update(Some(99), (30, 10), t);

        // Return to original — with 0 decay, candidate stays
        stab.update(Some(42), (10, 10), t);
        stab.update(Some(42), (10, 10), t);

        // Candidate should still have evidence (no decay)
        // We can't directly inspect candidate, but we know the algorithm
        // Just verify it doesn't crash
        assert_eq!(stab.current_target(), Some(42));
    }

    #[test]
    fn decay_rate_one_instant_decay() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            decay_rate: 1.0,
            detection_threshold: 2.0,
            hysteresis_cells: 0,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // Build evidence then return
        stab.update(Some(99), (20, 10), t);
        stab.update(Some(42), (10, 10), t); // decay_rate=1.0 → score*0.0=0 → candidate cleared

        // Continue with new target — should need fresh evidence
        for i in 1..=5 {
            stab.update(Some(99), (10, 10 + i * 5), t);
        }

        // Should switch eventually (fresh evidence not affected by old candidate)
        // Just verify no crash and reasonable behavior
        let target = stab.current_target();
        assert!(target == Some(42) || target == Some(99));
    }

    // ── Edge-case: Zero drift allowance ──────────────────────────────

    #[test]
    fn zero_drift_allowance_fast_accumulation() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            drift_allowance: 0.0,
            detection_threshold: 1.0,
            hysteresis_cells: 0,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (10, 10), t);

        // With k=0, any positive signal accumulates directly
        stab.update(Some(99), (15, 10), t);

        // Should switch quickly since no drift subtracted
        assert_eq!(stab.current_target(), Some(99));
    }

    // ── Edge-case: Target ID boundaries ──────────────────────────────

    #[test]
    fn target_id_zero() {
        let mut stab = stabilizer();
        let t = now();

        let target = stab.update(Some(0), (10, 10), t);
        assert_eq!(target, Some(0));
        assert_eq!(stab.current_target(), Some(0));
    }

    #[test]
    fn target_id_max_u64() {
        let mut stab = stabilizer();
        let t = now();

        // u64::MAX is used internally as sentinel for None, but as a real target ID
        // it should be handled. Note: this tests the sentinel collision edge case.
        let target = stab.update(Some(u64::MAX), (10, 10), t);
        assert_eq!(target, Some(u64::MAX));
    }

    // ── Edge-case: Switch count tracking ─────────────────────────────

    #[test]
    fn switch_count_increments_across_multiple_switches() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            detection_threshold: 0.01,
            hysteresis_cells: 0,
            drift_allowance: 0.0,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(1), (10, 10), t);
        assert_eq!(stab.switch_count(), 1);

        stab.update(Some(2), (30, 10), t);
        assert_eq!(stab.current_target(), Some(2));
        assert_eq!(stab.switch_count(), 2);

        stab.update(Some(3), (60, 10), t);
        assert_eq!(stab.current_target(), Some(3));
        assert_eq!(stab.switch_count(), 3);
    }

    // ── Edge-case: set_config during active tracking ─────────────────

    #[test]
    fn set_config_preserves_state() {
        let mut stab = stabilizer();
        let t = now();

        stab.update(Some(42), (10, 10), t);
        assert_eq!(stab.current_target(), Some(42));

        // Change config while tracking
        stab.set_config(HoverStabilizerConfig {
            detection_threshold: 100.0,
            ..Default::default()
        });

        // Current target should be preserved
        assert_eq!(stab.current_target(), Some(42));
        assert_eq!(stab.config().detection_threshold, 100.0);
    }

    // ── Edge-case: Large hysteresis band ─────────────────────────────

    #[test]
    fn large_hysteresis_requires_big_movement() {
        let mut stab = HoverStabilizer::new(HoverStabilizerConfig {
            hysteresis_cells: 100,
            detection_threshold: 0.01,
            drift_allowance: 0.0,
            ..Default::default()
        });
        let t = now();

        stab.update(Some(42), (100, 100), t);

        // Move 50 cells — within hysteresis band of 100
        stab.update(Some(99), (150, 100), t);
        stab.update(Some(99), (150, 100), t);
        assert_eq!(stab.current_target(), Some(42)); // Still within band

        // Move 200 cells — way past hysteresis
        for i in 1..=5 {
            stab.update(Some(99), (100 + (i * 50), 100), t);
        }
        // Should eventually switch
        assert_eq!(stab.current_target(), Some(99));
    }
}