sugarrush 2026.8.3

A terminal UI for viewing Nightscout CGM (blood glucose sensor) data
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
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
//! Rendering. v1: a single dashboard screen.

use chrono::{Local, TimeZone};
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
    style::{Color, Modifier, Style},
    symbols,
    text::{Line, Span},
    widgets::{Axis, Block, Borders, Chart, Clear, Dataset, GraphType, Paragraph, Tabs, Wrap},
    Frame,
};

use crate::agp;
use crate::app::{App, Field, GraphView, Screen};
use crate::bigfont;
use crate::config::GraphStyle;
use crate::stats;
use crate::units::Units;

/// Format an already-in-display-units value: integer for mg/dL, one decimal for
/// mmol/L (mg/dL never has a fractional part).
fn fmt_disp(units: Units, v: f64) -> String {
    match units {
        Units::Mgdl => format!("{v:.0}"),
        Units::Mmol => format!("{v:.1}"),
    }
}

pub fn draw(f: &mut Frame, app: &App) {
    // The overlay composites over whatever screen is up. It used to be drawn
    // only by the dashboard branch, so `?` on the followers screen set the flag
    // and showed nothing — then ambushed the user on the next dashboard render.
    if app.screen == Screen::Followers {
        draw_followers(f, app);
        if app.show_help {
            draw_help(f, f.area(), app.screen);
        }
        return;
    }
    if app.screen == Screen::Settings {
        draw_settings(f, app);
        if app.show_help {
            draw_help(f, f.area(), app.screen);
        }
        return;
    }
    // A one-line alert banner appears above the header only while alerting.
    let banner = app.alert.is_alerting();
    // On wide terminals, current + stats share one row (side-by-side),
    // reclaiming ~5 rows for the graph. Otherwise they stack.
    let wide = f.area().width >= 90;
    let height = f.area().height;

    // Reflow ladder. The panes are fixed-height, so on a short terminal
    // ratatui satisfies the graph's Min(8) and crushes the rest — which used
    // to mean `current` collapsed to its border and the glucose number was not
    // on screen at all, while the graph (a decoration, next to the number)
    // survived intact. Drop panes deliberately instead, cheapest first, and
    // never the reading.
    let banner_h = u16::from(banner);
    // banner + header(3) + current(8) + graph(8) + footer(1). On a wide
    // terminal stats rides alongside `current` and costs nothing; otherwise it
    // is the first pane to go, then the minimap, then `current`'s own borders.
    let base = banner_h + 20;
    let full = height >= base;
    let stats = wide || height >= base + 5;
    let minimap = app.minimap_enabled && height >= base + if wide { 0 } else { 5 } + 4;
    // Below `full`, `current` gives up its borders and becomes a single line.
    let compact = !full;

    let mut constraints = Vec::new();
    if banner {
        constraints.push(Constraint::Length(1)); // banner
    }
    constraints.push(Constraint::Length(3)); // header
    if compact {
        constraints.push(Constraint::Length(2)); // reading + range bar
    } else if wide {
        constraints.push(Constraint::Length(8)); // current + stats
    } else {
        constraints.push(Constraint::Length(8)); // current
        if stats {
            constraints.push(Constraint::Length(5)); // stats
        }
    }
    constraints.push(Constraint::Min(if compact { 0 } else { 8 })); // graph
    if minimap {
        constraints.push(Constraint::Length(4)); // minimap
    }
    constraints.push(Constraint::Length(1)); // footer

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(f.area());

    let mut i = 0;
    if banner {
        draw_banner(f, chunks[i], app);
        i += 1;
    }
    draw_header(f, chunks[i], app);
    i += 1;
    if compact {
        draw_current_compact(f, chunks[i], app);
        i += 1;
    } else if wide {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
            .split(chunks[i]);
        draw_current(f, cols[0], app);
        draw_stats(f, cols[1], app);
        i += 1;
    } else {
        draw_current(f, chunks[i], app);
        i += 1;
        if stats {
            draw_stats(f, chunks[i], app);
            i += 1;
        }
    }
    draw_graph_pane(f, chunks[i], app);
    i += 1;
    if minimap {
        draw_minimap(f, chunks[i], app);
        i += 1;
    }
    draw_footer(f, chunks[i], app);

    if app.show_help {
        draw_help(f, f.area(), app.screen);
    }
}

/// A centered keybinding cheatsheet, drawn over the dashboard. Dismissed by any
/// key. Reachable with `?` — the discoverable home for every binding, so the
/// footer can shrink on narrow terminals without hiding functionality.
fn draw_help(f: &mut Frame, area: Rect, screen: Screen) {
    // Settings has its own vocabulary, and it is the screen with the most rows
    // of unexplained options — so it needs the overlay more than the dashboard
    // does, and a dashboard cheatsheet there would be wrong on every line.
    let settings_rows = [
        ("↑ / ↓ · j / k", "select a setting"),
        ("← / →", "change the selected setting"),
        ("Enter", "edit text (URL, tokens, timezone, push URL)"),
        ("w", "save to config.toml"),
        ("s / Esc", "back"),
        ("?", "toggle this help"),
        ("q", "quit"),
        ("Ctrl+C", "quit from anywhere"),
    ];
    let dashboard_rows = [
        ("q", "quit"),
        ("?", "toggle this help"),
        ("r", "refresh now"),
        ("u", "toggle mg/dL ↔ mmol/L"),
        ("Tab / ⇧Tab", "switch graph view (3h / 24h / AGP)"),
        ("h / l · ← / →", "pan back / forward"),
        ("H / L · PgUp/Dn", "pan a whole window"),
        ("+ / -", "zoom window (1h–24h)"),
        ("g", "jump to a date"),
        ("[ / ]", "previous / next day"),
        ("End", "jump to the start of the overview"),
        ("f / Home / Esc", "return to live"),
        ("e", "export the clinical window (csv + summary)"),
        ("a", "snooze the audible alarm"),
        ("n", "switch site (multi-site)"),
        ("m", "follow all sites at once"),
        ("s", "open / close settings"),
        ("Ctrl+C", "quit from anywhere"),
        ("drag the overview", "scrub through history (mouse)"),
    ];
    let follower_rows = [
        ("↑ / ↓ · j / k", "select a followed person"),
        ("PgUp / PgDn", "move five people"),
        ("Home / End", "first / last person"),
        ("Enter", "open selected person's dashboard"),
        ("a", "snooze selected person's alarm"),
        ("r", "refresh everyone"),
        ("m / Esc", "back to dashboard"),
        ("s", "open settings"),
        ("?", "toggle this help"),
        ("q / Ctrl+C", "quit"),
    ];
    let rows: &[(&str, &str)] = match screen {
        Screen::Settings => &settings_rows,
        Screen::Followers => &follower_rows,
        Screen::Dashboard => &dashboard_rows,
    };
    // Two columns of key text now; keep the popup wide enough for the longest.
    let key_w = 17usize;
    // Sized from the content, not a guess: the old fixed 56 columns clipped
    // the longest row, and the fixed height dropped the "press any key" line —
    // the overlay never said how to leave it.
    let widest = rows
        .iter()
        .map(|(_, d)| d.chars().count())
        .max()
        .unwrap_or(0);
    let w = ((key_w + widest + 6) as u16).min(area.width.saturating_sub(2));
    // 1 leading blank + rows + 1 blank + 2 footer lines + 2 border rows.
    let h = (rows.len() as u16 + 6).min(area.height.saturating_sub(2));
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let popup = Rect::new(x, y, w, h);

    let mut lines = vec![Line::from("")];
    for (k, d) in rows.iter().copied() {
        lines.push(Line::from(vec![
            Span::styled(
                format!("  {k:<key_w$}"),
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(d),
        ]));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  also: sugarrush watch · export · status   (see --help)",
        Style::default().fg(Color::DarkGray),
    )));
    lines.push(Line::from(Span::styled(
        "  press any key to close",
        Style::default().fg(Color::DarkGray),
    )));

    f.render_widget(Clear, popup);
    f.render_widget(
        Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .title(" keybindings "),
        ),
        popup,
    );
}

fn draw_minimap(f: &mut Frame, area: Rect, app: &App) {
    let hours = app.minimap_span_ms / 3_600_000;
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" {hours}h overview "));
    let inner = block.inner(area);
    f.render_widget(block, area);
    // Record the inner rect so mouse events can map columns back to time.
    app.minimap_rect.set(Some(inner));

    let now = chrono::Utc::now().timestamp_millis();
    let start = now - app.minimap_span_ms;

    if app.minimap_entries.is_empty() {
        // An empty bordered box reads as "nothing happened"; say which it is.
        let msg = format!("  {}", empty_reason(app));
        f.render_widget(
            Paragraph::new(Span::styled(msg, Style::default().fg(Color::DarkGray))),
            inner,
        );
        return;
    }

    let points: Vec<(f64, f64)> = app
        .minimap_entries
        .iter()
        .rev()
        .map(|e| (e.date as f64, app.units.from_mgdl(e.sgv)))
        .collect();
    let (min_y, max_y) = points
        .iter()
        .fold((f64::MAX, f64::MIN), |(lo, hi), (_, y)| {
            (lo.min(*y), hi.max(*y))
        });
    let bounds_y = [min_y, max_y.max(min_y + 1.0)];

    // Bracket the currently-visible window with two vertical rules.
    let vs = (app.view_start.max(start)) as f64;
    let ve = (app.view_end.min(now)) as f64;
    let start_rule = [(vs, bounds_y[0]), (vs, bounds_y[1])];
    let end_rule = [(ve, bounds_y[0]), (ve, bounds_y[1])];

    let datasets = vec![
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Line)
            .style(Style::default().fg(Color::DarkGray))
            .data(&points),
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Line)
            .style(Style::default().fg(app.theme.graph))
            .data(&start_rule),
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Line)
            .style(Style::default().fg(app.theme.graph))
            .data(&end_rule),
    ];

    let chart = Chart::new(datasets)
        .x_axis(Axis::default().bounds([start as f64, now as f64]))
        .y_axis(Axis::default().bounds(bounds_y));
    f.render_widget(chart, inner);
}

fn draw_stats(f: &mut Frame, area: Rect, app: &App) {
    // TIR / mean / GMI are computed over a fixed clinical window (the last
    // `agp_days` days, reusing the AGP history buffer), not the visible graph
    // window — panning/zooming must not change the clinical numbers. The
    // title names the window so it can't be misread as "what's on screen".
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" stats · {}d ", app.agp_days));
    let inner = block.inner(area);
    f.render_widget(block, area);

    let u = app.units;
    // Time-in-range as a stacked zone bar with the in-range % alongside.
    let tir_line = match stats::tir(
        &app.agp_entries,
        app.alerts.urgent_low,
        app.alerts.low,
        app.alerts.high,
        app.alerts.urgent_high,
    ) {
        Some(t) => {
            // Budget the line: the numbers are the point, the bar is what
            // gives. Without this the suffixes fall off the edge of a
            // half-width panel and the reader never learns they existed.
            let width = inner.width as usize;
            let in_range = format!(" {:.0}% in range", t.in_range);
            // Three of the five bands used to have no textual form at all —
            // above-range and very-high were only ever a colour in the bar,
            // which is unreadable to anyone who can't distinguish the two reds
            // or isn't looking at colour at all.
            let mut below = if t.below() > 0.0 {
                if t.very_low > 0.0 {
                    format!(" · {:.0}% below ({:.0}% very low)", t.below(), t.very_low)
                } else {
                    format!(" · {:.0}% below", t.below())
                }
            } else {
                String::new()
            };
            let mut above = if t.above() > 0.0 {
                format!(" · {:.0}% above", t.above())
            } else {
                String::new()
            };
            // Order of sacrifice as the pane narrows: the bar shrinks, then the
            // very-low detail, then above-range, then below-range, then the bar
            // goes. A clipped "· 7%" is worse than no suffix — it reads as a
            // different number. Below outlives above because it is the one that
            // changes what someone does tonight.
            const MIN_BAR: usize = 5;
            let budget =
                |a: &str, b: &str| 6 + in_range.len() + a.len() + b.len() + MIN_BAR > width;
            if budget(&below, &above) && t.very_low > 0.0 {
                below = format!(" · {:.0}% below", t.below());
            }
            if budget(&below, &above) {
                above.clear();
            }
            if budget(&below, &above) {
                below.clear();
            }
            let bar_w = width
                .saturating_sub(6 + in_range.len() + below.len() + above.len())
                .min(40);
            let bar_w = if bar_w < MIN_BAR { 0 } else { bar_w };
            // Cells are allocated to the urgent bands first: a single very-low
            // reading in two weeks rounds to 0% but is exactly what someone
            // scanning this panel needs to see, so give it a cell if it exists.
            let cells = |pct: f64| {
                let n = (pct / 100.0 * bar_w as f64).round() as usize;
                if n == 0 && pct > 0.0 {
                    1
                } else {
                    n
                }
            };
            let (vlo, lo) = (cells(t.very_low), cells(t.low));
            let (vhi, hi) = (cells(t.very_high), cells(t.high));
            let mid = bar_w.saturating_sub(vlo + lo + hi + vhi);
            let mut spans = vec![
                Span::raw("  TIR "),
                Span::styled("".repeat(vlo), Style::default().fg(app.theme.urgent)),
                Span::styled("".repeat(lo), Style::default().fg(app.theme.low)),
                Span::styled("".repeat(mid), Style::default().fg(app.theme.in_range)),
                Span::styled("".repeat(hi), Style::default().fg(app.theme.high)),
                Span::styled("".repeat(vhi), Style::default().fg(app.theme.urgent)),
                Span::styled(in_range, Style::default().fg(app.theme.in_range)),
            ];
            // Time below range is the number that changes treatment; call it
            // out rather than leaving it to be read off the bar.
            if !below.is_empty() {
                spans.push(Span::styled(below, Style::default().fg(app.theme.low)));
            }
            if !above.is_empty() {
                spans.push(Span::styled(above, Style::default().fg(app.theme.high)));
            }
            Line::from(spans)
        }
        None => Line::from("  TIR  —"),
    };

    // Mean + estimated A1c over the clinical window; the sparkline stays on
    // recent readings (it's a trend glance, not a statistic).
    let avg_line = match stats::mean_mgdl(&app.agp_entries) {
        Some(mean) => {
            let head = format!("  avg  {} {}  ", u.format(mean), u.label());
            let mut gmi = format!("  ·  GMI {:.1}%", stats::gmi(mean));
            let mut cv = stats::cv_pct(&app.agp_entries);
            let mut cv_text = cv.map(|c| format!("  ·  CV {c:.0}%")).unwrap_or_default();
            // Same sacrifice order on this line: tighten the separators, then
            // drop CV whole. GMI is the number people quote, so it stays.
            let width = inner.width as usize;
            if head.len() + gmi.len() + cv_text.len() > width {
                gmi = gmi.replace("  ·  ", " · ");
                cv_text = cv_text.replace("  ·  ", " · ");
            }
            if head.len() + gmi.len() + cv_text.len() > width {
                cv = None;
                cv_text.clear();
            }
            // The sparkline is a trend glance, not a statistic — it yields the
            // width to GMI and CV rather than pushing them off the line.
            let room =
                (inner.width as usize).saturating_sub(head.len() + gmi.len() + cv_text.len());
            let mut spark: Vec<f64> = app
                .entries
                .iter()
                .take(room.min(16))
                .map(|e| e.sgv)
                .collect();
            spark.reverse();
            let mut spans = vec![Span::raw(head)];
            if spark.len() >= 4 {
                spans.push(Span::styled(
                    sparkline_str(&spark),
                    Style::default().fg(app.theme.graph),
                ));
            }
            spans.push(Span::raw(gmi));
            if let Some(c) = cv {
                // Variability: at the same average, a high CV means more hypos.
                // The consensus target is ≤ 36%, so colour the breach.
                spans.push(Span::styled(
                    cv_text,
                    if c > 36.0 {
                        Style::default().fg(app.theme.high)
                    } else {
                        Style::default()
                    },
                ));
            }
            Line::from(spans)
        }
        None => Line::from("  avg  —"),
    };

    // Device / uploader status. IOB/COB are the clinically actionable numbers,
    // so give them foreground weight; the device/battery/uploader stay dim.
    let now = chrono::Utc::now().timestamp_millis();
    let strong = Style::default().add_modifier(Modifier::BOLD);
    let dim = Style::default().fg(Color::DarkGray);
    let mut spans: Vec<Span> = Vec::new();
    if let Some(iob) = app.device.iob {
        spans.push(Span::styled(format!("  IOB {iob:.1}U"), strong));
    }
    if let Some(cob) = app.device.cob {
        spans.push(Span::styled(format!("   COB {cob:.0}g"), strong));
    }
    let mut rest = Vec::new();
    if let Some(name) = &app.device.device {
        rest.push(name.clone());
    }
    if let Some(b) = app.device.battery {
        rest.push(format!("battery {b}%"));
    }
    if let Some(start) = app.sensor_start_ms {
        rest.push(format!("sensor {}", fmt_age(now - start)));
    }
    if let Some(last) = app.device.last_ms {
        rest.push(format!("uploader {} ago", fmt_age(now - last)));
    }
    if !rest.is_empty() {
        let prefix = if spans.is_empty() { "  " } else { "   ·   " };
        spans.push(Span::styled(
            format!("{prefix}{}", rest.join("   ·   ")),
            dim,
        ));
    }
    let dev_line = if spans.is_empty() {
        Line::from(Span::styled("  device  —", dim))
    } else {
        Line::from(spans)
    };

    f.render_widget(Paragraph::new(vec![tir_line, avg_line, dev_line]), inner);
}

/// An 8-level block sparkline over the values (min→max normalized).
fn sparkline_str(values: &[f64]) -> String {
    const BARS: [char; 8] = ['', '', '', '', '', '', '', ''];
    if values.is_empty() {
        return String::new();
    }
    let (min, max) = values
        .iter()
        .fold((f64::MAX, f64::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v)));
    let range = (max - min).max(1.0);
    values
        .iter()
        .map(|&v| {
            let level = ((v - min) / range * (BARS.len() - 1) as f64).round() as usize;
            BARS[level.min(BARS.len() - 1)]
        })
        .collect()
}

/// Format a positive duration in ms as a compact age like `6d 4h` or `12m`.
fn fmt_age(ms: i64) -> String {
    let mins = ms.max(0) / 60_000;
    let days = mins / 1440;
    let hours = (mins % 1440) / 60;
    let m = mins % 60;
    if days > 0 {
        format!("{days}d {hours}h")
    } else if hours > 0 {
        format!("{hours}h {m}m")
    } else {
        format!("{m}m")
    }
}

fn field_controls(field: Field) -> &'static str {
    match field {
        Field::SiteName
        | Field::SiteUrl
        | Field::SiteToken
        | Field::SiteWriteToken
        | Field::SiteTimezone
        | Field::PushUrl => "Enter to edit",
        Field::AddSite | Field::RemoveSite | Field::TestAlarm => "Enter to run",
        _ => "← / → to change",
    }
}

fn field_detail(field: Field) -> &'static str {
    match field {
        Field::SiteName => "The name used in follower rows, notifications, logs, and persisted alarm episodes. It must be unique.",
        Field::SiteUrl => "The Nightscout base URL for the selected person. HTTPS keeps the read-only token and readings encrypted in transit.",
        Field::SiteToken => "A dedicated read-only Nightscout token. It is masked here and stored in the owner-only config file.",
        Field::SiteWriteToken => "Optional separate CarePortal token. Setting it crosses a security boundary: confirmed treatment commands can modify this person's Nightscout data. It is verified before every write.",
        Field::SiteTimezone => "The followed person's IANA timezone (for example Europe/Amsterdam), used for AGP patterns and clinical exports. Empty means this computer's local time.",
        Field::TestSite => "Fetch this Nightscout site and require a reading from the last hour. New or edited credentials cannot be saved until this passes.",
        Field::AddSite => "Create another followed person without copying the current person's credential. Fill in its name, URL, and token next.",
        Field::RemoveSite => "Remove the selected site from the saved list. At least one site is always retained.",
        Field::SiteAlerts => "Use the global alert profile, or make a complete threshold and delivery profile for only this person.",
        Field::Units => "How glucose values and editable thresholds are displayed. Internally, safety comparisons remain in mg/dL.",
        Field::Refresh => "How often the dashboard asks Nightscout for new data. The watcher uses its own conservative polling policy.",
        Field::Desktop => "Send a desktop notification when an alert episode starts or a predictive warning becomes due.",
        Field::Osd => "Also show urgent alerts on Omarchy's on-screen display, which is drawn above fullscreen windows and is not suppressed by Do Not Disturb. Ignored on other desktops.",
        Field::NotifyContent => "Choose whether notifications include the reading and state, or stay generic for shared and locked screens.",
        Field::Sound => "Play the looping audible alarm for urgent and stale states. Use the test below to verify the machine can actually sound.",
        Field::TestAlarm => "Play the audible half of the alarm self-test now. Run `sugarrush watch --test` for every delivery channel.",
        Field::Snooze => "How long acknowledgement silences the active alarm before it can sound again.",
        Field::QuietHours => "Schedule a daily period when alarms are muted. The urgent-low override below can remain armed.",
        Field::QuietStart | Field::QuietEnd => "Start or end of the daily quiet window, adjusted in 30-minute steps.",
        Field::QuietUrgentLow => "Keep urgent-low audio active during quiet hours as a safety override.",
        Field::Escalate => "Send the configured push webhook when an urgent episode remains unacknowledged for this long.",
        Field::PushAlerts => "Enable or disable the configured phone/webhook destination without discarding its URL.",
        Field::PushUrl => "A phone/webhook destination. It is hidden because private topics and tokens are often embedded in the URL; enter a replacement, or `off` to clear it.",
        Field::PredictHorizon => "Warn when a forecast crosses low or high within this many minutes. Zero disables predictive alerts.",
        Field::UrgentLow => "At or below this value, classify the reading as urgent low and use the urgent alarm path.",
        Field::Low => "Below this value, classify the reading as low after applying hysteresis on recovery.",
        Field::High => "Above this value, classify the reading as high after applying hysteresis on recovery.",
        Field::UrgentHigh => "At or above this value, classify the reading as urgent high and use the urgent alarm path.",
        Field::Stale => "Treat the data as a sensor gap when the newest reading is older than this many minutes.",
        Field::SensorDays => {
            "How long your sensor is expected to last, so its age reads as time remaining. 0 turns that off."
        }
        Field::GraphStyle => "Draw readings as a connected line, small dots, or larger blocks.",
        Field::AgpDays => "The fixed clinical window used by the AGP, time-in-range statistics, and default export.",
        Field::CacheEnabled => "Opt in to an owner-only local reading cache for instant startup and outage context. Turning it off deletes every cached reading.",
        Field::CacheDays => "Maximum local cache retention. Old readings are removed on every successful update; cached data is never presented as a live fetch.",
        Field::MinimapEnabled => "Show the overview strip and enable mouse click/drag navigation through history.",
        Field::MinimapSpan => "How much history the overview strip covers, from 6 to 72 hours.",
        Field::BarArrow => "Print the trend arrow in the status-bar reading (sugarrush status, waybar, the Quickshell pill).",
        Field::BarDelta => "Print the change since the previous reading in the status-bar reading.",
        Field::BarUnits => "Send the unit label to bars that render one. Only the JSON output carries it; the plain, polybar, tmux and i3blocks lines never have.",
        Field::BarSparkline => "Send the last hour to bars that draw a trace. JSON output only; no text format draws one.",
        Field::ThemeLow => "Colour used for low readings and low-state text.",
        Field::ThemeInRange => "Colour used for in-range readings and target-band cues.",
        Field::ThemeHigh => "Colour used for high readings and high-state text.",
        Field::ThemeUrgent => "Colour used for urgent lows, urgent highs, and safety-critical banners.",
        Field::ThemePrediction => "Colour used for the forecast centre and uncertainty cone.",
        Field::ThemeGraph => "Primary graph, AGP median, percentile fan, and sparkline colour.",
        Field::Colorblind => "Switch the full palette to colourblind-safe colours with distinct alert roles.",
    }
}

fn draw_settings(f: &mut Frame, app: &App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // header
            Constraint::Min(5),    // fields
            Constraint::Length(1), // footer
        ])
        .split(f.area());

    // Edits apply live but only `w` persists them, so an unsaved change has to
    // be visible — otherwise quitting silently reverts everything.
    let mut title = vec![Span::styled(
        " settings ",
        Style::default()
            .fg(Color::Magenta)
            .add_modifier(Modifier::BOLD),
    )];
    if app.settings_dirty {
        title.push(Span::styled(
            "· unsaved changes (w to save) ",
            Style::default().fg(Color::Yellow),
        ));
    }
    let header = Paragraph::new(Line::from(title)).block(Block::default().borders(Borders::ALL));
    f.render_widget(header, chunks[0]);

    // Build display rows: a dim section header whenever the group changes,
    // then each field. Headers aren't selectable — navigation stays over
    // Field::ALL, so `settings_sel` still indexes fields directly.
    enum Row {
        Header(&'static str),
        Field(usize, Field),
    }
    let mut display: Vec<Row> = Vec::new();
    let mut last_group = "";
    for (i, &field) in Field::ALL.iter().enumerate() {
        let g = field.group();
        if g != last_group {
            display.push(Row::Header(g));
            last_group = g;
        }
        display.push(Row::Field(i, field));
    }

    let split = chunks[1].width >= 80;
    let panes = Layout::default()
        .direction(Direction::Horizontal)
        .constraints(if split {
            [Constraint::Percentage(55), Constraint::Percentage(45)]
        } else {
            [Constraint::Percentage(100), Constraint::Percentage(0)]
        })
        .split(chunks[1]);
    let list_area = panes[0];
    let height = list_area.height.saturating_sub(2).max(1) as usize;

    // Scroll so the selected field (and ideally its header) stays visible.
    let sel_display = display
        .iter()
        .position(|r| matches!(r, Row::Field(i, _) if *i == app.settings_sel))
        .unwrap_or(0);
    let offset = if sel_display < height {
        0
    } else {
        (sel_display + 1 - height).min(display.len().saturating_sub(height))
    };
    let above = offset > 0;
    let below = offset + height < display.len();
    let list_title = match (above, below) {
        (true, true) => " ↑ more · fields · ↓ more ",
        (true, false) => " ↑ more · fields ",
        (false, true) => " fields · ↓ more ",
        (false, false) => " fields ",
    };
    let list_block = Block::default().borders(Borders::ALL).title(list_title);
    let inner = list_block.inner(list_area);
    f.render_widget(list_block, list_area);

    let lines: Vec<Line> = display
        .iter()
        .skip(offset)
        .take(height)
        .map(|row| match row {
            Row::Header(name) => Line::from(Span::styled(
                format!(" {name}"),
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )),
            Row::Field(i, field) => {
                let selected = *i == app.settings_sel;
                let marker = if selected { "" } else { "   " };
                let style = if selected {
                    Style::default()
                        .fg(Color::Black)
                        .bg(Color::Cyan)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                };
                let text = format!("{marker}{:<26}{}", field.label(), app.field_value(*field));
                // Pad the selected row to full width so its highlight fills the
                // line instead of ending ragged mid-text.
                let text = if selected {
                    format!("{text:<width$}", width = inner.width as usize)
                } else {
                    text
                };
                Line::from(Span::styled(text, style))
            }
        })
        .collect();
    f.render_widget(Paragraph::new(lines), inner);

    if split {
        let field = app.selected_field();
        let detail = vec![
            Line::from(vec![
                Span::styled("Current  ", Style::default().fg(Color::DarkGray)),
                Span::styled(
                    app.field_value(field),
                    Style::default().add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::default(),
            Line::from(field_detail(field)),
            Line::default(),
            Line::from(Span::styled(
                field_controls(field),
                Style::default().fg(Color::Cyan),
            )),
        ];
        f.render_widget(
            Paragraph::new(detail).wrap(Wrap { trim: true }).block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(format!(" {} ", field.label())),
            ),
            panes[1],
        );
    }

    // Where the real terminal cursor goes, set after the footer is rendered.
    // A screen reader's caret tracking and a braille display's cursor routing
    // both follow the *terminal* cursor; nothing here ever set one, so someone
    // editing the site URL — or a token, which renders as bullets — had no way
    // to know where the insertion point was.
    let mut cursor: Option<u16> = None;
    let footer = match (&app.field_edit, &app.status) {
        // An open editor replaces the hint line with the prompt. The token is
        // masked as it's typed — a typo is fixed by retyping, not by reading it
        // back off a screen that's likely being shared.
        (Some(edit), _) => {
            let shown = if edit.masked {
                "".repeat(edit.buffer.chars().count())
            } else {
                edit.buffer.clone()
            };
            let prompt = format!(" {}: ", edit.field.label().to_lowercase());
            cursor = Some((prompt.chars().count() + shown.chars().count()) as u16);
            Line::from(vec![
                Span::styled(prompt, Style::default().fg(Color::Cyan)),
                Span::styled(shown, Style::default().add_modifier(Modifier::BOLD)),
                Span::raw(" · enter confirm · esc cancel"),
            ])
        }
        (None, Some(msg)) => Line::from(Span::styled(
            format!(" {msg} "),
            Style::default().fg(Color::Green),
        )),
        (None, None) => Line::from(Span::raw(
            " ↑/↓ select · ←/→ change · enter edit/action · w save · s/esc back · ? help · q quit ",
        )),
    };
    f.render_widget(Paragraph::new(footer), chunks[2]);
    if let Some(x) = cursor {
        if x < chunks[2].width {
            f.set_cursor_position((chunks[2].x + x, chunks[2].y));
        }
    }
}

/// Every followed site at once: one row each, worst first.
///
/// Deliberately a list of rows rather than several graphs — a caregiver checks
/// this to answer "is anyone in trouble", and graphs make that a slower
/// question, not a faster one.
fn draw_followers(f: &mut Frame, app: &App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // header
            Constraint::Min(3),    // rows
            Constraint::Length(1), // footer
        ])
        .split(f.area());

    // The header answers the only question this screen exists for — is anyone
    // in trouble — without making you read the rows.
    let mut title = vec![Span::styled(
        format!(" following {} sites ", app.sites.len()),
        Style::default()
            .fg(Color::Magenta)
            .add_modifier(Modifier::BOLD),
    )];
    if let Some(worst) = crate::follow::worst(&app.followers) {
        let (text, color) = if worst.alert.is_alerting() {
            (
                format!("· {} needs attention: {} ", worst.name, worst.alert.label()),
                app.theme.urgent,
            )
        } else {
            ("· all in range ".to_string(), app.theme.in_range)
        };
        title.push(Span::styled(text, Style::default().fg(color)));
    }
    let header = Paragraph::new(Line::from(title)).block(Block::default().borders(Borders::ALL));
    f.render_widget(header, chunks[0]);

    let now = chrono::Utc::now().timestamp_millis();
    let available = chunks[1].height.saturating_sub(2) as usize;
    let data_rows = available.saturating_sub(1);
    let max_start = app.followers.len().saturating_sub(data_rows.max(1));
    let start = app.follower_scroll.min(max_start);
    let end = (start + data_rows).min(app.followers.len());
    let rows_title = match (start > 0, end < app.followers.len()) {
        (true, true) => " ↑ more · people · ↓ more ",
        (true, false) => " ↑ more · people ",
        (false, true) => " people · ↓ more ",
        (false, false) => " people ",
    };
    let block = Block::default().borders(Borders::ALL).title(rows_title);
    let inner = block.inner(chunks[1]);
    f.render_widget(block, chunks[1]);

    let lines: Vec<Line> = if app.followers.is_empty() {
        vec![Line::from(format!("  {}", empty_reason(app)))]
    } else {
        let wide = inner.width >= 82;
        let mut rows: Vec<Line> = Vec::with_capacity(app.followers.len() + 1);
        rows.push(Line::from(Span::styled(
            if wide {
                format!(
                    "  {:<12} {:>9} {:>7}  {:<18} {:<10} {}",
                    "PERSON",
                    app.units.label(),
                    "DELTA",
                    "STATE",
                    "AGE",
                    "LAST HOUR"
                )
            } else {
                format!(
                    "  {:<10} {:>7} {:<13} {}",
                    "PERSON",
                    app.units.label(),
                    "STATE",
                    "TREND"
                )
            },
            Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        )));
        rows.extend(app.followers[start..end].iter().map(|s| {
            let color = match s.alert {
                crate::alert::Alert::UrgentLow | crate::alert::Alert::UrgentHigh => {
                    app.theme.urgent
                }
                crate::alert::Alert::Low => app.theme.low,
                crate::alert::Alert::High => app.theme.high,
                crate::alert::Alert::Stale => Color::DarkGray,
                crate::alert::Alert::InRange => app.theme.in_range,
            };
            // The age is what tells you whether to trust the value, so it
            // sits next to it rather than at the end of the row.
            let age = match s.age_min(now) {
                Some(m) => format!("{m}m ago"),
                None if s.error.is_some() => "unavailable".into(),
                None => "no data".into(),
            };
            let spark = sparkline_str(&s.history);
            let mut spans = vec![
                // A solid severity rail makes the row's state visible even
                // when the text columns no longer line up on a narrow TTY.
                Span::styled("", Style::default().fg(color)),
                Span::styled(
                    format!(
                        "{:<width$}",
                        fit_cell(&s.name, if wide { 12 } else { 10 }),
                        width = if wide { 12 } else { 10 }
                    ),
                    Style::default().add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    format!(
                        "{:>width$} {} ",
                        s.value(app.units),
                        s.arrow(),
                        width = if wide { 6 } else { 4 }
                    ),
                    Style::default().fg(color).add_modifier(Modifier::BOLD),
                ),
            ];
            if wide {
                spans.push(Span::raw(format!("{:>7}  ", s.delta_text(app.units))));
                spans.push(Span::styled(
                    format!("{:<18}", s.alert.label()),
                    Style::default().fg(color),
                ));
                spans.push(Span::styled(
                    format!("{age:<10}"),
                    Style::default().fg(Color::DarkGray),
                ));
            } else {
                spans.push(Span::styled(
                    format!("{:<13}", s.alert.label()),
                    Style::default().fg(color),
                ));
            }
            spans.push(Span::styled(spark, Style::default().fg(app.theme.graph)));
            let selected = app.selected_follower() == Some(s.name.as_str());
            Line::from(spans).style(if selected {
                Style::default().bg(Color::DarkGray)
            } else {
                Style::default()
            })
        }));
        rows
    };
    f.render_widget(Paragraph::new(lines), inner);

    let footer = match &app.status {
        Some(msg) => Span::styled(format!(" {msg} "), Style::default().fg(Color::Green)),
        None => {
            Span::raw(" ↑/↓ select · enter open · a snooze person · m/esc back · ? help · q quit ")
        }
    };
    f.render_widget(Paragraph::new(Line::from(footer)), chunks[2]);
}

fn fit_cell(text: &str, width: usize) -> String {
    let len = text.chars().count();
    if len <= width {
        return text.to_string();
    }
    text.chars()
        .take(width.saturating_sub(1))
        .chain([''])
        .collect()
}

fn draw_banner(f: &mut Frame, area: Rect, app: &App) {
    use crate::alert::Alert;
    // Route the banner background through the theme so the colourblind preset
    // (and any custom palette) recolours the most safety-critical widget.
    let color = match app.alert {
        Alert::UrgentLow | Alert::UrgentHigh => app.theme.urgent,
        Alert::Low => app.theme.low,
        Alert::High => app.theme.high,
        Alert::Stale => Color::Magenta,
        Alert::InRange => app.theme.in_range,
    };
    let line = Line::from(Span::styled(
        format!("{} ", app.alert.label()),
        Style::default()
            .fg(Color::Black)
            .bg(color)
            .add_modifier(Modifier::BOLD),
    ));
    f.render_widget(
        Paragraph::new(line)
            .style(Style::default().bg(color))
            .alignment(Alignment::Center),
        area,
    );
}

/// Why a panel has nothing to draw, phrased the same way everywhere.
///
/// Three panels used to answer one failure three different ways — "no data in
/// this window…", "no readings in this window…" and "loading overview…" — and
/// on a rejected token the last was simply untrue: nothing was loading and
/// nothing ever would.
fn empty_reason(app: &App) -> &'static str {
    if app.fetch_paused() {
        "not loading — see the error below"
    } else if !app.online() {
        "no readings — can't reach Nightscout"
    } else if app.last_ok_ms().is_none() {
        "loading…"
    } else {
        "no readings in this window"
    }
}

fn draw_header(f: &mut Frame, area: Rect, app: &App) {
    // The dot answers "is the data current?"; the word answers "which window
    // am I looking at?". They used to be one span, so a green ● sat next to a
    // red authentication error and read as "the connection is live" — the
    // opposite of the truth. `live`/`history` is a view mode and says nothing
    // about the network.
    let (dot, dot_color) = if !app.online() {
        ("", app.theme.urgent)
    } else if app.alert == crate::alert::Alert::Stale {
        ("", app.theme.high)
    } else {
        ("", app.theme.in_range)
    };
    let mode = if app.view.is_live() {
        Span::styled("live ", Style::default().fg(Color::DarkGray))
    } else {
        Span::styled("history ", Style::default().fg(Color::Yellow))
    };
    let mut spans = vec![
        Span::styled(
            " sugarrush ",
            Style::default()
                .fg(Color::Magenta)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(format!(
            "· {} · {} ",
            app.units.label(),
            app.view.span.label()
        )),
        Span::styled(format!(" {dot} "), Style::default().fg(dot_color)),
        mode,
    ];
    if app.sites.len() > 1 {
        spans.push(Span::styled(
            format!(" [{}] ", app.active_site().name),
            Style::default().fg(Color::Blue),
        ));
    }
    // "Is my safety net armed?" — always answered, in the header, where it
    // survives every error state. It used to be four separate silences with no
    // on-screen evidence: quiet hours, a snooze, a stopped watcher, and an
    // alarm with nothing switched on to announce with.
    let armed = app.armed_state(chrono::Utc::now().timestamp_millis());
    let mut chip = Style::default().fg(if armed.is_suppressed() {
        app.theme.high
    } else {
        app.theme.in_range
    });
    if matches!(
        armed,
        crate::app::Armed::Off | crate::app::Armed::WatcherStopped
    ) {
        chip = Style::default()
            .fg(app.theme.urgent)
            .add_modifier(Modifier::BOLD);
    }
    spans.push(Span::styled(armed.label(), chip));
    // Escalation with no channel is a setting that reads as armed and does
    // nothing at all; it rides alongside rather than replacing the answer.
    if app.alerts.escalate_minutes > 0
        && !(app.alerts.push_url.is_some() && app.alerts.push_enabled)
    {
        spans.push(Span::styled(
            " ⚠ escalation inactive ",
            Style::default().fg(app.theme.high),
        ));
    }
    if !app.online() {
        let age = app
            .last_ok_ms()
            .map(|t| {
                format!(
                    " (last {} ago)",
                    fmt_age(chrono::Utc::now().timestamp_millis() - t)
                )
            })
            .unwrap_or_default();
        // Show the actual cause (auth vs unreachable) rather than a blanket
        // "offline", so a bad token doesn't send the user to debug the network.
        let msg = app.last_error().unwrap_or("can't reach Nightscout");
        spans.push(Span::styled(
            format!("{msg}{age} "),
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        ));
    }
    // Standing reminder in the daily-use surface (it's disclaimed in the README
    // and `about`, but a user who only ever runs the TUI should see it too).
    spans.push(Span::styled(
        " · not a medical device",
        Style::default().fg(Color::DarkGray),
    ));
    let title = Line::from(spans);
    let p = Paragraph::new(title).block(Block::default().borders(Borders::ALL));
    f.render_widget(p, area);
}

/// Borderless two-row readout for terminals too short to afford the `current`
/// pane: the value, arrow, range label, delta and age on one line, the range
/// bar under it.
///
/// A tiling window manager, a phone SSH client, or a terminal at 200% zoom all
/// land here. The rule is that the number is the last thing to go.
fn draw_current_compact(f: &mut Frame, area: Rect, app: &App) {
    let Some(e) = app.latest() else {
        f.render_widget(Paragraph::new(" no data in this window…"), area);
        return;
    };
    let value = app.units.format(e.sgv);
    let color = color_for(e.sgv, app);
    let range = crate::alert::from_value(e.sgv, &app.alerts).label();
    let delta = app
        .delta_mgdl()
        .map(|d| app.units.format_delta(d))
        .unwrap_or_else(|| "--".into());

    let mut spans = vec![
        Span::styled(
            format!(" {value} {} ", e.arrow()),
            Style::default().fg(color).add_modifier(Modifier::BOLD),
        ),
        Span::styled(range.to_string(), Style::default().fg(color)),
    ];
    // The unit and the age only earn their place if the line has room for
    // them — the value, the arrow and the state never drop.
    let rest = format!(
        " · {} · Δ {delta} · {}",
        app.units.label(),
        fmt_time(e.date)
    );
    let used: usize = spans.iter().map(|s| s.content.chars().count()).sum();
    if used + rest.chars().count() <= area.width as usize {
        spans.push(Span::styled(rest, Style::default().fg(Color::DarkGray)));
    }

    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(0)])
        .split(area);
    f.render_widget(Paragraph::new(Line::from(spans)), rows[0]);
    if rows[1].height > 0 {
        f.render_widget(
            Paragraph::new(range_bar(app, e.sgv, rows[1].width)),
            rows[1],
        );
    }
}

fn draw_current(f: &mut Frame, area: Rect, app: &App) {
    let block = Block::default().borders(Borders::ALL).title(" current ");
    let inner = block.inner(area);
    f.render_widget(block, area);

    let Some(e) = app.latest() else {
        f.render_widget(Paragraph::new(format!("  {}", empty_reason(app))), inner);
        return;
    };

    // Reserve a bottom row for the range bar when there's height to spare.
    let (content, bar_area) = if inner.height >= 6 {
        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(4), Constraint::Length(1)])
            .split(inner);
        (rows[0], Some(rows[1]))
    } else {
        (inner, None)
    };

    let value = app.units.format(e.sgv);
    let color = color_for(e.sgv, app);
    let info = current_info(app, e);
    let big_w = bigfont::width(&value);

    // Big number when there's room; compact single line otherwise.
    if content.height as usize >= bigfont::ROWS && content.width >= big_w + 24 {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(big_w + 3), Constraint::Min(0)])
            .split(content);
        let big: Vec<Line> = bigfont::render(&value)
            .into_iter()
            .map(|l| {
                Line::from(Span::styled(
                    format!(" {l}"),
                    Style::default().fg(color).add_modifier(Modifier::BOLD),
                ))
            })
            .collect();
        f.render_widget(Paragraph::new(big), cols[0]);
        f.render_widget(Paragraph::new(info), cols[1]);
    } else {
        // The range label rides on the headline rather than sitting on its own
        // line: on a short pane the lines below get clipped, and that label is
        // the only reading of the state that doesn't depend on seeing colour.
        let range = crate::alert::from_value(e.sgv, &app.alerts).label();
        let mut lines = vec![Line::from(vec![
            Span::styled(
                format!("  {}  {}", value, e.arrow()),
                Style::default().fg(color).add_modifier(Modifier::BOLD),
            ),
            Span::styled(format!("  {range}"), Style::default().fg(color)),
        ])];
        // Drop the value line and the standalone range line — both are above.
        lines.extend(info.into_iter().skip(2));
        f.render_widget(Paragraph::new(lines), content);
    }

    if let Some(ba) = bar_area {
        f.render_widget(Paragraph::new(range_bar(app, e.sgv, ba.width)), ba);
    }
}

/// A one-row zoned range bar: `low ━━━●━━━ high` (display units), coloured by
/// zone with a marker at the current value.
fn range_bar<'a>(app: &App, sgv: f64, width: u16) -> Line<'a> {
    let u = app.units;
    let lo = u.from_mgdl(app.alerts.urgent_low);
    let hi = u.from_mgdl(app.alerts.urgent_high);
    let lo_s = fmt_disp(u, lo);
    let hi_s = fmt_disp(u, hi);
    // ` <lo> ` + bar + ` <hi>`
    let used = lo_s.len() + hi_s.len() + 3;
    let cells = (width as usize).saturating_sub(used);
    if cells < 6 {
        return Line::from("");
    }
    let span = (hi - lo).max(0.1);
    let span_mgdl = (app.alerts.urgent_high - app.alerts.urgent_low).max(0.1);
    let cur = u.from_mgdl(sgv);
    let marker = (((cur - lo) / span) * (cells as f64 - 1.0)).round();
    let marker = marker.clamp(0.0, cells as f64 - 1.0) as usize;

    let mut spans = vec![Span::styled(
        format!(" {lo_s} "),
        Style::default().fg(Color::DarkGray),
    )];
    for i in 0..cells {
        if i == marker {
            spans.push(Span::styled(
                "",
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ));
            continue;
        }
        // The bar spans urgent-low → urgent-high. Interpolate in mg/dL and
        // colour each cell exactly as a reading of that value would be
        // coloured, so the bar can never disagree with the number above it.
        let v = app.alerts.urgent_low + (i as f64 / (cells as f64 - 1.0)) * span_mgdl;
        spans.push(Span::styled("", Style::default().fg(color_for(v, app))));
    }
    spans.push(Span::styled(
        format!(" {hi_s}"),
        Style::default().fg(Color::DarkGray),
    ));
    Line::from(spans)
}

/// The secondary info lines beside/below the current value: unit + arrow,
/// delta, forecast ETA, and the timestamp.
fn current_info<'a>(app: &App, e: &crate::nightscout::Entry) -> Vec<Line<'a>> {
    let delta = app
        .delta_mgdl()
        .map(|d| app.units.format_delta(d))
        .unwrap_or_else(|| "--".into());
    let stamp = fmt_time(e.date);
    let when = if app.view.is_live() {
        format!("as of {stamp}")
    } else {
        format!("window end · {stamp}")
    };

    // Textual range label — legible without relying on color.
    let range = crate::alert::from_value(e.sgv, &app.alerts).label();
    let mut lines = vec![
        // Includes the value as plain text so the reading is readable when the
        // big-number layout draws it as block glyphs (screen readers, tmux
        // copy, braille). The compact layout skips this line — it shows the
        // value itself already.
        Line::from(Span::styled(
            format!(
                " {} {}  {}",
                app.units.format(e.sgv),
                app.units.label(),
                e.arrow()
            ),
            Style::default().add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::styled(
            format!(" {range}"),
            Style::default().fg(color_for(e.sgv, app)),
        )),
        Line::from(format!(" Δ {} {}", delta, app.units.label())),
    ];
    if let Some((rising, mins)) = app.prediction_eta(chrono::Utc::now().timestamp_millis()) {
        let (arrow, word, c) = if rising {
            ("", "high", app.theme.high)
        } else {
            ("", "low", app.theme.low)
        };
        lines.push(Line::from(Span::styled(
            format!(" {arrow} {word} in ~{mins} min"),
            Style::default().fg(c),
        )));
    }
    lines.push(Line::from(Span::styled(
        format!(" {when}"),
        Style::default().fg(Color::DarkGray),
    )));
    lines
}

/// The graph pane: a tab bar to pick the view, then the chosen chart below it.
fn draw_graph_pane(f: &mut Frame, area: Rect, app: &App) {
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(3)])
        .split(area);
    draw_graph_tabs(f, rows[0], app);
    match app.graph_view {
        GraphView::Agp => draw_agp(f, rows[1], app),
        _ => draw_graph(f, rows[1], app),
    }
}

/// The 3h / 24h / AGP selector above the graph.
fn draw_graph_tabs(f: &mut Frame, area: Rect, app: &App) {
    let titles: Vec<Line> = GraphView::ALL
        .iter()
        .map(|v| Line::from(v.label()))
        .collect();
    let tabs = Tabs::new(titles)
        .select(app.graph_view.index())
        .style(Style::default().fg(Color::DarkGray))
        .highlight_style(
            Style::default()
                .fg(app.theme.graph)
                .add_modifier(Modifier::BOLD),
        )
        .divider(symbols::DOT);
    f.render_widget(tabs, area);
}

/// Ambulatory Glucose Profile: readings from the last N days folded onto one
/// 24-hour clock, drawn as a percentile fan (median + 25/75 + 5/95 bands).
fn draw_agp(f: &mut Frame, area: Rect, app: &App) {
    let timezone = app
        .active_site()
        .timezone
        .as_deref()
        .and_then(|name| name.parse::<chrono_tz::Tz>().ok());
    let bands = agp::profile_in(&app.agp_entries, timezone);
    // Reading a pattern off a percentile fan is a skill; name the worst one in
    // the title so it doesn't depend on having that skill. The rest are in the
    // exported report, where there's room for all of them.
    let headline = agp::insights(&bands, app.alerts.low, app.alerts.high)
        .first()
        .map(|i| format!("{} · ", i.text(app.units)))
        .unwrap_or_default();
    // The legend used to be *replaced* by the headline, so the key to reading
    // the chart disappeared exactly when the chart had something to say. Both
    // now, headline first — it drops off a narrow title before the legend does,
    // and it is the legend that makes the fan interpretable at all.
    let title = format!(
        " AGP · last {}d · target {}{} {} · {}median + IQR + 5/95 ",
        app.agp_days,
        fmt_disp(app.units, app.units.from_mgdl(app.alerts.low)),
        fmt_disp(app.units, app.units.from_mgdl(app.alerts.high)),
        app.units.label(),
        headline,
    );
    let block = Block::default().borders(Borders::ALL).title(title);

    if bands.is_empty() {
        f.render_widget(
            Paragraph::new("  gathering days of history…").block(block),
            area,
        );
        return;
    }

    let conv = |mgdl: f64| app.units.from_mgdl(mgdl);
    // Median line (the only line drawn; the fan is a background tint).
    let p50: Vec<(f64, f64)> = bands
        .iter()
        .map(|b| (b.minute as f64, conv(b.p50)))
        .collect();

    let low_y = conv(app.alerts.low);
    let high_y = conv(app.alerts.high);
    let (min_y, max_y) = bands.iter().fold((f64::MAX, f64::MIN), |(lo, hi), b| {
        (lo.min(conv(b.p05)), hi.max(conv(b.p95)))
    });
    let (min_y, max_y) = (min_y.min(low_y), max_y.max(high_y));
    let pad = ((max_y - min_y) * 0.1).max(conv(10.0));
    let bounds_y = [min_y - pad, max_y + pad];
    let bounds_x = [0.0, 1440.0];

    let low_rail = [(0.0, low_y), (1440.0, low_y)];
    let high_rail = [(0.0, high_y), (1440.0, high_y)];

    // Only the median is a line; the 5–95 and 25–75 bands are a background fan.
    let median = Style::default()
        .fg(app.theme.graph)
        .add_modifier(Modifier::BOLD);
    let datasets = vec![
        braille_line(&low_rail, Style::default().fg(Color::DarkGray)),
        braille_line(&high_rail, Style::default().fg(Color::DarkGray)),
        braille_line(&p50, median),
    ];

    let lo_lab = fmt_disp(app.units, bounds_y[0]);
    let hi_lab = fmt_disp(app.units, bounds_y[1]);
    let gutter = chart_gutter(&[&lo_lab, &hi_lab], "00:00");

    let plot_w = area.width.saturating_sub(gutter + 3) as usize;
    let x_labels = fit_labels(
        plot_w,
        ["00:00", "06:00", "12:00", "18:00", "24:00"]
            .iter()
            .map(|s| s.to_string())
            .collect(),
    );

    let chart = Chart::new(datasets)
        .block(block)
        .x_axis(
            Axis::default()
                .bounds(bounds_x)
                .labels(x_labels.into_iter().map(Span::raw).collect::<Vec<_>>()),
        )
        .y_axis(
            Axis::default()
                .bounds(bounds_y)
                .labels(vec![Span::raw(lo_lab), Span::raw(hi_lab)]),
        );
    f.render_widget(chart, area);
    tint_in_range_band(f, area, bounds_y, gutter, low_y, high_y, app.theme.in_range);
    tint_agp_fan(f, area, bounds_y, gutter, &bands, &conv, app.theme.graph);
    label_agp_rails(f, area, bounds_y, gutter, low_y, high_y, app);
}

/// Name the two AGP reference rails directly on the plot. A gray line without
/// a label asks the reader to remember which threshold it represents.
fn label_agp_rails(
    f: &mut Frame,
    area: Rect,
    bounds_y: [f64; 2],
    gutter: u16,
    low_y: f64,
    high_y: f64,
    app: &App,
) {
    let Some(plot) = Plot::new(area, bounds_y, gutter) else {
        return;
    };
    for (value, row, color, name) in [
        (low_y, plot.row_of(low_y), app.theme.low, "low"),
        (high_y, plot.row_of(high_y), app.theme.high, "high"),
    ] {
        let label = format!(" {name} {} ", fmt_disp(app.units, value));
        let width = label.chars().count() as u16;
        let x = plot.x1.saturating_sub(width + 1).max(plot.x0);
        for (offset, ch) in label.chars().enumerate() {
            if let Some(cell) = f.buffer_mut().cell_mut((x + offset as u16, row)) {
                cell.set_char(ch)
                    .set_style(Style::default().fg(color).add_modifier(Modifier::BOLD));
            }
        }
    }
}

/// A braille line dataset over `data`, styled. Free fn so the borrow of `data`
/// carries into the returned `Dataset` (a closure can't express that).
fn braille_line(data: &[(f64, f64)], style: Style) -> Dataset<'_> {
    Dataset::default()
        .marker(symbols::Marker::Braille)
        .graph_type(GraphType::Line)
        .style(style)
        .data(data)
}

fn draw_graph(f: &mut Frame, area: Rect, app: &App) {
    // Title carries a small legend for the treatment markers, which are
    // otherwise unlabelled dots on the graph.
    let mut title = vec![Span::raw(format!(
        " {}{} ",
        fmt_time(app.view_start),
        fmt_time(app.view_end)
    ))];
    if app.treatments.iter().any(|t| t.carbs.is_some()) {
        title.push(Span::styled(
            "· ● carbs ",
            Style::default().fg(Color::Yellow),
        ));
    }
    if app.treatments.iter().any(|t| t.insulin.is_some()) {
        title.push(Span::styled("· ● bolus ", Style::default().fg(Color::Blue)));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(Line::from(title));

    if app.entries.is_empty() {
        f.render_widget(
            Paragraph::new(format!("  {}", empty_reason(app)))
                .block(block)
                .alignment(Alignment::Left),
            area,
        );
        return;
    }

    // x = real timestamp (ms), y = value in current units.
    let points: Vec<(f64, f64)> = app
        .entries
        .iter()
        .rev()
        .map(|e| (e.date as f64, app.units.from_mgdl(e.sgv)))
        .collect();

    // Forecast cone, anchored to the latest actual reading so it emanates from
    // the current dot. The whole band is shifted so its first centre sits on the
    // reading — uploader curves already start near the current value (shift ≈ 0),
    // so this mainly straightens the AR2 fallback's initial jump. Band width
    // (the uncertainty) is preserved.
    let (mut pred_center, mut pred_low, mut pred_high) = (Vec::new(), Vec::new(), Vec::new());
    if let (Some(e), Some(first)) = (app.latest(), app.predictions.first()) {
        let anchor_y = app.units.from_mgdl(e.sgv);
        let first_mid = app.units.from_mgdl((first.low + first.high) / 2.0);
        // Nudge the forecast so its *start* sits on the current reading, but let
        // the correction decay to zero across the horizon — so the fan emanates
        // from the dot yet still reaches the model's true endpoint (the AR2
        // fallback amplifies the recent trend on its first step; a constant
        // shift would drag the whole projection off). Uploader curves start near
        // the current value, so the correction is tiny for them anyway.
        let shift = anchor_y - first_mid;
        let n = app.predictions.len();
        let a = (e.date as f64, anchor_y);
        pred_center.push(a);
        pred_low.push(a);
        pred_high.push(a);
        for (j, p) in app.predictions.iter().enumerate() {
            let decay = if n > 1 {
                (n - 1 - j) as f64 / (n - 1) as f64
            } else {
                0.0
            };
            let s = shift * decay;
            let t = p.at_ms as f64;
            let lo = app.units.from_mgdl(p.low) + s;
            let hi = app.units.from_mgdl(p.high) + s;
            pred_low.push((t, lo));
            pred_high.push((t, hi));
            pred_center.push((t, (lo + hi) / 2.0));
        }
    }

    // Threshold rails (in display units) — always kept in view for reference.
    let low_y = app.units.from_mgdl(app.alerts.low);
    let high_y = app.units.from_mgdl(app.alerts.high);
    let (min_y, max_y) = points
        .iter()
        .chain(pred_low.iter())
        .chain(pred_high.iter())
        .fold((f64::MAX, f64::MIN), |(lo, hi), (_, y)| {
            (lo.min(*y), hi.max(*y))
        });
    let (min_y, max_y) = (min_y.min(low_y), max_y.max(high_y));
    let pad = ((max_y - min_y) * 0.1).max(app.units.from_mgdl(10.0));
    let bounds_y = [min_y - pad, max_y + pad];
    // Anchor x to the requested window; extend right to cover any forecast.
    let right = app
        .predictions
        .last()
        .map(|p| p.at_ms)
        .unwrap_or(app.view_end)
        .max(app.view_end);
    let bounds_x = [app.view_start as f64, right as f64];
    let mid_x = (app.view_start + right) / 2;

    // A dim vertical rule at the latest reading marks the boundary between
    // actual readings and the forecast — only when it's within the window.
    let now_line = app
        .latest()
        .map(|e| e.date as f64)
        .filter(|x| *x >= app.view_start as f64 && *x <= right as f64)
        .map(|x| [(x, bounds_y[0]), (x, bounds_y[1])]);

    // Treatment markers along the bottom: carbs and boluses on separate rows.
    let span_y = (bounds_y[1] - bounds_y[0]).max(1.0);
    let carb_pts: Vec<(f64, f64)> = app
        .treatments
        .iter()
        .filter(|t| t.carbs.is_some())
        .map(|t| (t.at_ms as f64, bounds_y[0] + span_y * 0.02))
        .collect();
    let bolus_pts: Vec<(f64, f64)> = app
        .treatments
        .iter()
        .filter(|t| t.insulin.is_some())
        .map(|t| (t.at_ms as f64, bounds_y[0] + span_y * 0.08))
        .collect();

    let (marker, gtype) = match app.graph_style {
        GraphStyle::Line => (symbols::Marker::Braille, GraphType::Line),
        GraphStyle::Dots => (symbols::Marker::Dot, GraphType::Scatter),
        GraphStyle::Blocks => (symbols::Marker::Block, GraphType::Scatter),
    };

    // Dim reference rails at the low/high thresholds (drawn under everything).
    let low_rail = [(app.view_start as f64, low_y), (right as f64, low_y)];
    let high_rail = [(app.view_start as f64, high_y), (right as f64, high_y)];

    // In scatter modes, colour readings by zone. A connected line can't change
    // colour mid-segment, so line mode keeps a single colour.
    let scatter = !matches!(app.graph_style, GraphStyle::Line);
    let (mut low_z, mut in_z, mut high_z) = (Vec::new(), Vec::new(), Vec::new());
    if scatter {
        for e in app.entries.iter().rev() {
            let p = (e.date as f64, app.units.from_mgdl(e.sgv));
            if e.sgv < app.alerts.low {
                low_z.push(p);
            } else if e.sgv > app.alerts.high {
                high_z.push(p);
            } else {
                in_z.push(p);
            }
        }
    }

    let mut datasets = vec![
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Line)
            .style(Style::default().fg(Color::DarkGray))
            .data(&low_rail),
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Line)
            .style(Style::default().fg(Color::DarkGray))
            .data(&high_rail),
    ];
    if scatter {
        for (pts, color) in [
            (&in_z, app.theme.in_range),
            (&low_z, app.theme.low),
            (&high_z, app.theme.high),
        ] {
            if !pts.is_empty() {
                datasets.push(
                    Dataset::default()
                        .marker(marker)
                        .graph_type(gtype)
                        .style(Style::default().fg(color))
                        .data(pts),
                );
            }
        }
    } else {
        datasets.push(
            Dataset::default()
                .marker(marker)
                .graph_type(gtype)
                .style(Style::default().fg(app.theme.graph))
                .data(&points),
        );
    }
    if let Some(nl) = &now_line {
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(Color::DarkGray))
                .data(nl),
        );
    }
    if !carb_pts.is_empty() {
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Dot)
                .graph_type(GraphType::Scatter)
                .style(Style::default().fg(Color::Yellow))
                .data(&carb_pts),
        );
    }
    if !bolus_pts.is_empty() {
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Dot)
                .graph_type(GraphType::Scatter)
                .style(Style::default().fg(Color::Blue))
                .data(&bolus_pts),
        );
    }
    // Forecast cone: the low–high band is a filled tint (below); draw only the
    // bright centre line on top.
    if !pred_center.is_empty() {
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(app.theme.prediction))
                .data(&pred_center),
        );
    }

    let lo_lab = fmt_disp(app.units, bounds_y[0]);
    let hi_lab = fmt_disp(app.units, bounds_y[1]);
    let first_x = fmt_time(app.view_start);
    let gutter = chart_gutter(&[&lo_lab, &hi_lab], &first_x);

    // Prefer full `MM-DD HH:MM` stamps, but fall back to the clock alone before
    // dropping labels — the pane's own title already carries the dated range,
    // so the time is what the axis is really for.
    let plot_w = area
        .width
        .saturating_sub(gutter + 3) // borders + y-axis line
        as usize;
    let stamps = [app.view_start, mid_x, right];
    let full: Vec<String> = stamps.iter().map(|t| fmt_time(*t)).collect();
    let x_labels = if fit_labels(plot_w, full.clone()).len() == full.len() {
        full
    } else {
        fit_labels(plot_w, stamps.iter().map(|t| fmt_clock(*t)).collect())
    };

    let chart = Chart::new(datasets)
        .block(block)
        .x_axis(
            Axis::default()
                .bounds(bounds_x)
                .labels(x_labels.into_iter().map(Span::raw).collect::<Vec<_>>()),
        )
        .y_axis(
            Axis::default()
                .bounds(bounds_y)
                .labels(vec![Span::raw(lo_lab), Span::raw(hi_lab)]),
        );
    f.render_widget(chart, area);
    tint_in_range_band(f, area, bounds_y, gutter, low_y, high_y, app.theme.in_range);
    // Fill the forecast cone's low–high band, leaving the centre line on top.
    if pred_low.len() > 1 {
        tint_band(
            f,
            area,
            (bounds_x, bounds_y),
            gutter,
            &pred_low,
            &pred_high,
            tint_bg(app.theme.prediction, 0.32),
        );
    }
}

/// Approximate RGB for a `Color`, so background tints can be derived from the
/// (possibly named / colourblind) palette rather than hardcoded.
fn rgb_of(c: Color) -> (u8, u8, u8) {
    match c {
        Color::Rgb(r, g, b) => (r, g, b),
        Color::Red => (205, 60, 55),
        Color::LightRed => (240, 100, 95),
        Color::Green => (40, 170, 95),
        Color::LightGreen => (90, 220, 130),
        Color::Yellow => (200, 170, 40),
        Color::LightYellow => (235, 215, 90),
        Color::Blue => (60, 110, 210),
        Color::LightBlue => (110, 170, 235),
        Color::Magenta => (185, 90, 175),
        Color::LightMagenta => (225, 130, 215),
        Color::Cyan => (40, 175, 180),
        Color::LightCyan => (110, 220, 225),
        Color::White | Color::Gray => (200, 205, 210),
        _ => (150, 155, 160),
    }
}

/// A dark background tint derived from a foreground colour (scaled toward
/// black), so a shaded zone tracks the active palette.
/// Whether the terminal advertises 24-bit colour.
///
/// The `Color::Rgb` tints degrade to nothing useful without it, so the code
/// that uses them needs a fallback rather than a hope.
fn truecolor() -> bool {
    std::env::var("COLORTERM")
        .map(|v| v.eq_ignore_ascii_case("truecolor") || v.eq_ignore_ascii_case("24bit"))
        .unwrap_or(false)
}

fn tint_bg(c: Color, scale: f32) -> Color {
    let (r, g, b) = rgb_of(c);
    Color::Rgb(
        (r as f32 * scale) as u8,
        (g as f32 * scale) as u8,
        (b as f32 * scale) as u8,
    )
}

/// The widest left-gutter reservation a `Chart` makes for its y-axis, matching
/// ratatui: the max y-label width, but at least the first (left-aligned) x-label
/// overhanging left of the y-axis by all but its last character.
/// Thin a set of x-axis labels until they fit the plot without colliding.
///
/// ratatui places the first label flush left, the last flush right and the rest
/// centred, and does nothing to keep them apart. Three 11-character stamps need
/// 35 columns; on a 60-column terminal the plot is narrower than that, so they
/// overlapped — and two overlapping dates read as a single date that never
/// existed. That is worse than no label at all on a chart people read clinically.
///
/// Drops middle labels first (the ends carry the window bounds), then falls
/// back to one, then to none.
fn fit_labels(plot_w: usize, mut labels: Vec<String>) -> Vec<String> {
    // One blank column between neighbours is the minimum that still reads as
    // two labels rather than one word.
    let needed = |ls: &[String]| -> usize {
        ls.iter().map(|l| l.chars().count()).sum::<usize>() + ls.len().saturating_sub(1)
    };
    while labels.len() > 2 && needed(&labels) > plot_w {
        // Drop every other middle label, keeping both ends.
        let keep: Vec<String> = labels
            .iter()
            .enumerate()
            .filter(|(i, _)| *i == 0 || *i == labels.len() - 1 || i % 2 == 0)
            .map(|(_, l)| l.clone())
            .collect();
        if keep.len() == labels.len() {
            labels.remove(labels.len() / 2);
        } else {
            labels = keep;
        }
    }
    if labels.len() == 2 && needed(&labels) > plot_w {
        labels.truncate(1);
    }
    if labels.len() == 1 && needed(&labels) > plot_w {
        labels.clear();
    }
    labels
}

fn chart_gutter(y_labels: &[&str], first_x_label: &str) -> u16 {
    let ymax = y_labels
        .iter()
        .map(|s| s.chars().count())
        .max()
        .unwrap_or(0) as u16;
    let x_overhang = (first_x_label.chars().count() as u16).saturating_sub(1);
    ymax.max(x_overhang)
}

/// Geometry of a `Chart`'s plotting rect inside `area`, replicating ratatui's
/// layout so background tints line up with the chart's own lines/points:
/// exclude the block border, the left gutter + a y-axis line column, and the
/// bottom two rows (the x-axis line and its labels).
struct Plot {
    x0: u16,
    x1: u16,
    top: u16,
    bot: u16,
    bounds_y: [f64; 2],
}

impl Plot {
    fn new(area: Rect, bounds_y: [f64; 2], gutter: u16) -> Option<Self> {
        let inner = area.inner(Margin::new(1, 1));
        let x0 = inner.x.saturating_add(gutter + 1); // gutter + y-axis line
        let x1 = inner.x + inner.width;
        let top = inner.y;
        let bot = inner.y + inner.height.saturating_sub(3); // x-axis line + labels
        (bot > top && x1 > x0).then_some(Self {
            x0,
            x1,
            top,
            bot,
            bounds_y,
        })
    }
    fn row_of(&self, v: f64) -> u16 {
        let ph = (self.bot - self.top) as f64;
        let yspan = (self.bounds_y[1] - self.bounds_y[0]).max(0.001);
        let r = ((self.bounds_y[1] - v) / yspan * ph).round() as i32;
        (self.top as i32 + r).clamp(self.top as i32, self.bot as i32) as u16
    }
}

/// Shade the in-range y-band by tinting the plot cells' background — a clean
/// solid band that `Chart` can't paint directly. Runs after the chart so
/// readings keep their foreground colour on the tint. The tint is derived from
/// the in-range palette colour so it survives theming / the colourblind preset.
fn tint_in_range_band(
    f: &mut Frame,
    area: Rect,
    bounds_y: [f64; 2],
    gutter: u16,
    low_y: f64,
    high_y: f64,
    in_range: Color,
) {
    let Some(plot) = Plot::new(area, bounds_y, gutter) else {
        return;
    };
    let (y0, y1) = (plot.row_of(high_y), plot.row_of(low_y));
    let band = tint_bg(in_range, 0.20);
    let buf = f.buffer_mut();
    for yy in y0..=y1 {
        for xx in plot.x0..plot.x1 {
            if let Some(cell) = buf.cell_mut((xx, yy)) {
                cell.set_bg(band);
            }
        }
    }
}

/// Interpolate the `y` of a sorted `(x, y)` series at `x` (clamped to the ends).
fn interp_xy(pts: &[(f64, f64)], x: f64) -> f64 {
    match pts.iter().position(|p| p.0 >= x) {
        Some(0) => pts[0].1,
        Some(i) => {
            let (a, b) = (pts[i - 1], pts[i]);
            let span = (b.0 - a.0).max(1.0);
            a.1 + (b.1 - a.1) * ((x - a.0) / span)
        }
        None => pts.last().map(|p| p.1).unwrap_or(0.0),
    }
}

/// Fill the band between a `low` and `high` `(x_data, y_display)` series by
/// tinting cell backgrounds per column — used for the forecast cone. `x_data`
/// is in the chart's x-bounds space (epoch ms); columns outside the series'
/// x-range are left untouched, so only the forecast region is shaded.
fn tint_band(
    f: &mut Frame,
    area: Rect,
    bounds: ([f64; 2], [f64; 2]),
    gutter: u16,
    low: &[(f64, f64)],
    high: &[(f64, f64)],
    bg: Color,
) {
    let (bounds_x, bounds_y) = bounds;
    let Some(plot) = Plot::new(area, bounds_y, gutter) else {
        return;
    };
    if low.len() < 2 || high.len() < 2 {
        return;
    }
    let (xmin, xmax) = (low[0].0, low[low.len() - 1].0);
    let xspan = (bounds_x[1] - bounds_x[0]).max(1.0);
    let pw = (plot.x1 - plot.x0).max(1) as f64;
    let buf = f.buffer_mut();
    for xx in plot.x0..plot.x1 {
        let x = bounds_x[0] + (xx - plot.x0) as f64 / pw * xspan;
        if x < xmin || x > xmax {
            continue;
        }
        let a = plot.row_of(interp_xy(high, x));
        let b = plot.row_of(interp_xy(low, x));
        for yy in a.min(b)..=a.max(b) {
            if let Some(cell) = buf.cell_mut((xx, yy)) {
                cell.set_bg(bg);
            }
        }
    }
}

/// Fill the AGP percentile fan by tinting cell backgrounds per column: a light
/// outer 5–95 band and a darker inner 25–75 band, interpolated across the day.
/// Leaves the median line (drawn by the chart) crisp on top.
fn tint_agp_fan(
    f: &mut Frame,
    area: Rect,
    bounds_y: [f64; 2],
    gutter: u16,
    bands: &[agp::Band],
    conv: &dyn Fn(f64) -> f64,
    base: Color,
) {
    let Some(plot) = Plot::new(area, bounds_y, gutter) else {
        return;
    };
    if bands.len() < 2 {
        return;
    }
    // theme.rs deliberately uses named ANSI colours "so the palette renders
    // identically on 16-color consoles, tmux, and SSH sessions that lack
    // COLORTERM=truecolor" — and then the fan painted itself in Color::Rgb
    // backgrounds, which is exactly what collapses on those sessions, leaving
    // an unlabelled median line. Where 24-bit isn't available, draw the fan as
    // shaded glyphs in the theme colour instead: it survives 16 colours, and
    // the texture difference reads without colour at all.
    let shaded = !truecolor();
    // Linear-interpolate a percentile curve at `minute` from the sparse buckets.
    let at = |minute: f64, pick: &dyn Fn(&agp::Band) -> f64| -> f64 {
        match bands.iter().position(|b| b.minute as f64 >= minute) {
            Some(0) => conv(pick(&bands[0])),
            Some(i) => {
                let (a, b) = (&bands[i - 1], &bands[i]);
                let span = (b.minute - a.minute).max(1) as f64;
                let t = (minute - a.minute as f64) / span;
                conv(pick(a)) + (conv(pick(b)) - conv(pick(a))) * t
            }
            None => conv(pick(&bands[bands.len() - 1])),
        }
    };
    let pw = (plot.x1 - plot.x0).max(1) as f64;
    let buf = f.buffer_mut();
    for xx in plot.x0..plot.x1 {
        let minute = (xx - plot.x0) as f64 / pw * 1440.0;
        let (o_lo, o_hi) = (
            plot.row_of(at(minute, &|b| b.p95)),
            plot.row_of(at(minute, &|b| b.p05)),
        );
        let (i_lo, i_hi) = (
            plot.row_of(at(minute, &|b| b.p75)),
            plot.row_of(at(minute, &|b| b.p25)),
        );
        for yy in o_lo..=o_hi {
            let is_inner = yy >= i_lo && yy <= i_hi;
            let Some(cell) = buf.cell_mut((xx, yy)) else {
                continue;
            };
            // Never overwrite the median line or a rail that has already been
            // drawn into this cell.
            if shaded {
                if cell.symbol() == " " {
                    cell.set_symbol(if is_inner { "" } else { "" });
                    cell.set_fg(base);
                }
            } else {
                cell.set_bg(tint_bg(base, if is_inner { 0.34 } else { 0.16 }));
            }
        }
    }
}

fn draw_footer(f: &mut Frame, area: Rect, app: &App) {
    if let Some(buf) = &app.date_input {
        const PROMPT: &str = " jump to date (YYYY-MM-DD): ";
        let line = Line::from(vec![
            Span::styled(PROMPT, Style::default().fg(Color::Cyan)),
            Span::styled(buf.clone(), Style::default().add_modifier(Modifier::BOLD)),
            Span::raw(" · enter confirm · esc cancel"),
        ]);
        f.render_widget(Paragraph::new(line), area);
        // The real cursor, rather than a blinking `_`: see draw_settings.
        let x = (PROMPT.chars().count() + buf.chars().count()) as u16;
        if x < area.width {
            f.set_cursor_position((area.x + x, area.y));
        }
        return;
    }

    // Warnings return (message, colour) rather than a finished span, so the
    // renderer below can keep `? help` pinned to the right in every state.
    // Previously a warning replaced the hint line outright — and two of them
    // (a group-readable config, an http site) are *standing* conditions, so a
    // user in that state never saw a keybinding again, including the one that
    // opens the help explaining the fix.
    let mut hints: Option<String> = None;
    let warning: Option<(String, Color)> = match app.last_error() {
        Some(err) => Some((format!(" error: {err}"), Color::Red)),
        // Readings arrived but something alongside them didn't: not an outage,
        // but the affected panels are showing stale values, so say which.
        None if app.partial().is_some() => Some((
            format!(
                " ⚠ unavailable, showing last known: {}",
                app.partial().unwrap_or_default()
            ),
            Color::Yellow,
        )),
        // A cleartext site leaks the token and the readings to anything on the
        // path. Not fatal — a LAN self-host is a real setup — but never silent.
        None if app.notify_failed => Some((
            " ⚠ desktop notifications aren't reaching a notification daemon".into(),
            Color::Yellow,
        )),
        None if !app.demo && app.active_site().is_insecure() => Some((
            " ⚠ unencrypted http:// site — the token is sent in clear (settings › site URL)".into(),
            Color::Yellow,
        )),
        // A coerced threshold outranks the permissions notice: it means the
        // alarm is not using the numbers the user wrote.
        None if !app.config_warnings.is_empty() => Some((
            format!(" ⚠ config: {}", app.config_warnings.join(" · ")),
            Color::Yellow,
        )),
        None if app.perm_warning => Some((
            " ⚠ config.toml is readable by others — run: chmod 600 ~/.config/sugarrush/config.toml"
                .into(),
            Color::Yellow,
        )),
        None => {
            // On a narrow footer the full hint line silently clips, hiding
            // settings/site/snooze; fall back to a terse set that always keeps
            // `? help` so nothing becomes undiscoverable.
            let alarm = app.alarm_active(chrono::Utc::now().timestamp_millis());
            let s = if area.width < 72 {
                let mut s = String::from(" q quit · tab view · s settings");
                if alarm {
                    s.push_str(" · a snooze");
                }
                s.push_str(" · ? help ");
                s
            } else {
                let mut s = if app.is_agp() {
                    String::from(" q quit · r refresh · u units · tab view · s settings")
                } else {
                    String::from(
                        " q quit · r refresh · u units · tab view · h/l pan · +/- zoom · g date · f live · s settings",
                    )
                };
                if app.sites.len() > 1 {
                    s.push_str(" · n site");
                }
                if app.minimap_enabled {
                    s.push_str(" · drag overview");
                }
                if alarm {
                    s.push_str(" · a snooze");
                }
                s.push_str(" · ? help ");
                s
            };
            hints = Some(s);
            None
        }
    };
    // The snooze countdown used to live here too. It is in the header chip now
    // — one place, and one that an error state can't take over.
    let mut spans = Vec::new();
    let text = match (warning, hints) {
        (Some((msg, color)), _) => {
            const HELP: &str = " ? help ";
            let width = area.width as usize;
            let room = width.saturating_sub(HELP.chars().count());
            let shown: String = if msg.chars().count() > room && room > 2 {
                // Elide rather than let the terminal clip: the actionable
                // half of these messages is always at the end.
                msg.chars().take(room - 1).chain(['']).collect()
            } else {
                msg
            };
            let pad = width
                .saturating_sub(shown.chars().count())
                .saturating_sub(HELP.chars().count());
            spans.push(Span::styled(shown, Style::default().fg(color)));
            spans.push(Span::raw(" ".repeat(pad)));
            Span::styled(HELP, Style::default().fg(Color::Cyan))
        }
        (None, Some(s)) => Span::raw(s),
        (None, None) => Span::raw(""),
    };
    spans.push(text);
    f.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// Format an epoch-ms timestamp as local `MM-DD HH:MM`.
/// Just the clock, for axis labels too narrow to carry a date.
fn fmt_clock(ms: i64) -> String {
    match Local.timestamp_millis_opt(ms).single() {
        Some(dt) => dt.format("%H:%M").to_string(),
        None => "--".into(),
    }
}

fn fmt_time(ms: i64) -> String {
    match Local.timestamp_millis_opt(ms).single() {
        Some(dt) => dt.format("%m-%d %H:%M").to_string(),
        None => "--".into(),
    }
}

/// Colour a reading by configured thresholds and theme.
fn color_for(sgv: f64, app: &App) -> Color {
    crate::alert::from_value(sgv, &app.alerts).color(&app.theme)
}

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

    // These are pure functions doing arithmetic. The repo's rule — "verify UI
    // changes visually" — is right for `Chart` geometry and wrong for this;
    // a terminal is not required to know what 90 minutes reads as.

    #[test]
    fn ages_read_the_way_a_person_would_say_them() {
        assert_eq!(fmt_age(0), "0m");
        assert_eq!(fmt_age(59_000), "0m");
        assert_eq!(fmt_age(90 * 60_000), "1h 30m");
        assert_eq!(fmt_age(24 * 3_600_000), "1d 0h");
        assert_eq!(fmt_age(50 * 3_600_000), "2d 2h");
        // A clock skew shouldn't render a negative age.
        assert_eq!(fmt_age(-5_000), "0m");
    }

    #[test]
    fn sparkline_spans_its_range_and_survives_a_flat_series() {
        assert_eq!(sparkline_str(&[]), "");
        let s = sparkline_str(&[100.0, 150.0, 200.0]);
        assert_eq!(s.chars().count(), 3);
        assert_eq!(s.chars().next(), Some(''));
        assert_eq!(s.chars().last(), Some(''));
        // Flat input must not divide by zero or render garbage.
        let flat = sparkline_str(&[100.0, 100.0, 100.0]);
        assert_eq!(flat.chars().count(), 3);
        assert!(flat.chars().all(|c| c == ''));
    }

    #[test]
    fn the_chart_gutter_fits_the_widest_label_it_must_hold() {
        // Wide y labels win.
        assert_eq!(chart_gutter(&["10.6", "3.3"], "08-08 12:00"), 10);
        // A long first x label overhangs the axis by all but one column.
        assert_eq!(chart_gutter(&["10"], "08-08 12:00"), 10);
        assert_eq!(chart_gutter(&["120", "60"], "12:00"), 4);
        assert_eq!(chart_gutter(&[], ""), 0);
    }

    #[test]
    fn interpolation_holds_flat_outside_the_series() {
        let pts = [(0.0, 10.0), (10.0, 20.0)];
        assert_eq!(interp_xy(&pts, -5.0), 10.0); // before the first point
        assert_eq!(interp_xy(&pts, 0.0), 10.0);
        assert_eq!(interp_xy(&pts, 5.0), 15.0); // midpoint
        assert_eq!(interp_xy(&pts, 10.0), 20.0);
        assert_eq!(interp_xy(&pts, 99.0), 20.0); // after the last point
        assert_eq!(interp_xy(&[], 1.0), 0.0);
    }

    #[test]
    fn tinting_moves_toward_the_colour_without_leaving_the_ground() {
        // scale 0 is the background, scale 1 is the colour itself.
        let (r, g, b) = rgb_of(tint_bg(Color::Rgb(200, 100, 50), 0.0));
        assert!(
            r < 30 && g < 30 && b < 30,
            "({r},{g},{b}) is not near-black"
        );
        let full = rgb_of(tint_bg(Color::Rgb(200, 100, 50), 1.0));
        assert_eq!(full, (200, 100, 50));
        // A partial tint sits between the two.
        let (r, _, _) = rgb_of(tint_bg(Color::Rgb(200, 100, 50), 0.5));
        assert!((80..=140).contains(&r), "midpoint red was {r}");
    }

    /// Rendering must not panic at any plausible terminal size — including the
    /// ones a tiling WM or a phone SSH client produces. This is the cheap half
    /// of the "verify visually" rule that a machine can do.
    #[test]
    fn every_screen_renders_at_every_plausible_size() {
        use ratatui::{backend::TestBackend, Terminal};

        for (w, h) in [
            (200u16, 60u16),
            (120, 40),
            (80, 24),
            (60, 20),
            (40, 15),
            (20, 10),
            (10, 5),
        ] {
            for screen in [Screen::Dashboard, Screen::Settings, Screen::Followers] {
                let mut app = demo_app();
                app.screen = screen;
                let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
                term.draw(|f| draw(f, &app))
                    .unwrap_or_else(|e| panic!("{screen:?} at {w}x{h}: {e}"));
                // And with the help overlay up, which composites over the top.
                app.show_help = true;
                term.draw(|f| draw(f, &app))
                    .unwrap_or_else(|e| panic!("{screen:?} + help at {w}x{h}: {e}"));
            }
        }
    }

    /// At a size anyone would call usable, the reading itself must be on
    /// screen. This is the assertion that would have caught the class of bug
    /// where a pane collapses and the glucose value silently disappears.
    #[test]
    fn the_reading_is_on_screen_at_usable_sizes() {
        use ratatui::{backend::TestBackend, Terminal};

        for (w, h) in [
            (200u16, 60u16),
            (120, 40),
            (80, 30),
            (60, 26),
            (80, 22),
            (63, 20),
            (80, 16),
            (60, 12),
            (40, 8),
        ] {
            let app = demo_app();
            let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
            term.draw(|f| draw(f, &app)).unwrap();
            let text: String = term
                .backend()
                .buffer()
                .content()
                .iter()
                .map(|c| c.symbol())
                .collect();
            assert!(
                text.contains("5.6"),
                "the current reading is not in the buffer at {w}x{h}"
            );
            // And the state, as text — not only as a colour.
            assert!(
                text.contains("in range"),
                "the range label is not in the buffer at {w}x{h}"
            );
        }
    }

    /// The same guarantee while alerting — which costs a banner row, and is
    /// exactly when the number matters most.
    #[test]
    fn the_reading_survives_the_alert_banner_on_a_short_terminal() {
        use ratatui::{backend::TestBackend, Terminal};

        for (w, h) in [(80u16, 24u16), (63, 20), (80, 16), (60, 12), (40, 8)] {
            let mut app = demo_app();
            let now = chrono::Utc::now().timestamp_millis();
            app.entries = vec![crate::nightscout::Entry {
                sgv: 45.0,
                date: now,
                direction: Some("DoubleDown".into()),
            }];
            app.evaluate_alert(now);
            assert!(app.alert.is_alerting(), "the fixture should be alerting");

            let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
            term.draw(|f| draw(f, &app)).unwrap();
            let text: String = term
                .backend()
                .buffer()
                .content()
                .iter()
                .map(|c| c.symbol())
                .collect();
            assert!(
                text.contains("2.5"),
                "the urgent reading is not in the buffer at {w}x{h}"
            );
            assert!(
                text.contains("URGENT LOW"),
                "the alert state is not in the buffer at {w}x{h}"
            );
        }
    }
    /// One failure, one explanation. A rejected token used to produce three
    /// different messages across three panels, one of which ("loading
    /// overview…") was a lie — nothing was loading and nothing ever would.
    #[test]
    fn every_empty_panel_gives_the_same_reason() {
        use ratatui::{backend::TestBackend, Terminal};

        let mut app = demo_app();
        app.entries.clear();
        app.minimap_entries.clear();
        app.demo = false;
        app.mark_offline(
            chrono::Utc::now().timestamp_millis(),
            "authentication failed".into(),
            true,
        );

        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();

        assert!(
            !text.contains("loading"),
            "a paused fetch must never claim to be loading"
        );
        let reason = empty_reason(&app);
        // current, graph and the 24h overview — all three empty, all three
        // saying the same thing.
        assert_eq!(
            text.matches(reason).count(),
            3,
            "every empty panel should carry the same reason: {reason:?}"
        );
    }

    /// The connection dot is not the view mode. A green ● beside a red
    /// authentication error read as "the connection is live".
    #[test]
    fn the_dot_follows_the_connection_not_the_view() {
        use ratatui::{backend::TestBackend, Terminal};

        let render = |app: &App| -> String {
            let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
            term.draw(|f| draw(f, app)).unwrap();
            term.backend()
                .buffer()
                .content()
                .iter()
                .map(|c| c.symbol())
                .collect()
        };

        let app = demo_app();
        assert!(render(&app).contains("● live"), "fresh data reads live");

        let mut down = demo_app();
        down.demo = false;
        down.mark_offline(
            chrono::Utc::now().timestamp_millis(),
            "can't reach Nightscout".into(),
            false,
        );
        let text = render(&down);
        assert!(
            !text.contains("● live"),
            "the dot must not stay green during an outage"
        );
        assert!(
            text.contains("✖ live"),
            "an outage should show a broken dot"
        );
    }

    /// A blinking fake `_` is invisible to a screen reader's caret tracking and
    /// unstoppable on terminals that honour SGR 5 — a WCAG 2.2.2 failure and a
    /// migraine trigger. Both text prompts must position the real terminal
    /// cursor instead, and nothing may blink.
    #[test]
    fn text_prompts_position_the_real_cursor_and_never_blink() {
        use ratatui::style::Modifier;
        use ratatui::{backend::TestBackend, Terminal};

        // The settings editor, on a masked field where the text is bullets and
        // the caret is the only cue about where typing lands.
        let mut app = demo_app();
        app.screen = Screen::Settings;
        assert!(app.begin_field_edit(), "the first field should be editable");
        for c in "abc".chars() {
            app.field_edit_push(c);
        }

        // …and the date-jump prompt on the dashboard.
        let mut jumping = demo_app();
        jumping.date_input = Some("2026-08".to_string());

        for app in [&app, &jumping] {
            let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap();
            term.draw(|f| draw(f, app)).unwrap();

            let pos = term.get_cursor_position().unwrap();
            assert!(
                pos.x > 0 && pos.y > 0,
                "an open text prompt must place the terminal cursor, got {pos:?}"
            );
            assert!(
                !term
                    .backend()
                    .buffer()
                    .content()
                    .iter()
                    .any(|c| c.style().add_modifier.contains(Modifier::SLOW_BLINK)),
                "nothing may blink"
            );
        }
    }

    /// `?` used to be a dead key on the followers screen — it set the flag, the
    /// early return meant nothing drew, and the overlay then ambushed the next
    /// dashboard render. Settings had no `?` handler at all, so the screen with
    /// the most unexplained rows was the one screen with no key reference.
    #[test]
    fn help_opens_on_every_screen() {
        use ratatui::{backend::TestBackend, Terminal};

        for screen in [Screen::Dashboard, Screen::Settings, Screen::Followers] {
            let mut app = demo_app();
            app.screen = screen;
            app.show_help = true;

            let mut term = Terminal::new(TestBackend::new(100, 40)).unwrap();
            term.draw(|f| draw(f, &app)).unwrap();
            let text: String = term
                .backend()
                .buffer()
                .content()
                .iter()
                .map(|c| c.symbol())
                .collect();

            assert!(
                text.contains("press any key to close"),
                "the help overlay should be visible on {screen:?}"
            );
            // Settings gets its own vocabulary — a dashboard cheatsheet there
            // would be wrong on every line.
            match screen {
                Screen::Settings => assert!(
                    text.contains("save to config.toml"),
                    "settings help should document the settings keys"
                ),
                Screen::Followers => {
                    assert!(text.contains("select a followed person"));
                    assert!(!text.contains("pan back / forward"));
                }
                Screen::Dashboard => assert!(
                    text.contains("pan back / forward"),
                    "dashboard help should document the graph keys"
                ),
            }
        }
    }

    /// Both footers must advertise the key, or the overlay is only reachable by
    /// guessing.
    #[test]
    fn every_screen_advertises_help_in_its_footer() {
        use ratatui::{backend::TestBackend, Terminal};

        for screen in [Screen::Dashboard, Screen::Settings, Screen::Followers] {
            let mut app = demo_app();
            app.screen = screen;
            let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
            term.draw(|f| draw(f, &app)).unwrap();
            let text: String = term
                .backend()
                .buffer()
                .content()
                .iter()
                .map(|c| c.symbol())
                .collect();
            assert!(
                text.contains("? help"),
                "{screen:?} does not advertise the help key"
            );
        }
    }

    /// Three `MM-DD HH:MM` stamps need 35 columns. On a narrow terminal
    /// ratatui laid them out anyway — first flush left, last flush right,
    /// middle centred — and they ran together into text that reads as a date
    /// that never existed. On a chart people read clinically, a wrong date is
    /// worse than a missing one.
    #[test]
    fn x_axis_labels_never_collide() {
        use ratatui::{backend::TestBackend, Terminal};

        for w in [40u16, 50, 60, 70, 80, 100, 140, 200] {
            for view in [
                crate::app::GraphView::H3,
                crate::app::GraphView::H24,
                crate::app::GraphView::Agp,
            ] {
                let mut app = demo_app();
                app.graph_view = view;
                let mut term = Terminal::new(TestBackend::new(w, 40)).unwrap();
                term.draw(|f| draw(f, &app)).unwrap();
                let b = term.backend().buffer();

                // Every row of the buffer: any date stamp that appears must be
                // a whole one. A collision shows up as digits butting straight
                // onto the end of a previous label.
                // Any token carrying a clock must be a whole `HH:MM`. A
                // collision splices two labels and produces things like
                // `01:-09`, which a reader parses as a time that never was.
                for y in 0..40u16 {
                    let row: String = (0..w).map(|x| b[(x, y)].symbol()).collect();
                    // Box-drawing sits flush against the first and last label;
                    // it is chrome, not part of the text under test.
                    let stripped: String = row
                        .chars()
                        .map(|c| if c.is_ascii_graphic() { c } else { ' ' })
                        .collect();
                    for token in stripped.split_whitespace() {
                        if !token.contains(':') {
                            continue;
                        }
                        let clock = token.len() == 5
                            && token.chars().enumerate().all(|(i, c)| {
                                if i == 2 {
                                    c == ':'
                                } else {
                                    c.is_ascii_digit()
                                }
                            });
                        assert!(
                            clock,
                            "labels collided at width {w} ({view:?}): {token:?} in {row:?}"
                        );
                    }
                }
            }
        }
    }

    /// The thinning itself: ends are kept, middles go first, and nothing is
    /// ever returned that cannot fit.
    #[test]
    fn fit_labels_keeps_the_ends() {
        let three = || {
            vec![
                "08-08 23:08".to_string(),
                "08-09 00:51".to_string(),
                "08-09 02:35".to_string(),
            ]
        };
        assert_eq!(fit_labels(40, three()).len(), 3, "all three fit at 40");
        let thinned = fit_labels(25, three());
        assert_eq!(thinned.len(), 2, "the middle goes first");
        assert_eq!(thinned[0], "08-08 23:08");
        assert_eq!(thinned[1], "08-09 02:35");
        assert_eq!(fit_labels(15, three()).len(), 1);
        assert!(fit_labels(4, three()).is_empty());
    }

    /// Three of the five clinical bands had no textual form: above-range and
    /// very-high existed only as colours in the bar, and with the default
    /// palette two of those colours were the same red. Anyone not reading
    /// colour got two numbers out of five.
    #[test]
    fn every_time_in_range_band_has_a_number() {
        use ratatui::{backend::TestBackend, Terminal};

        let mut app = demo_app();
        let now = chrono::Utc::now().timestamp_millis();
        // A window that lands in all five bands.
        app.agp_entries = [40.0, 60.0, 100.0, 200.0, 300.0]
            .iter()
            .enumerate()
            .map(|(i, sgv)| crate::nightscout::Entry {
                sgv: *sgv,
                date: now - i as i64 * 300_000,
                direction: None,
            })
            .collect();

        let mut term = Terminal::new(TestBackend::new(200, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();

        for expected in ["in range", "below", "very low", "above"] {
            assert!(
                text.contains(expected),
                "{expected:?} has no textual form in the stats panel"
            );
        }
    }

    /// …and the suffixes are dropped whole as the pane narrows, never clipped:
    /// a truncated "· 7%" reads as a different number.
    #[test]
    fn time_in_range_suffixes_are_dropped_whole() {
        use ratatui::{backend::TestBackend, Terminal};

        for w in [40u16, 50, 60, 70, 80, 90, 110, 140, 200] {
            let mut app = demo_app();
            let now = chrono::Utc::now().timestamp_millis();
            app.agp_entries = [40.0, 60.0, 100.0, 200.0, 300.0]
                .iter()
                .enumerate()
                .map(|(i, sgv)| crate::nightscout::Entry {
                    sgv: *sgv,
                    date: now - i as i64 * 300_000,
                    direction: None,
                })
                .collect();

            let mut term = Terminal::new(TestBackend::new(w, 40)).unwrap();
            term.draw(|f| draw(f, &app)).unwrap();
            let b = term.backend().buffer();
            for y in 0..40u16 {
                let row: String = (0..w).map(|x| b[(x, y)].symbol()).collect();
                if !row.contains("TIR") {
                    continue;
                }
                // Any "%" on the line must be followed by a whole word, not by
                // the pane border or the end of the row.
                for (i, _) in row.match_indices('%') {
                    let rest = row[i + 1..].trim_start();
                    assert!(
                        rest.starts_with("in range")
                            || rest.starts_with("below")
                            || rest.starts_with("above")
                            || rest.starts_with("very low"),
                        "a percentage was clipped at width {w}: {row:?}"
                    );
                }
            }
        }
    }

    /// theme.rs picks named ANSI colours on purpose, "so the palette renders
    /// identically on 16-color consoles, tmux, and SSH sessions that lack
    /// COLORTERM=truecolor". The AGP fan then painted itself in `Color::Rgb`
    /// backgrounds, which is precisely what collapses there — leaving an
    /// unlabelled median line where the percentile fan should be.
    #[test]
    fn the_agp_fan_survives_without_truecolor() {
        use ratatui::{backend::TestBackend, Terminal};

        let render = |truecolor: bool| -> (usize, usize) {
            // SAFETY-free: this is a process-wide env var, and the tests that
            // read it are in this one function.
            if truecolor {
                std::env::set_var("COLORTERM", "truecolor");
            } else {
                std::env::remove_var("COLORTERM");
            }
            let mut app = demo_app();
            app.graph_view = crate::app::GraphView::Agp;
            let now = chrono::Utc::now().timestamp_millis();
            // Ten days of readings so the profile has buckets to fan out.
            app.agp_entries = (0..10 * 24 * 4)
                .map(|i| crate::nightscout::Entry {
                    sgv: 100.0 + ((i % 40) as f64 - 20.0) * 3.0,
                    date: now - i as i64 * 15 * 60_000,
                    direction: None,
                })
                .collect();

            let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
            term.draw(|f| draw(f, &app)).unwrap();
            let buf = term.backend().buffer();
            let shaded = buf
                .content()
                .iter()
                .filter(|c| c.symbol() == "" || c.symbol() == "")
                .count();
            let tinted = buf
                .content()
                .iter()
                .filter(|c| matches!(c.style().bg, Some(ratatui::style::Color::Rgb(..))))
                .count();
            (shaded, tinted)
        };

        let (shaded_16, _) = render(false);
        assert!(
            shaded_16 > 50,
            "without truecolor the fan must be drawn with glyphs, got {shaded_16} cells"
        );

        let (_, tinted_24) = render(true);
        assert!(
            tinted_24 > 50,
            "with truecolor the fan should still be a background tint, got {tinted_24} cells"
        );
        std::env::remove_var("COLORTERM");
    }

    /// The legend is what makes a percentile fan readable. It used to be
    /// *replaced* by the insight headline, so it vanished exactly when the
    /// chart had something to say.
    #[test]
    fn the_agp_legend_survives_an_insight() {
        use ratatui::{backend::TestBackend, Terminal};

        let mut app = demo_app();
        app.graph_view = crate::app::GraphView::Agp;
        let now = chrono::Utc::now().timestamp_millis();
        // Ten days that are low every night between 02:00 and 05:00 — enough
        // separate days for an insight to fire.
        app.agp_entries = (0..10 * 24 * 4)
            .map(|i| {
                let date = now - i as i64 * 15 * 60_000;
                let hour = chrono::Local
                    .timestamp_millis_opt(date)
                    .single()
                    .map(|d| chrono::Timelike::hour(&d))
                    .unwrap_or(12);
                crate::nightscout::Entry {
                    sgv: if (2..5).contains(&hour) { 55.0 } else { 120.0 },
                    date,
                    direction: None,
                }
            })
            .collect();

        let mut term = Terminal::new(TestBackend::new(160, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();

        assert!(text.contains(""), "the fixture should produce an insight");
        assert!(
            text.contains("median + IQR + 5/95"),
            "the legend must survive the headline"
        );
        assert!(text.contains("low 3.9"), "the low rail is not labelled");
        assert!(text.contains("high 10.0"), "the high rail is not labelled");
    }

    /// The alarm self-test is reachable from the settings screen — a setting
    /// that says "Audible alarm: on" is a claim about a config field, not about
    /// whether this machine can make a noise.
    #[test]
    fn the_settings_screen_offers_the_alarm_test() {
        use ratatui::{backend::TestBackend, Terminal};

        let mut app = demo_app();
        app.screen = Screen::Settings;
        let mut term = Terminal::new(TestBackend::new(100, 60)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            text.contains("Test the alarm"),
            "no self-test row in settings"
        );
        assert!(
            text.contains("press enter"),
            "the row should say how to run it"
        );
    }

    #[test]
    fn settings_show_field_detail_and_scroll_affordance() {
        use ratatui::{backend::TestBackend, Terminal};

        let mut app = demo_app();
        app.screen = Screen::Settings;
        let mut term = Terminal::new(TestBackend::new(100, 24)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let first: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|cell| cell.symbol())
            .collect();
        assert!(first.contains("Current"));
        assert!(first.contains("↓ more"));
        assert!(first.contains("name used in follower rows"));

        app.settings_sel = Field::ALL.len() - 1;
        term.draw(|f| draw(f, &app)).unwrap();
        let last: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|cell| cell.symbol())
            .collect();
        assert!(last.contains("↑ more"));
        assert!(last.contains("Colorblind palette"));
    }

    #[test]
    fn followers_have_units_severity_rails_and_sparklines() {
        use ratatui::{backend::TestBackend, Terminal};

        let mut app = demo_app();
        app.screen = Screen::Followers;
        app.followers = crate::follow::demo(
            chrono::Utc::now().timestamp_millis(),
            &[app.alerts.clone(), app.alerts.clone(), app.alerts.clone()],
        );
        let mut term = Terminal::new(TestBackend::new(120, 24)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|cell| cell.symbol())
            .collect();
        assert!(text.contains(app.units.label()));
        assert!(text.contains("LAST HOUR"));
        assert!(text.contains(''));
        assert!(text.contains('') || text.contains(''));
    }

    #[test]
    fn follower_overflow_is_scrollable_and_keeps_columns_bounded() {
        use ratatui::{backend::TestBackend, Terminal};

        let mut app = demo_app();
        app.screen = Screen::Followers;
        let sample =
            crate::follow::demo(chrono::Utc::now().timestamp_millis(), &[app.alerts.clone()])[0]
                .clone();
        app.followers = (0..20)
            .map(|i| {
                let mut row = sample.clone();
                row.name = format!("{i:02}-person-with-a-very-long-name");
                row
            })
            .collect();
        app.follower_scroll = 10;

        let mut term = Terminal::new(TestBackend::new(90, 12)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|cell| cell.symbol())
            .collect();
        assert!(text.contains("↑ more"));
        assert!(text.contains("↓ more"));
        assert!(text.contains(''), "long names should be ellipsized");
        assert!(text.contains("10") || text.contains("11"));
    }

    /// An app on demo config with one fixed, in-range reading.
    fn demo_app() -> App {
        let cfg = crate::config::Config::demo();
        let alerts = cfg.alerts.resolve(cfg.units);
        let sites = cfg.resolve_sites().unwrap();
        let mut app = App::new(&cfg, alerts, sites);
        app.demo = true;
        let now = chrono::Utc::now().timestamp_millis();
        app.entries = vec![crate::nightscout::Entry {
            sgv: 100.0,
            date: now,
            direction: Some("Flat".into()),
        }];
        app.view_start = now - 3 * 3_600_000;
        app.view_end = now;
        app.evaluate_alert(now);
        app
    }
}