talk-rs 0.7.1

Voice dictation for Linux -- record, transcribe, and paste
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
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
//! Visual overlay indicator for recording/transcribing status.
//!
//! Displays a small badge at the top-center of the primary monitor using X11.
//! Uses the Shape extension for binary transparency (works without a compositor).
//! The overlay runs on a dedicated background thread with a command channel.
//!
//! During **recording**, the badge is rendered dynamically at 60 fps:
//! a pulsing red dot (brightness driven by volume) plus a real-time
//! spectrogram waterfall that scrolls right-to-left, replacing the
//! former static "recording" text.
//!
//! During **transcribing**, the badge is a static PNG (unchanged).

use super::render_util::{
    apply_rounded_shape, blit_glyph_at, compute_spectrum, map_spectrum_to_column, rasterise_glyphs,
    rms, PixelBuffer, RingBuffer, FFT_SIZE, FREQ_MAX, FREQ_NOISE_FLOOR, PEAK_DECAY, PEAK_FLOOR,
};
use crate::error::TalkError;
use crate::telemetry::TranscriptionEvent;
use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use x11rb::connection::Connection;
use x11rb::protocol::shape;
use x11rb::protocol::xproto::*;
use x11rb::wrapper::ConnectionExt as _;
use x11rb::COPY_DEPTH_FROM_PARENT;

// ── Embedded PNG assets ──────────────────────────────────────────────

/// "transcribing" badge: 210×52, dark rounded rect with blue dot + text.
const TRANSCRIBING_PNG: &[u8] = include_bytes!("../../assets/transcribing.png");

// ── Badge layout constants ───────────────────────────────────────────

/// Badge width in pixels (~50% wider than original for full-width spectrogram).
pub(crate) const BADGE_W: u16 = 273;
/// Badge height in pixels.
const BADGE_H: u16 = 52;
/// Corner radius for the rounded rectangle background.
const CORNER_RADIUS: usize = 13;

/// X coordinate of the red dot centre.  Moved right from the original
/// `20` so the larger dot (radius 21 + gap 2) fits inside the border
/// without clipping the rounded corners.
const DOT_CX: usize = 26;
/// Y coordinate of the red dot centre (vertically centred in the spec
/// area: spec rows 4..48 → centre at 26, and with an odd-pixel
/// diameter the dot is perfectly symmetric top/bottom).
const DOT_CY: usize = 26;
/// Minimum red dot radius (quiet).  Scaled up proportionally from the
/// original `3.0` to remain visible at the new badge scale.
const DOT_RADIUS_MIN: f32 = 6.0;
/// Maximum red dot radius (loud).  Fills almost the entire spec area
/// height (diameter 43 inside the 44 px spec band) so the volume
/// indicator is easy to read at a glance.
const DOT_RADIUS_MAX: f32 = 16.0;
/// Radius for the prohibit icon shown during dead-signal detection.
///
/// Deliberately smaller than [`DOT_RADIUS_MAX`] so the icon stays
/// compact with a visibly thick stroke (stroke/radius ≈ 20%), matching
/// the proportions before the dot was enlarged in commit 31d99f0.
const PROHIBIT_ICON_RADIUS: f32 = 16.0;
/// Minimum dot brightness — always visible.
const DOT_MIN_BRIGHTNESS: f32 = 0.5;
/// Transparent gap (pixels) between red dot edge and spectrogram.
const DOT_GAP: f32 = 2.0;

/// Left edge of the spectrogram area (inside border margin).
const SPEC_LEFT: usize = 4;
/// Top edge of the spectrogram area (padding from badge top).
const SPEC_TOP: usize = 4;
/// Right edge of the spectrogram area (inside border margin).
const SPEC_RIGHT: usize = 269;
/// Bottom edge of the spectrogram area (padding from badge bottom).
const SPEC_BOTTOM: usize = 48;
/// Spectrogram width in pixels (time columns).
const SPEC_W: usize = SPEC_RIGHT - SPEC_LEFT;
/// Spectrogram height in pixels (frequency rows).
const SPEC_H: usize = SPEC_BOTTOM - SPEC_TOP;

/// Target frames per second for the recording render loop.
const FPS: u32 = 60;

/// How many render frames elapse between two waterfall column pushes.
///
/// The render loop still runs at [`FPS`] — the red dot pulse, border,
/// and text all update every frame — but the spectrogram history is
/// only appended every `COLUMN_PERIOD_FRAMES` frames.  This decouples
/// the waterfall's *temporal* resolution from the render rate without
/// sacrificing animation smoothness.
///
/// At 60 fps with `COLUMN_PERIOD_FRAMES = 2` the waterfall advances
/// 30 columns/sec, giving a visible window of roughly
/// `SPEC_W / 30 ≈ 8.8` seconds across the 265-pixel spectrogram area.
const COLUMN_PERIOD_FRAMES: u32 = 2;

// ── Centered "no sound" overlay constants ────────────────────────────

/// Height of the centered overlay as a fraction of monitor height (5%).
const CENTERED_HEIGHT_FRACTION: f32 = 0.05;
/// Minimum height for the centered overlay (pixels).
const CENTERED_MIN_HEIGHT: u16 = 50;
/// Aspect ratio (width / height) for the centered overlay.
const CENTERED_ASPECT_RATIO: f32 = 5.0;
/// Corner radius for the centered overlay (pixels).
const CENTERED_CORNER_RADIUS: usize = 16;
/// Background colour for the centered overlay with ARGB visual: 80% opaque black.
const CENTERED_BG_ARGB: [u8; 4] = [0x00, 0x00, 0x00, 0xCC];
/// Background colour for the centered overlay without ARGB visual: solid black.
const CENTERED_BG_OPAQUE: [u8; 4] = [0x00, 0x00, 0x00, 0xFF];

/// Opacity multiplier applied to the waterfall (and sibling visualizers)
/// while auto-pause is active.  The graph keeps scrolling at the same
/// rate but is rendered dimmer, leaving the `LISTENING` indicator and
/// pause icon on top at full brightness.
const DIM_FACTOR_PAUSED: f32 = 0.3;

/// Wall-clock interval between time-grid marks drawn over the
/// waterfall.  One mark per second gives ~9 visible marks across the
/// current `SPEC_W` at the slowed column rate — enough to read "how
/// long ago did that happen" at a glance without crowding.
///
/// Grid marks behave just like any other event overlaid on the
/// waterfall time axis: they appear at the right edge when emitted
/// and scroll left with the audio columns they were emitted next to.
const GRID_PERIOD_SECONDS: u64 = 1;

/// Columns between two consecutive grid marks.  At 60 fps with
/// `COLUMN_PERIOD_FRAMES = 2` the waterfall advances 30 cols/sec,
/// so `GRID_PERIOD_SECONDS = 1` ⇒ one mark every 30 columns.
const COLUMNS_PER_GRID_MARK: u64 = (FPS as u64 / COLUMN_PERIOD_FRAMES as u64) * GRID_PERIOD_SECONDS;

/// Alpha-blend factor for time-grid dots.  Each drawn grid pixel is
/// `(existing * (1 - GRID_BLEND_ALPHA) + yellow * GRID_BLEND_ALPHA)`,
/// giving a visible time reference without washing out the waterfall
/// content underneath.  Bumped to 0.6 after 0.3 proved too subtle to
/// read at a glance against the full-brightness spectrogram.
const GRID_BLEND_ALPHA: f32 = 0.6;

/// Initial effective frequency ceiling; grows as higher harmonics appear.
const FREQ_INITIAL_MAX: f32 = 320.0;

// ── Colors (BGRA for little-endian ZPixmap, depth 24/32) ────────────

/// Badge background: opaque black.
const BG_COLOR: [u8; 4] = [0x00, 0x00, 0x00, 0xFF];

/// Border colour: medium gray, fully opaque (BGRA).
const BORDER_COLOR: [u8; 4] = [0x88, 0x88, 0x88, 0xFF];
/// Border width in pixels.
const BORDER_WIDTH: f32 = 2.0;

// ── Public types ─────────────────────────────────────────────────────

/// Which indicator to display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndicatorKind {
    /// Red badge shown during audio recording (dynamic spectrogram).
    Recording,
    /// Blue badge shown during transcription (static PNG).
    Transcribing,
    /// Badge shown while the local speech model is downloading.
    ///
    /// Rendered as a static "DOWNLOADING MODEL" text badge using the
    /// same mechanism as [`IndicatorKind::Transcribing`] — the
    /// recording-loop render path with a dimmed
    /// waterfall/amplitude/spectrum background and a static text
    /// overlay on top.  The three states (Recording, Transcribing,
    /// DownloadingModel) are mutually exclusive.
    DownloadingModel,
}

/// Commands sent from the main thread to the overlay thread.
enum Command {
    Show(IndicatorKind),
    Hide,
    Quit,
}

/// Handle to the overlay background thread.
///
/// Sending [`show`](OverlayHandle::show) or [`hide`](OverlayHandle::hide)
/// controls the X11 window from any thread. The overlay is destroyed
/// when this handle is dropped.
pub struct OverlayHandle {
    tx: mpsc::Sender<Command>,
    thread: Option<std::thread::JoinHandle<()>>,
    /// Set to `true` by the overlay thread whenever it sees audio with
    /// variance above the dead-signal threshold.  Stays `false` when
    /// the recording was entirely dead signal (no live audio).
    had_live_audio: Arc<std::sync::atomic::AtomicBool>,
}

impl OverlayHandle {
    /// Spawn the overlay thread and open an X11 connection.
    ///
    /// * `viz` — visualizer mode to render inside the badge (or `None`
    ///   for a plain badge with only the red dot).
    /// * `mono` — use monochrome colours (theme-aware).
    /// * `audio_ring` — shared ring buffer fed by the audio tee task.
    /// * `sample_rate` — capture sample rate (for FFT/RMS sizing).
    /// * `silence_tx` — optional channel to notify when silence is
    ///   detected (`true`) or audio returns (`false`).
    /// * `pause_flag` — shared atomic flag; the overlay sets it to
    ///   `true` when auto-pause triggers (silence during recording)
    ///   and clears it when speech resumes.
    ///
    /// Monitor geometry is queried via GDK4 **before** spawning the
    /// thread (GDK must be called from the main thread) and passed in.
    ///
    /// Returns `Err` if the X11 display cannot be opened.
    #[allow(clippy::too_many_arguments)] // Overlay threading inherently needs many params
    pub fn new(
        viz: Option<crate::config::VizMode>,
        mono: bool,
        audio_ring: Arc<Mutex<RingBuffer>>,
        sample_rate: u32,
        silence_tx: Option<std::sync::mpsc::Sender<bool>>,
        pause_flag: Arc<std::sync::atomic::AtomicBool>,
        auto_pause: bool,
        telemetry_rx: Option<tokio::sync::broadcast::Receiver<TranscriptionEvent>>,
    ) -> Result<Self, TalkError> {
        let geom = super::monitor::primary_monitor_geometry()?;

        // Resolve monochrome palette up front (D-Bus on main thread).
        let mono_palette = if mono {
            let (fg, bg) = super::render_util::monochrome_palette();
            log::info!("monochrome overlay: fg={:?} bg={:?}", fg, bg);
            Some((fg, bg))
        } else {
            None
        };

        let (tx, rx) = mpsc::channel();

        let had_live_audio = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let had_live_audio_clone = Arc::clone(&had_live_audio);

        let thread = std::thread::Builder::new()
            .name("overlay".into())
            .spawn(move || {
                if let Err(e) = overlay_thread(
                    rx,
                    geom,
                    viz,
                    mono_palette,
                    audio_ring,
                    sample_rate,
                    silence_tx,
                    pause_flag,
                    auto_pause,
                    telemetry_rx,
                    had_live_audio_clone,
                ) {
                    log::error!("overlay thread error: {}", e);
                }
            })
            .map_err(|e| TalkError::Audio(format!("failed to spawn overlay thread: {}", e)))?;

        Ok(Self {
            tx,
            thread: Some(thread),
            had_live_audio,
        })
    }

    /// Display the indicator badge.
    pub fn show(&self, kind: IndicatorKind) {
        let _ = self.tx.send(Command::Show(kind));
    }

    /// Hide the indicator badge.
    pub fn hide(&self) {
        let _ = self.tx.send(Command::Hide);
    }

    /// Whether any frame with real audio variance was seen during the
    /// current recording session.  Returns `false` when the mic was
    /// dead the entire time (dead signal only).
    pub fn had_live_audio(&self) -> bool {
        self.had_live_audio
            .load(std::sync::atomic::Ordering::Relaxed)
    }
}

impl Drop for OverlayHandle {
    fn drop(&mut self) {
        let _ = self.tx.send(Command::Quit);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

// ── PNG decoding ─────────────────────────────────────────────────────

/// Decoded RGBA image.
struct RgbaImage {
    width: u32,
    height: u32,
    /// Row-major RGBA pixels (4 bytes per pixel).
    data: Vec<u8>,
}

/// Return `true` when `samples` carry the "stuck at the rail"
/// signature of a dead / disconnected audio device: a perfectly
/// constant frame (max−min within `flat_eps`) pinned near the i16 rail
/// (peak magnitude at or above `rail_floor`).
///
/// Samples are normalized f32 in `[-1.0, 1.0]` (i16 / 32768), so a
/// disconnected device that emits constant `i16::MIN` (-32768) appears
/// here as constant `-1.0`.
///
/// Crucially, benign silence is NOT flagged: a constant-zero frame
/// (e.g. the exact-zero digital silence a Bluetooth HFP mic emits
/// between speech) is flat but far below `rail_floor`, so it returns
/// `false`.  An empty slice returns `false`.
fn is_stuck_at_rail(samples: &[f32], rail_floor: f32, flat_eps: f32) -> bool {
    if samples.is_empty() {
        return false;
    }
    let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
    for &s in samples {
        if s < lo {
            lo = s;
        }
        if s > hi {
            hi = s;
        }
    }
    let flat = (hi - lo) <= flat_eps;
    let near_rail = lo.abs().max(hi.abs()) >= rail_floor;
    flat && near_rail
}

/// Decode an embedded PNG into RGBA pixels.
fn decode_png(bytes: &[u8]) -> Result<RgbaImage, TalkError> {
    let decoder = png::Decoder::new(bytes);
    let mut reader = decoder
        .read_info()
        .map_err(|e| TalkError::Config(format!("failed to read PNG header: {}", e)))?;

    let mut buf = vec![0u8; reader.output_buffer_size()];
    let info = reader
        .next_frame(&mut buf)
        .map_err(|e| TalkError::Config(format!("failed to decode PNG frame: {}", e)))?;

    let data = match info.color_type {
        png::ColorType::Rgba => buf[..info.buffer_size()].to_vec(),
        png::ColorType::Rgb => {
            let rgb = &buf[..info.buffer_size()];
            let mut rgba = Vec::with_capacity(info.width as usize * info.height as usize * 4);
            for chunk in rgb.chunks_exact(3) {
                rgba.extend_from_slice(chunk);
                rgba.push(255);
            }
            rgba
        }
        other => {
            return Err(TalkError::Config(format!(
                "unsupported PNG color type: {:?}",
                other
            )));
        }
    };

    Ok(RgbaImage {
        width: info.width,
        height: info.height,
        data,
    })
}

/// Render the spectrogram waterfall into the pixel buffer.
///
/// `history` holds the most recent columns of spectral data (each a
/// `Vec<f32>` of length `SPEC_H`).  Newer columns are at the end.
/// The spectrogram is right-aligned: the newest column draws at the
/// right edge of the area, oldest on the left.
///
/// `dim` scales each pixel's visible intensity.  Pass `1.0` for the
/// normal render, `DIM_FACTOR_PAUSED` during auto-pause to render a
/// dimmed (30 % brightness) waterfall behind the `LISTENING` indicator.
/// Out-of-range values are clamped to `[0.0, 1.0]`.
#[allow(clippy::too_many_arguments)]
fn render_spectrogram(
    pb: &mut PixelBuffer,
    history: &[Vec<f32>],
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
    peak: f32,
    mono: Option<([u8; 4], [u8; 4])>,
    dim: f32,
) {
    if history.is_empty() || peak < PEAK_FLOOR {
        return;
    }

    let dim = dim.clamp(0.0, 1.0);

    let n = history.len();
    let start = n.saturating_sub(w);
    let num_cols = n - start;

    for (col_idx, column) in history[start..].iter().enumerate() {
        // Right-aligned: newest column at the right edge.
        let x = x0 + w - num_cols + col_idx;

        for (row_idx, &magnitude) in column.iter().enumerate() {
            // row 0 = low freq = bottom of area
            if row_idx >= h {
                break;
            }
            let y = y0 + h - 1 - row_idx;

            let norm = (magnitude / peak).clamp(0.0, 1.0);
            // Log scale for better visual contrast.
            let brightness = if norm > 0.0 {
                (1.0 + norm * 9.0).log10() // maps 0..1 → 0..1
            } else {
                0.0
            };

            let mut color = if mono.is_some() {
                // Premultiplied alpha: white × brightness × dim.
                let alpha = (brightness * 255.0 * dim) as u8;
                [alpha, alpha, alpha, alpha]
            } else {
                let c = super::render_util::heat_map_color(norm, brightness);
                [
                    (c[0] as f32 * dim) as u8,
                    (c[1] as f32 * dim) as u8,
                    (c[2] as f32 * dim) as u8,
                    c[3],
                ]
            };
            // Keep pixel fully opaque over the black background.
            color[3] = 0xFF;
            pb.set_pixel(x, y, color);
        }
    }
}

/// Render amplitude history inside a sub-region of the badge.
///
/// Draws symmetric bars around the vertical centre, scrolling left
/// (newest at right edge).  Uses premultiplied alpha white (like the
/// waterfall), or monochrome palette if provided.
///
/// `dim` scales each pixel's visible intensity (see
/// [`render_spectrogram`] for the rationale).
#[allow(clippy::too_many_arguments)]
fn render_amplitude_badge(
    pb: &mut PixelBuffer,
    history: &[f32],
    max_rms: f32,
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
    mono: Option<([u8; 4], [u8; 4])>,
    dim: f32,
) {
    if history.is_empty() || max_rms < PEAK_FLOOR {
        return;
    }

    let dim = dim.clamp(0.0, 1.0);

    let n = history.len();
    let center_y = y0 + h / 2;
    let max_half = (h / 2).saturating_sub(1);

    for col in 0..w {
        let start = col * n / w;
        let end = ((col + 1) * n / w).max(start + 1).min(n);

        let avg_rms = if end > start {
            history[start..end].iter().sum::<f32>() / (end - start) as f32
        } else if start < n {
            history[start]
        } else {
            0.0
        };

        let norm = (avg_rms / max_rms).clamp(0.0, 1.0);
        let half_height = (norm * max_half as f32) as usize;

        let base = if let Some((fg, bg)) = mono {
            super::render_util::lerp_color(bg, fg, norm)
        } else {
            super::render_util::level_color(norm)
        };
        let color = [
            (base[0] as f32 * dim) as u8,
            (base[1] as f32 * dim) as u8,
            (base[2] as f32 * dim) as u8,
            base[3],
        ];

        let top = center_y.saturating_sub(half_height);
        let bottom = center_y + half_height;
        for y in top..=bottom.min(y0 + h - 1) {
            pb.set_pixel(x0 + col, y, color);
        }
    }
}

/// Render spectrum bars inside a sub-region of the badge.
///
/// Bars grow upward from the bottom edge.  Uses premultiplied alpha
/// white (like the waterfall), or monochrome palette if provided.
///
/// `dim` scales each pixel's visible intensity (see
/// [`render_spectrogram`] for the rationale).
#[allow(clippy::too_many_arguments)]
fn render_spectrum_badge(
    pb: &mut PixelBuffer,
    magnitudes: &[f32],
    peak: f32,
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
    mono: Option<([u8; 4], [u8; 4])>,
    dim: f32,
) {
    if magnitudes.is_empty() || peak < PEAK_FLOOR {
        return;
    }

    let dim = dim.clamp(0.0, 1.0);

    // Use lower quarter of spectrum (voice content).
    let useful = &magnitudes[..magnitudes.len() / 4];

    let num_bars = w; // one bar per pixel column — no gaps
    if num_bars == 0 || useful.is_empty() {
        return;
    }

    for bar in 0..num_bars {
        // Proportional mapping: distribute ALL bins across bars evenly.
        let start = bar * useful.len() / num_bars;
        let end = ((bar + 1) * useful.len() / num_bars).max(start + 1);

        let avg = if end > start {
            useful[start..end].iter().sum::<f32>() / (end - start) as f32
        } else {
            0.0
        };

        let norm = (avg / peak).clamp(0.0, 1.0);
        let log_norm = (1.0 + norm * 9.0).log10();

        let bar_height = (log_norm * (h.saturating_sub(4)) as f32) as usize;
        let bar_x = x0 + bar;
        let bar_y = y0 + h - 2 - bar_height;

        let base = if let Some((fg, bg)) = mono {
            super::render_util::lerp_color(bg, fg, log_norm)
        } else {
            super::render_util::level_color(log_norm)
        };
        let color = [
            (base[0] as f32 * dim) as u8,
            (base[1] as f32 * dim) as u8,
            (base[2] as f32 * dim) as u8,
            base[3],
        ];

        for dy in 0..bar_height {
            pb.set_pixel(bar_x, bar_y + dy, color);
        }
    }
}

/// Draw the time grid: vertical dotted yellow lines over the
/// spectrogram area, one line per [`GRID_PERIOD_SECONDS`]
/// wall-clock second, alpha-blended with the existing pixel
/// contents so they remain visible through whatever's underneath.
///
/// # Model
///
/// Grid marks behave exactly like any other event on the waterfall
/// time axis — when a new column is pushed whose absolute index
/// (since the last history reset) is a multiple of
/// [`COLUMNS_PER_GRID_MARK`], that column becomes a grid column.
/// As the history scrolls left, the grid columns scroll with it
/// automatically because their position in the visible window is
/// determined by the absolute index rather than by a fixed screen
/// coordinate.
///
/// # Arguments
///
/// * `first_visible_abs_idx` — the absolute column index of the
///   oldest column currently in the spectrogram history
///   (`columns_pushed_total - spectrogram_history.len() as u64`).
///   Used so the caller does not need to know how to compute the
///   right-alignment offset.
/// * `num_visible_cols` — number of columns currently held in the
///   spectrogram history (`spectrogram_history.len()`).  The grid
///   function uses this to right-align the grid marks exactly the
///   same way [`render_spectrogram`] right-aligns the waterfall.
///
/// # Drawing
///
/// Each grid mark is a column of 1-pixel yellow dots spaced by
/// 1 pixel gaps (dot at y=0, empty at y=1, dot at y=2, …).  Each
/// dot alpha-blends [`GRID_BLEND_ALPHA`] of pure yellow
/// `(255, 255, 0)` with the existing pixel colour, preserving
/// whatever waterfall content was there underneath at 70 % strength.
#[allow(clippy::too_many_arguments)]
fn render_time_grid(
    pb: &mut PixelBuffer,
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
    first_visible_abs_idx: u64,
    num_visible_cols: usize,
    columns_per_mark: u64,
) {
    if num_visible_cols == 0 || columns_per_mark == 0 || w == 0 || h == 0 {
        return;
    }

    let num = num_visible_cols.min(w);
    let inv_alpha = 1.0 - GRID_BLEND_ALPHA;

    // Pure yellow in BGRA byte order (little-endian ZPixmap): B=0,
    // G=255, R=255, alpha doesn't participate in the blend because
    // we always leave the destination alpha untouched.
    const YELLOW_B: f32 = 0.0;
    const YELLOW_G: f32 = 255.0;
    const YELLOW_R: f32 = 255.0;

    for col_idx in 0..num {
        let abs_idx = first_visible_abs_idx + col_idx as u64;
        if !abs_idx.is_multiple_of(columns_per_mark) {
            continue;
        }

        // Right-align: the newest column of the history always sits
        // at `x0 + w - 1`, the oldest at `x0 + w - num`.
        let x = x0 + w - num + col_idx;
        if x >= pb.width {
            continue;
        }

        // 1 px dot, 1 px gap, starting at the top of the spec area.
        let mut row = 0usize;
        while row < h {
            let y = y0 + row;
            if y < pb.height {
                let off = (y * pb.width + x) * 4;
                // Read existing BGR, alpha-blend with yellow, write
                // back.  Leave the destination alpha byte untouched
                // so the pixel stays opaque relative to whatever
                // shape mask the window uses.
                let b = pb.data[off] as f32;
                let g = pb.data[off + 1] as f32;
                let r = pb.data[off + 2] as f32;
                pb.data[off] = (b * inv_alpha + YELLOW_B * GRID_BLEND_ALPHA) as u8;
                pb.data[off + 1] = (g * inv_alpha + YELLOW_G * GRID_BLEND_ALPHA) as u8;
                pb.data[off + 2] = (r * inv_alpha + YELLOW_R * GRID_BLEND_ALPHA) as u8;
            }
            // Dot (row even) + skip (row odd): advance 2 rows per
            // dot so we get the 1-on-1-off dotted pattern.
            row += 2;
        }
    }
}

// ── Phase layer rendering ───────────────────────────────────────────

/// Network transcription phase as derived from [`TranscriptionEvent`]s.
///
/// The overlay maintains a simple state machine driven by events
/// arriving from the telemetry broker.  Each variant maps to a
/// distinct colour (and opacity) in the phase overlay layer drawn
/// above the waterfall.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
    /// No HTTP activity in progress.
    Idle,
    /// `PreflightStarted` received — `/v1/models` validation in
    /// flight.  Visually distinct from the actual transcription
    /// connection: same green as [`Self::Done`] but at half
    /// opacity, so the user knows we're not yet doing the real
    /// transcription work.
    Validating,
    /// `RequestStarted` received, waiting for first byte pull.
    Connecting,
    /// `ConnectionEstablished` received, body bytes flowing.
    Uploading,
    /// `UploadComplete` received, waiting for response headers.
    WaitingResponse,
    /// `ResponseHeaders` received, body arriving / JSON parsing.
    Receiving,
    /// `RetryScheduled { kind: Data }` received — the provider
    /// answered "busy" (5xx / 429) and the transport is sleeping
    /// out a backoff before the next attempt.  Amber like
    /// [`Self::WaitingResponse`] ("the server's turn"), but the
    /// stripe is drawn as a draining bar (see
    /// [`render_backoff_bar`]) so a two-minute wait reads as
    /// timed, not hung.  Leaves on the next `RequestStarted`.
    WaitingRetry,
    /// `RequestCompleted { success: true }` received.
    Done,
    /// `RequestCompleted { success: false }` received.
    Error,
}

/// Reuseable BGRA constant for the "transcription succeeded /
/// validation in progress" green so [`Phase::color`] cannot drift
/// between the two variants by accident.
const PHASE_GREEN: [u8; 4] = [110, 255, 60, 255]; // RGB(60,255,110)

/// Amber shared by the two "waiting on the provider" phases so the
/// hue keeps one meaning: [`Phase::WaitingResponse`] (request sent,
/// answer pending) and [`Phase::WaitingRetry`] (provider said busy,
/// backoff running).  RGB(255,180,50) → BGRA.
const PHASE_AMBER: [u8; 4] = [50, 180, 255, 255];

/// Opacity of the [`Phase::WaitingRetry`] history stripe.  The
/// per-column trail records "the provider was busy for this long"
/// dimly, while the live countdown band ([`render_backoff_bar`]) is
/// drawn at full opacity on top — the contrast between the two is
/// what makes the drain readable.
const BACKOFF_TRAIL_OPACITY: f32 = 0.35;

/// Opacity used by [`Phase::Validating`] for both its phase-line
/// stripe and the retry counter overlay.  At 0.5 the validation
/// state is visibly in-progress without blending into the
/// transcription colours of subsequent phases.
const VALIDATING_OPACITY: f32 = 0.5;

impl Phase {
    /// BGRA colour and opacity for this phase, or `None` for
    /// `Idle` (nothing drawn).  Colours are chosen to stand out
    /// against the monochrome waterfall without being garish.
    /// Opacity is `1.0` for every phase except [`Self::Validating`]
    /// (`0.5`) — see [`VALIDATING_OPACITY`] for rationale.
    fn color(self) -> Option<([u8; 4], f32)> {
        match self {
            Self::Idle => None,
            Self::Validating => Some((PHASE_GREEN, VALIDATING_OPACITY)),
            // dim blue  RGB(80,130,200) → BGRA
            Self::Connecting => Some(([200, 130, 80, 255], 1.0)),
            // bright blue  RGB(60,170,255)
            Self::Uploading => Some(([255, 170, 60, 255], 1.0)),
            // amber  RGB(255,180,50)
            Self::WaitingResponse => Some((PHASE_AMBER, 1.0)),
            Self::WaitingRetry => Some((PHASE_AMBER, BACKOFF_TRAIL_OPACITY)),
            // teal  RGB(60,200,180)
            Self::Receiving => Some(([180, 200, 60, 255], 1.0)),
            // green  RGB(60,255,110)
            Self::Done => Some((PHASE_GREEN, 1.0)),
            // red  RGB(200,40,40)
            Self::Error => Some(([40, 40, 200, 255], 1.0)),
        }
    }

    /// Opacity component of [`Self::color`], or `1.0` when the
    /// phase has no colour (i.e. `Idle`).  Used by overlay
    /// elements like the retry counter that should match the
    /// phase line's dimming during validation.
    fn opacity(self) -> f32 {
        self.color().map(|(_, op)| op).unwrap_or(1.0)
    }

    /// Advance the state machine given a telemetry event.
    fn advance(self, event: &TranscriptionEvent) -> Self {
        match event {
            // Preflight (validate-cache miss path).
            TranscriptionEvent::PreflightStarted { .. } => Self::Validating,
            TranscriptionEvent::PreflightCompleted { success: true, .. } => {
                // Successful preflight — wait for the real
                // transcription request to start.  The next event
                // will normally be `RequestStarted` which advances
                // us to `Connecting`.  Until then, drop back to
                // `Idle` so the phase stripe doesn't keep
                // emitting green-50%.
                Self::Idle
            }
            TranscriptionEvent::PreflightCompleted { success: false, .. } => Self::Error,
            // Transcription request lifecycle.
            TranscriptionEvent::RequestStarted { .. } => Self::Connecting,
            TranscriptionEvent::ConnectionEstablished { .. } => Self::Uploading,
            TranscriptionEvent::UploadComplete { .. } => Self::WaitingResponse,
            TranscriptionEvent::ResponseHeaders { .. } => Self::Receiving,
            TranscriptionEvent::RequestCompleted { success: true, .. } => Self::Done,
            TranscriptionEvent::RequestCompleted { success: false, .. } => Self::Error,
            // A retry inside the validate path (where `self` is
            // `Validating`) stays in `Validating` so the stripe
            // remains dimmed.  Otherwise a connection retry drops
            // back to `Connecting` (a new attempt fires at once),
            // while a data retry — provider busy, backoff running —
            // enters `WaitingRetry` until the next `RequestStarted`.
            TranscriptionEvent::RetryScheduled { kind, .. } => match (self, kind) {
                (Self::Validating, _) => Self::Validating,
                (_, crate::telemetry::RetryKind::Data) => Self::WaitingRetry,
                (_, crate::telemetry::RetryKind::Connection) => Self::Connecting,
            },
            TranscriptionEvent::PasteStarted { .. } => Self::Done, // green during paste
            TranscriptionEvent::Done { .. } | TranscriptionEvent::PasteCompleted { .. } => {
                Self::Idle
            }
            TranscriptionEvent::Failed { .. } => Self::Error,
            // Upload/download progress don't change the phase.
            _ => self,
        }
    }
}

/// Height of the phase colour line drawn at the top of the spec area.
const PHASE_LINE_HEIGHT: usize = 2;

/// Render the phase overlay: a thin horizontal colour band at the
/// top of the spectrogram area, one colour per column, right-aligned
/// in the same way as the waterfall.
///
/// Each entry in `phase_history` is `Some((color, opacity))` for a
/// column we want stripped, or `None` for columns where nothing
/// should be drawn.  Columns at full opacity overwrite the
/// underlying pixel; sub-1.0 columns alpha-blend into whatever
/// waterfall content was there underneath, which makes the
/// half-opacity validation stripe visibly translucent rather than
/// hiding the spectrogram entirely.
fn render_phase_line(
    pb: &mut PixelBuffer,
    x0: usize,
    y0: usize,
    w: usize,
    phase_history: &[Option<([u8; 4], f32)>],
) {
    let n = phase_history.len();
    if n == 0 || w == 0 {
        return;
    }

    let num = n.min(w);

    for col_idx in 0..num {
        let (color, opacity) = match phase_history[n - num + col_idx] {
            Some(t) => t,
            None => continue,
        };

        // Right-align: newest column at `x0 + w - 1`.
        let x = x0 + w - num + col_idx;
        if x >= pb.width {
            continue;
        }

        for dy in 0..PHASE_LINE_HEIGHT {
            let y = y0 + dy;
            if y >= pb.height {
                continue;
            }
            // Use the cheap direct path for full opacity (the
            // common case), and the blend path when the phase
            // explicitly asks for translucency.  A `1.0` opacity
            // through `blend_pixel` is equivalent but pays an
            // unnecessary float multiplication per pixel.
            if opacity >= 1.0 {
                pb.set_pixel(x, y, color);
            } else {
                pb.blend_pixel(x, y, color, opacity);
            }
        }
    }
}

/// Fraction of a backoff wait still remaining at `now`, linear in
/// elapsed time: `1.0` when the wait starts, `0.0` once `delay` has
/// elapsed, clamped to `[0, 1]` (never negative when the render loop
/// outlives the wait by a frame or two).  A zero `delay` — the
/// connection-retry case — has nothing to drain and yields `0.0`.
fn backoff_remaining_fraction(
    now: std::time::Instant,
    started: std::time::Instant,
    delay: std::time::Duration,
) -> f32 {
    if delay.is_zero() {
        return 0.0;
    }
    let elapsed = now.saturating_duration_since(started).as_secs_f32();
    (1.0 - elapsed / delay.as_secs_f32()).clamp(0.0, 1.0)
}

/// Render the backoff countdown as a solid amber band over the
/// phase-line row: `fraction * w` pixels wide, anchored at the left
/// edge of the spec area and `PHASE_LINE_HEIGHT` tall, so it drains
/// right-to-left as the wait elapses.
///
/// Drawn AFTER [`render_phase_line`], on top of it: the scrolling
/// per-column history underneath still records amber for every
/// column pushed during the wait (so the timeline shows how long the
/// provider stayed busy), while the band on top gives the live
/// "how much longer" reading.
fn render_backoff_bar(pb: &mut PixelBuffer, x0: usize, y0: usize, w: usize, fraction: f32) {
    let filled = (w as f32 * fraction.clamp(0.0, 1.0)).round() as usize;
    if filled == 0 {
        return;
    }
    pb.fill_rect(x0, y0, filled.min(w), PHASE_LINE_HEIGHT, PHASE_AMBER);
}

/// Centre badge text shown while a server backoff runs.  Names the
/// cause ("busy" — it is the provider, not the user's setup) and the
/// progress through the server-retry budget.
fn backoff_badge_label(attempt: u32, max: u32) -> String {
    format!("BUSY · RETRY {}/{}", attempt, max)
}

/// Render the backoff badge text in amber, centred in the SPEC area
/// (same path as `TRANSCRIBING` / `LISTENING`).  `retry` is the
/// `(attempt, max)` pair from the last `RetryScheduled`.
fn render_backoff_text(
    pb: &mut PixelBuffer,
    font: &fontdue::Font,
    retry: (u32, u32),
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
) {
    let label = backoff_badge_label(retry.0, retry.1);
    render_badge_text(pb, font, &label, PHASE_AMBER, x0, y0, w, h);
}

/// Pixel budget for each individual throughput track.  Each of the
/// three tracks (upload, download, paste) gets its own 16 px with
/// its own independent scale — a 100 KB upload and a 1 KB download
/// both fill their 16 px when they hit their respective peaks.
const TRACK_HEIGHT_PX: usize = 16;

/// Render the three throughput tracks (Layer 3b).
///
/// Each track has its own 16 px budget and its own scale (normalised
/// against its own peak delta).  This avoids the problem where a
/// ~100 KB upload dwarfs a ~1 KB JSON response into invisibility.
///
/// Layout (all right-aligned on the same column x positions):
///   - **Upload**: grows DOWN from `y0 + PHASE_LINE_HEIGHT` (top)
///   - **Download**: grows UP from `y0 + h - 1` (bottom)
///   - **Paste**: centred at `y0 + h / 2` (middle)
#[allow(clippy::too_many_arguments)]
fn render_throughput_tracks(
    pb: &mut PixelBuffer,
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
    upload_history: &[u64],
    download_history: &[u64],
    paste_history: &[u64],
    _phase_history: &[Option<([u8; 4], f32)>],
    upload_peak: u64,
    download_peak: u64,
    paste_peak: u64,
) {
    if w == 0 || h == 0 {
        return;
    }

    let num = upload_history
        .len()
        .min(download_history.len())
        .min(paste_history.len())
        .min(w);
    if num == 0 {
        return;
    }

    let track_h = TRACK_HEIGHT_PX.min(h / 3) as f32;
    let bar_zone_top = y0 + PHASE_LINE_HEIGHT;
    let bar_zone_bottom = y0 + h - 1;
    let bar_zone_center = y0 + h / 2;

    // Throughput tracks always render at full opacity regardless of
    // the per-column phase opacity, so we drop the opacity component
    // and keep just the BGRA tuple.
    let upload_color: [u8; 4] = Phase::Uploading
        .color()
        .map(|(c, _)| c)
        .unwrap_or([255, 170, 60, 255]);
    let download_color: [u8; 4] = Phase::Receiving
        .color()
        .map(|(c, _)| c)
        .unwrap_or([180, 200, 60, 255]);
    let paste_color: [u8; 4] = Phase::Done
        .color()
        .map(|(c, _)| c)
        .unwrap_or([110, 255, 60, 255]);

    for col_idx in 0..num {
        let x = x0 + w - num + col_idx;
        if x >= pb.width {
            continue;
        }

        let ui = upload_history.len() - num + col_idx;
        let di = download_history.len() - num + col_idx;
        let pi = paste_history.len() - num + col_idx;

        // ── Upload: own scale, grow DOWN from top ──
        if upload_history[ui] > 0 && upload_peak > 0 {
            let norm = (upload_history[ui] as f32 / upload_peak as f32).clamp(0.0, 1.0);
            let bar_h = ((norm * track_h) as usize).max(1);
            for dy in 0..bar_h {
                let y = bar_zone_top + dy;
                if y >= pb.height || y > bar_zone_bottom {
                    break;
                }
                pb.set_pixel(x, y, upload_color);
            }
        }

        // ── Download: own scale, grow UP from bottom ──
        if download_history[di] > 0 && download_peak > 0 {
            let norm = (download_history[di] as f32 / download_peak as f32).clamp(0.0, 1.0);
            let bar_h = ((norm * track_h) as usize).max(1);
            for dy in 0..bar_h {
                let y = bar_zone_bottom.saturating_sub(dy);
                if y < y0 || y < bar_zone_top {
                    break;
                }
                pb.set_pixel(x, y, download_color);
            }
        }

        // ── Paste: own scale, centred in middle ──
        if paste_history[pi] > 0 && paste_peak > 0 {
            let norm = (paste_history[pi] as f32 / paste_peak as f32).clamp(0.0, 1.0);
            let bar_h = ((norm * track_h) as usize).max(1);
            let half = bar_h / 2;
            for dy in 0..bar_h {
                let y = bar_zone_center.saturating_sub(half) + dy;
                if y >= pb.height || y > bar_zone_bottom || y < bar_zone_top {
                    continue;
                }
                pb.set_pixel(x, y, paste_color);
            }
        }
    }
}

/// Draw the red dot with brightness driven by current volume level.
/// Clear a circle to `BG_COLOR` (transparent), creating a gap between
/// the red dot and the spectrogram underneath.
fn clear_dot_gap(pb: &mut PixelBuffer, cx: usize, cy: usize, outer_radius: f32) {
    let r_sq = outer_radius * outer_radius;
    let r_int = outer_radius.ceil() as usize;

    for dy in 0..=r_int {
        for dx in 0..=r_int {
            let dist_sq = (dx * dx + dy * dy) as f32;
            if dist_sq > r_sq {
                continue;
            }
            // Anti-aliased edge: fade to transparent over 1 px.
            let edge_dist = outer_radius - dist_sq.sqrt();
            let edge_alpha = edge_dist.clamp(0.0, 1.0);

            let coords: [(usize, usize); 4] = [
                (cx + dx, cy + dy),
                (cx.wrapping_sub(dx), cy + dy),
                (cx + dx, cy.wrapping_sub(dy)),
                (cx.wrapping_sub(dx), cy.wrapping_sub(dy)),
            ];
            for (px, py) in coords {
                if px < pb.width && py < pb.height {
                    if edge_alpha >= 1.0 {
                        pb.set_pixel(px, py, BG_COLOR);
                    } else {
                        // Blend existing pixel towards transparent.
                        let off = (py * pb.width + px) * 4;
                        let keep = 1.0 - edge_alpha;
                        pb.data[off] = (pb.data[off] as f32 * keep) as u8;
                        pb.data[off + 1] = (pb.data[off + 1] as f32 * keep) as u8;
                        pb.data[off + 2] = (pb.data[off + 2] as f32 * keep) as u8;
                        pb.data[off + 3] = (pb.data[off + 3] as f32 * keep) as u8;
                    }
                }
            }
        }
    }
}

fn draw_pulsing_dot(pb: &mut PixelBuffer, cx: usize, cy: usize, radius: f32, brightness: f32) {
    let r_sq = radius * radius;
    let r_int = radius.ceil() as usize;
    let brightness = brightness.clamp(DOT_MIN_BRIGHTNESS, 1.0);

    for dy in 0..=r_int {
        for dx in 0..=r_int {
            let dist_sq = (dx * dx + dy * dy) as f32;
            if dist_sq > r_sq {
                continue;
            }

            // Anti-aliasing at the edge: smooth falloff over 1px.
            let edge_dist = radius - dist_sq.sqrt();
            let edge_alpha = edge_dist.clamp(0.0, 1.0);

            // BGRA with true alpha for compositor transparency.
            let val = (255.0 * brightness * edge_alpha) as u8;
            let color = [0x00, 0x00, val, val];

            // Draw in all four quadrants.
            let coords: [(usize, usize); 4] = [
                (cx + dx, cy + dy),
                (cx.wrapping_sub(dx), cy + dy),
                (cx + dx, cy.wrapping_sub(dy)),
                (cx.wrapping_sub(dx), cy.wrapping_sub(dy)),
            ];
            for (px, py) in coords {
                if px < pb.width && py < pb.height {
                    pb.set_pixel(px, py, color);
                }
            }
        }
    }
}

/// Signed distance from a point to the border of a rounded rectangle.
///
/// Negative values are inside, positive outside.
fn rounded_rect_sdf(px: f32, py: f32, w: f32, h: f32, r: f32) -> f32 {
    let cx = px - w / 2.0;
    let cy = py - h / 2.0;
    let hw = w / 2.0 - r;
    let hh = h / 2.0 - r;
    let dx = cx.abs() - hw;
    let dy = cy.abs() - hh;
    let outside = (dx.max(0.0).powi(2) + dy.max(0.0).powi(2)).sqrt();
    let inside = dx.max(dy).min(0.0);
    outside + inside - r
}

/// Draw a rounded rectangle border (outline only) into the pixel buffer.
///
/// Uses an SDF for anti-aliased edges.  Only the border ring is drawn;
/// the interior is left untouched (transparent).
fn draw_rounded_border(pb: &mut PixelBuffer, color: [u8; 4], radius: f32, border_width: f32) {
    let w = pb.width as f32;
    let h = pb.height as f32;

    for y in 0..pb.height {
        for x in 0..pb.width {
            let d = rounded_rect_sdf(x as f32 + 0.5, y as f32 + 0.5, w, h, radius);

            // Outside the shape: d > 0 → skip (transparent).
            // Inside the border ring: -border_width < d <= 0.
            // Deep inside: d <= -border_width → skip (interior).

            // Outer edge anti-aliasing (smooth over 1px).
            let outer_alpha = (-d).clamp(0.0, 1.0);
            // Inner edge anti-aliasing (smooth over 1px).
            let inner_alpha = (d + border_width).clamp(0.0, 1.0);

            let alpha = outer_alpha * inner_alpha;

            if alpha > 0.0 {
                let a = (color[3] as f32 * alpha) as u8;
                // Premultiplied: color channels scaled by effective alpha.
                let b = (color[0] as f32 * alpha) as u8;
                let g = (color[1] as f32 * alpha) as u8;
                let r = (color[2] as f32 * alpha) as u8;
                let pixel = [b, g, r, a];
                pb.set_pixel(x, y, pixel);
            }
        }
    }
}

// ── Silence warning rendering ────────────────────────────────────────

/// Draw a prohibit icon (circle outline + diagonal bar) in bright red
/// with the given `stroke` width.
///
/// Anti-aliased circle ring plus a 45° diagonal bar.  Used for both
/// the badge (small) and the centered no-sound overlay (large).
fn draw_prohibit_icon_with_stroke(
    pb: &mut PixelBuffer,
    cx: usize,
    cy: usize,
    radius: f32,
    stroke: f32,
) {
    let color: [u8; 4] = [0x00, 0x00, 0xFF, 0xFF]; // bright red BGRA
    let r_outer = radius;
    let r_inner = radius - stroke;
    let r_outer_sq = r_outer * r_outer;
    let r_inner_sq = r_inner * r_inner;
    let r_int = r_outer.ceil() as i32;

    // Draw circle outline
    for dy in -r_int..=r_int {
        for dx in -r_int..=r_int {
            let dist_sq = (dx * dx + dy * dy) as f32;
            if dist_sq > r_outer_sq {
                continue;
            }
            // Anti-aliased outer edge
            let outer_edge = r_outer - dist_sq.sqrt();
            let outer_alpha = outer_edge.clamp(0.0, 1.0);
            // Anti-aliased inner edge (hollow centre)
            let inner_edge = dist_sq.sqrt() - r_inner;
            let inner_alpha = inner_edge.clamp(0.0, 1.0);

            let alpha = outer_alpha * inner_alpha;
            if alpha <= 0.0 {
                continue;
            }

            let px = cx as i32 + dx;
            let py = cy as i32 + dy;
            if px >= 0 && (px as usize) < pb.width && py >= 0 && (py as usize) < pb.height {
                let off = (py as usize * pb.width + px as usize) * 4;
                for (c, &fg_val) in color.iter().enumerate().take(4) {
                    let bg_val = pb.data[off + c] as f32;
                    pb.data[off + c] = (bg_val + (fg_val as f32 - bg_val) * alpha) as u8;
                }
            }
        }
    }

    // Draw diagonal bar (top-left to bottom-right at 45°)
    let half_stroke = stroke / 2.0;
    for dy in -r_int..=r_int {
        for dx in -r_int..=r_int {
            let dist_sq = (dx * dx + dy * dy) as f32;
            // Only draw inside the circle
            if dist_sq > r_inner_sq {
                continue;
            }
            // Distance from the line y = x (45° diagonal)
            let line_dist = ((dx as f32) - (dy as f32)).abs() / std::f32::consts::SQRT_2;
            if line_dist > half_stroke + 1.0 {
                continue;
            }
            let alpha = (half_stroke + 1.0 - line_dist).clamp(0.0, 1.0);
            if alpha <= 0.0 {
                continue;
            }

            let px = cx as i32 + dx;
            let py = cy as i32 + dy;
            if px >= 0 && (px as usize) < pb.width && py >= 0 && (py as usize) < pb.height {
                let off = (py as usize * pb.width + px as usize) * 4;
                for (c, &fg_val) in color.iter().enumerate().take(4) {
                    let bg_val = pb.data[off + c] as f32;
                    pb.data[off + c] = (bg_val + (fg_val as f32 - bg_val) * alpha) as u8;
                }
            }
        }
    }
}

/// Draw a prohibit icon at badge size (stroke = 2.0).
///
/// Wrapper around [`draw_prohibit_icon_with_stroke`] with the original
/// stroke width that matches [`PROHIBIT_ICON_RADIUS`].
fn draw_prohibit_icon(pb: &mut PixelBuffer, cx: usize, cy: usize, radius: f32) {
    draw_prohibit_icon_with_stroke(pb, cx, cy, radius, 2.0);
}

/// Draw a pause icon (two vertical bars ⏸) in yellow.
///
/// Replaces the pulsing red dot when auto-pause is active.
fn draw_pause_icon(pb: &mut PixelBuffer, cx: usize, cy: usize, radius: f32) {
    // Warm yellow, BGRA
    let color: [u8; 4] = [0x00, 0xC0, 0xFF, 0xFF];
    let bar_h = (radius * 1.4) as i32;
    let bar_w = (radius * 0.35).max(2.0) as i32;
    let gap = (radius * 0.35).max(2.0) as i32;

    let cx = cx as i32;
    let cy = cy as i32;

    // Left bar
    let lx = cx - gap / 2 - bar_w;
    let ly = cy - bar_h / 2;
    // Right bar
    let rx = cx + gap / 2;

    for bar_x in [lx, rx] {
        for dy in 0..bar_h {
            for dx in 0..bar_w {
                let px = bar_x + dx;
                let py = ly + dy;
                if px >= 0 && (px as usize) < pb.width && py >= 0 && (py as usize) < pb.height {
                    let off = (py as usize * pb.width + px as usize) * 4;
                    for (c, &val) in color.iter().enumerate().take(4) {
                        pb.data[off + c] = val;
                    }
                }
            }
        }
    }
}

/// Render centred text in the SPEC area with the given colour.
#[allow(clippy::too_many_arguments)]
fn render_badge_text(
    pb: &mut PixelBuffer,
    font: &fontdue::Font,
    text: &str,
    color: [u8; 4],
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
) {
    let font_size = 24.0f32;
    let (glyphs, text_w) = rasterise_glyphs(text, font, font_size);

    let start_x = x0 as i32 + (w as i32 - text_w as i32) / 2;
    let baseline = y0 as i32 + (h as i32 * 3) / 4;

    let buf_w = pb.width;
    let buf_h = pb.height;
    let mut cursor_x = start_x;
    for (metrics, bitmap) in &glyphs {
        blit_glyph_at(
            pb, metrics, bitmap, cursor_x, baseline, buf_w, buf_h, color, 1.0,
        );
        cursor_x += metrics.advance_width as i32;
    }
}

/// Render "NO SOUND" text in bright red, centred in the SPEC area.
fn render_no_sound_text(
    pb: &mut PixelBuffer,
    font: &fontdue::Font,
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
) {
    let color: [u8; 4] = [0x00, 0x00, 0xFF, 0xFF]; // bright red BGRA
    render_badge_text(pb, font, "NO SOUND", color, x0, y0, w, h);
}

/// Render "LISTENING" text in yellow, centred in the SPEC area.
fn render_listening_text(
    pb: &mut PixelBuffer,
    font: &fontdue::Font,
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
) {
    let color: [u8; 4] = [0x00, 0xC0, 0xFF, 0xFF]; // warm yellow BGRA
    render_badge_text(pb, font, "LISTENING", color, x0, y0, w, h);
}

/// Render "TRANSCRIBING" text in light blue, centred in the SPEC area.
fn render_transcribing_text(
    pb: &mut PixelBuffer,
    font: &fontdue::Font,
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
) {
    let color: [u8; 4] = [0xFF, 0xCC, 0x66, 0xFF]; // light blue BGRA
    render_badge_text(pb, font, "TRANSCRIBING", color, x0, y0, w, h);
}

/// Render "DOWNLOADING MODEL" text, centred in the SPEC area.
///
/// Same rendering path as [`render_transcribing_text`]; reuses the
/// light-blue colour so the static-badge family stays
/// theme-consistent.  Used while the local speech model is
/// downloading (a one-time, multi-second operation that blocks the
/// first recording).
fn render_downloading_text(
    pb: &mut PixelBuffer,
    font: &fontdue::Font,
    x0: usize,
    y0: usize,
    w: usize,
    h: usize,
) {
    let color: [u8; 4] = [0xFF, 0xCC, 0x66, 0xFF]; // light blue BGRA
    render_badge_text(pb, font, "DOWNLOADING MODEL", color, x0, y0, w, h);
}

/// Font size for the retry-attempt counter.  Smaller than the
/// `TRANSCRIBING`/`LISTENING` badge text so it doesn't compete
/// for attention; large enough that "1"–"5" remain legible
/// against the spectrogram waterfall behind.
const RETRY_COUNTER_FONT_SIZE: f32 = 14.0;

/// Render a small retry-attempt counter over the SPEC area.
///
/// Drawn at the top-left of the spectrogram, immediately below
/// the phase-line stripe, in the same green used for the
/// validating phase but at the phase's current opacity (so during
/// validation the digit fades along with the stripe).  Only fired
/// when an actual retry is in progress (`attempt >= 1`); the
/// initial attempt does not produce a counter.
///
/// `opacity` is the current [`Phase::opacity`], allowing the
/// counter to dim during validation and pop back to full opacity
/// during transcription retries.
fn render_retry_counter(
    pb: &mut PixelBuffer,
    font: &fontdue::Font,
    x0: usize,
    y0: usize,
    attempt: u32,
    _max: u32,
    opacity: f32,
) {
    if attempt == 0 {
        return;
    }
    // Single-digit display per the user spec ("first, second or
    // third retry").  If the schedule ever exceeds 9 attempts the
    // digit will overflow visually; this is acceptable because
    // [`super::transport::retry::MAX_RETRIES`] is 5 and the
    // validate-cache schedule has 5 entries — both single-digit.
    let text = format!("{}", attempt);
    let (glyphs, _) = rasterise_glyphs(&text, font, RETRY_COUNTER_FONT_SIZE);

    let buf_w = pb.width;
    let buf_h = pb.height;
    let mut cursor_x = x0 as i32;
    // Baseline a few pixels below the top of the SPEC area so the
    // glyph sits just under the phase-line stripe.
    let baseline = y0 as i32 + RETRY_COUNTER_FONT_SIZE as i32;
    for (metrics, bitmap) in &glyphs {
        blit_glyph_at(
            pb,
            metrics,
            bitmap,
            cursor_x,
            baseline,
            buf_w,
            buf_h,
            PHASE_GREEN,
            opacity,
        );
        cursor_x += metrics.advance_width as i32;
    }
}

// ── Centered no-sound overlay rendering ──────────────────────────────

/// Render the content of the large centered "no sound" overlay.
///
/// Layout (two rows):
///   Row 1 (upper ~60%): prohibit icon + "NO SOUND" side by side, centred as a unit
///   Row 2 (lower ~40%): subtitle text centred across full width
fn render_centered_no_sound(pb: &mut PixelBuffer, font: &fontdue::Font, bg: [u8; 4]) {
    let w = pb.width;
    let h = pb.height;

    // Fill background with rounded corners.
    pb.clear_rounded(bg, CENTERED_CORNER_RADIUS);

    // ── Row 1: icon + "NO SOUND" centred together ────────────
    let row1_cy = (h as f32 * 0.36) as usize; // vertical centre of top row

    let icon_radius = h as f32 * 0.22;
    let icon_stroke = (icon_radius * 0.15).max(2.0);
    let icon_diameter = (icon_radius * 2.0) as usize;

    let title_color: [u8; 4] = [0x00, 0x00, 0xFF, 0xFF]; // bright red BGRA
    let title_size = h as f32 * 0.35;
    let (title_glyphs, title_w) = rasterise_glyphs("NO SOUND", font, title_size);

    // Gap between icon and text.
    let gap = (h as f32 * 0.08) as usize;
    let row1_total_w = icon_diameter + gap + title_w;
    let row1_start_x = (w.saturating_sub(row1_total_w)) / 2;

    // Icon centred vertically in row 1.
    let icon_cx = row1_start_x + icon_radius as usize;
    draw_prohibit_icon_with_stroke(pb, icon_cx, row1_cy, icon_radius, icon_stroke);

    // Title text to the right of icon, baseline-aligned to row centre.
    let title_x = (row1_start_x + icon_diameter + gap) as i32;
    let title_baseline = row1_cy as i32 + (title_size * 0.30) as i32;

    let mut cursor_x = title_x;
    for (metrics, bitmap) in &title_glyphs {
        blit_glyph_at(
            pb,
            metrics,
            bitmap,
            cursor_x,
            title_baseline,
            w,
            h,
            title_color,
            1.0,
        );
        cursor_x += metrics.advance_width as i32;
    }

    // ── Row 2: subtitle centred across full width ────────────
    let sub_color: [u8; 4] = [0xAA, 0xAA, 0xAA, 0xFF]; // light gray BGRA
    let sub_size = h as f32 * 0.18;
    let sub_text = "No audio detected \u{2014} check your microphone";
    let (sub_glyphs, sub_w) = rasterise_glyphs(sub_text, font, sub_size);
    let sub_x = (w as i32 - sub_w as i32) / 2;
    let sub_baseline = (h as i32 * 82) / 100;

    let mut cursor_x = sub_x;
    for (metrics, bitmap) in &sub_glyphs {
        blit_glyph_at(
            pb,
            metrics,
            bitmap,
            cursor_x,
            sub_baseline,
            w,
            h,
            sub_color,
            1.0,
        );
        cursor_x += metrics.advance_width as i32;
    }
}

// ── Static PNG window (transcribing) ─────────────────────────────────

/// Apply a 1-bit shape mask based on the image alpha channel.
///
/// Pixels with alpha > 128 are visible; all others are transparent.
fn apply_alpha_shape_mask(
    conn: &impl Connection,
    win: u32,
    img: &RgbaImage,
    w: u16,
    h: u16,
) -> Result<(), TalkError> {
    let mask = conn
        .generate_id()
        .map_err(|e| TalkError::Config(format!("X11 generate_id failed: {}", e)))?;

    conn.create_pixmap(1, mask, win, w, h)
        .map_err(|e| TalkError::Config(format!("X11 create_pixmap failed: {}", e)))?;

    let gc = conn
        .generate_id()
        .map_err(|e| TalkError::Config(format!("X11 generate_id failed: {}", e)))?;

    conn.create_gc(gc, mask, &CreateGCAux::new().foreground(0))
        .map_err(|e| TalkError::Config(format!("X11 create_gc failed: {}", e)))?;

    conn.poly_fill_rectangle(
        mask,
        gc,
        &[Rectangle {
            x: 0,
            y: 0,
            width: w,
            height: h,
        }],
    )
    .map_err(|e| TalkError::Config(format!("X11 poly_fill_rectangle failed: {}", e)))?;

    conn.change_gc(gc, &ChangeGCAux::new().foreground(1))
        .map_err(|e| TalkError::Config(format!("X11 change_gc failed: {}", e)))?;

    let mut opaque_points: Vec<Point> = Vec::new();
    for py in 0..img.height {
        for px in 0..img.width {
            let idx = ((py * img.width + px) * 4) as usize;
            let alpha = img.data[idx + 3];
            if alpha > 128 {
                opaque_points.push(Point {
                    x: px as i16,
                    y: py as i16,
                });
            }
        }
    }

    for chunk in opaque_points.chunks(4096) {
        conn.poly_point(CoordMode::ORIGIN, mask, gc, chunk)
            .map_err(|e| TalkError::Config(format!("X11 poly_point failed: {}", e)))?;
    }

    shape::mask(conn, shape::SO::SET, shape::SK::BOUNDING, win, 0, 0, mask)
        .map_err(|e| TalkError::Config(format!("X11 shape_mask failed: {}", e)))?;

    conn.free_gc(gc)
        .map_err(|e| TalkError::Config(format!("X11 free_gc failed: {}", e)))?;
    conn.free_pixmap(mask)
        .map_err(|e| TalkError::Config(format!("X11 free_pixmap failed: {}", e)))?;

    Ok(())
}

/// Draw visible pixels onto the window, grouped by color for efficiency.
fn draw_image(
    conn: &impl Connection,
    win: u32,
    screen: &Screen,
    img: &RgbaImage,
) -> Result<(), TalkError> {
    let cmap = screen.default_colormap;

    let mut color_groups: HashMap<(u8, u8, u8), Vec<Point>> = HashMap::new();

    for py in 0..img.height {
        for px in 0..img.width {
            let idx = ((py * img.width + px) * 4) as usize;
            let r = img.data[idx];
            let g = img.data[idx + 1];
            let b = img.data[idx + 2];
            let a = img.data[idx + 3];

            if a > 128 {
                color_groups.entry((r, g, b)).or_default().push(Point {
                    x: px as i16,
                    y: py as i16,
                });
            }
        }
    }

    let gc = conn
        .generate_id()
        .map_err(|e| TalkError::Config(format!("X11 generate_id failed: {}", e)))?;

    conn.create_gc(gc, win, &CreateGCAux::new())
        .map_err(|e| TalkError::Config(format!("X11 create_gc failed: {}", e)))?;

    for ((r, g, b), points) in &color_groups {
        let reply = conn
            .alloc_color(
                cmap,
                (*r as u16) * 257,
                (*g as u16) * 257,
                (*b as u16) * 257,
            )
            .map_err(|e| TalkError::Config(format!("X11 alloc_color failed: {}", e)))?
            .reply()
            .map_err(|e| TalkError::Config(format!("X11 alloc_color reply failed: {}", e)))?;

        conn.change_gc(gc, &ChangeGCAux::new().foreground(reply.pixel))
            .map_err(|e| TalkError::Config(format!("X11 change_gc failed: {}", e)))?;

        for chunk in points.chunks(4096) {
            conn.poly_point(CoordMode::ORIGIN, win, gc, chunk)
                .map_err(|e| TalkError::Config(format!("X11 poly_point failed: {}", e)))?;
        }
    }

    conn.free_gc(gc)
        .map_err(|e| TalkError::Config(format!("X11 free_gc failed: {}", e)))?;

    Ok(())
}

// ── X11 overlay thread ──────────────────────────────────────────────

/// Main loop for the overlay background thread.
///
/// Has two modes:
///
/// * **Transcribing** — static PNG badge; blocks on commands.
/// * **Recording** — dynamic spectrogram badge at 60 fps reading from
///   the shared `audio_ring` buffer (fed by the audio tee); drains
///   commands non-blocking each frame.
#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
fn overlay_thread(
    rx: mpsc::Receiver<Command>,
    geom: super::monitor::MonitorGeometry,
    viz: Option<crate::config::VizMode>,
    mono_palette: Option<([u8; 4], [u8; 4])>,
    ring: Arc<Mutex<RingBuffer>>,
    sample_rate: u32,
    silence_tx: Option<std::sync::mpsc::Sender<bool>>,
    pause_flag: Arc<std::sync::atomic::AtomicBool>,
    auto_pause: bool,
    mut telemetry_rx: Option<tokio::sync::broadcast::Receiver<TranscriptionEvent>>,
    had_live_audio: Arc<std::sync::atomic::AtomicBool>,
) -> Result<(), TalkError> {
    let (conn, screen_num) = x11rb::connect(None)
        .map_err(|e| TalkError::Config(format!("failed to connect to X11: {}", e)))?;

    let screen = &conn.setup().roots[screen_num];
    let root = screen.root;

    // Try to find a 32-bit ARGB visual for compositor transparency.
    // Falls back to the root depth if unavailable.
    let argb_ctx = if let Some(visual) = find_argb_visual(screen) {
        let colormap = conn
            .generate_id()
            .map_err(|e| TalkError::Config(format!("X11 generate_id failed: {}", e)))?;
        conn.create_colormap(ColormapAlloc::NONE, colormap, root, visual)
            .map_err(|e| TalkError::Config(format!("X11 create_colormap failed: {}", e)))?;
        log::info!("using 32-bit ARGB visual for recording badge transparency");
        Some(ArgbContext {
            visual,
            colormap,
            depth: 32,
        })
    } else {
        log::warn!("no 32-bit ARGB visual found; recording badge will have opaque background");
        None
    };

    let depth = argb_ctx.as_ref().map_or(screen.root_depth, |c| c.depth);

    // Pre-decode the transcribing indicator image.
    let transcribing_img = decode_png(TRANSCRIBING_PNG)?;

    let (mon_x, mon_y, mon_w, mon_h) = geom;

    // Audio ring buffer and sample rate are now provided externally
    // via the audio tee task (no independent CPAL capture).
    let rms_chunk: usize = sample_rate as usize / FPS as usize;

    // Load a system font for rendering "NO SOUND" text on the badge.
    let badge_font = super::render_util::load_system_font(24.0);

    // ── Centered "no sound" overlay ─────────────────────────────────
    // Pre-compute dimensions and pre-render the content so the window
    // can be shown/hidden instantly on no-sound state transitions.
    let centered_h = (mon_h as f32 * CENTERED_HEIGHT_FRACTION) as u16;
    let centered_h = centered_h.max(CENTERED_MIN_HEIGHT);
    let centered_w = (centered_h as f32 * CENTERED_ASPECT_RATIO) as u16;
    let centered_w = centered_w.min(mon_w); // don't exceed monitor width
    let centered_font = super::render_util::load_system_font(centered_h as f32 * 0.55);
    let centered_bg = if argb_ctx.is_some() {
        CENTERED_BG_ARGB
    } else {
        CENTERED_BG_OPAQUE
    };
    // Pre-render the centered overlay content into a pixel buffer.
    let centered_pb = if let Some(ref font) = centered_font {
        let mut pb = PixelBuffer::new(centered_w as usize, centered_h as usize);
        render_centered_no_sound(&mut pb, font, centered_bg);
        Some(pb)
    } else {
        log::warn!("no font for centered no-sound overlay");
        None
    };
    // Window/GC handles for the centered overlay (created/destroyed
    // dynamically when no_sound_active transitions).
    let mut centered_window: Option<u32> = None;
    let mut centered_gc: Option<u32> = None;

    // ── Dead-signal detection state ─────────────────────────────────
    // Detect a dead/missing audio device by its "stuck at the rail"
    // signature: a disconnected device pins every sample at i16::MIN
    // (-32768 → -1.0f32), i.e. a perfectly constant frame at maximum
    // magnitude.  We flag NO SOUND only for that case.
    //
    // This deliberately does NOT key on low variance / silence: some
    // microphones (notably Bluetooth HFP) emit exact-zero digital
    // silence between speech (variance == 0, magnitude 0).  Treating
    // that as "dead" produced spurious NO SOUND warnings whenever the
    // user paused talking.  A constant-zero frame is benign silence
    // (handled by auto-pause); only a constant frame *near the rail*
    // is a dead device.
    let mut dead_signal_frames: u32 = 0;
    let mut no_sound_active: bool = false;
    let mut silence_notified: bool = false;
    // Magnitude (normalized, 0.0–1.0) at/above which a *constant* frame
    // is considered stuck at the i16 rail.  30000/32768 ≈ 0.915; a real
    // signal essentially never holds a single value this large across
    // an entire frame.
    const DEAD_SIGNAL_RAIL_FLOOR: f32 = 0.9;
    // Spread (max−min) below which a frame counts as "constant".  Uses
    // a tiny epsilon rather than exact equality to tolerate any f32
    // conversion noise; a stuck rail has spread 0.0.
    const DEAD_SIGNAL_FLAT_EPS: f32 = 1e-6;
    const DEAD_SIGNAL_TRIGGER_FRAMES: u32 = 30; // 0.5s grace for PipeWire to fill the ring buffer

    // ── Auto-pause state ─────────────────────────────────────────────
    // Pause the recording pipeline when the user stops speaking.
    // Uses RMS threshold (not variance) because this distinguishes
    // "quiet room with working mic" from "speech".
    let mut quiet_frames: u32 = 0;
    let mut auto_paused: bool = false;
    const AUTOPAUSE_RMS_THRESHOLD: f32 = 0.003; // well above mic noise (~0.00004)
    const AUTOPAUSE_TRIGGER_FRAMES: u32 = 15; // 0.3 seconds at 60fps

    // Diagnostic logging counter (logs every ~1 second = 60 frames).
    let mut diag_frame_counter: u32 = 0;
    const DIAG_LOG_INTERVAL: u32 = 60;

    // ── State ────────────────────────────────────────────────────────

    let frame_dur = std::time::Duration::from_micros(1_000_000 / FPS as u64);

    let mut current_window: Option<Window> = None;
    let mut current_gc: Option<Gcontext> = None;
    let mut is_recording = false;

    let mut spectrogram_history: Vec<Vec<f32>> = Vec::new();
    let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
    let mut rms_peak: f32 = PEAK_FLOOR;

    // Waterfall column advance counter.  Incremented every render
    // frame; a new column is pushed to [`spectrogram_history`] (and
    // amplitude/spectrum equivalents) only when the counter is a
    // multiple of [`COLUMN_PERIOD_FRAMES`].  This decouples the
    // waterfall's temporal resolution from the 60 fps render rate.
    let mut column_frame_counter: u32 = 0;

    // ── Phase overlay state ──────────────────────��───────────────
    //
    // Parallel to `spectrogram_history`: for each column we store
    // the colour of the HTTP phase that was active when the column
    // was pushed.  `None` = no HTTP activity (normal audio).
    // The state machine is driven by events from the telemetry
    // broker, drained non-blockingly every frame.
    let mut current_phase: Phase = Phase::Idle;
    let mut phase_history: Vec<Option<([u8; 4], f32)>> = Vec::new();

    // Retry-counter state, drawn over the SPEC area to advertise
    // "we're on attempt N out of M" to the user.  `None` until a
    // `RetryScheduled` event arrives; cleared when a fresh
    // request/preflight starts (so completing a successful retry
    // doesn't leave a stale digit on screen for the next cycle).
    let mut current_retry: Option<(u32, u32)> = None;

    // Server-backoff countdown: `(started, delay)` from the last
    // `RetryScheduled { kind: Data }`.  Drives the draining amber
    // bar and the `BUSY · RETRY N/M` badge while `current_phase`
    // is `WaitingRetry`; cleared whenever `current_retry` is.
    let mut current_backoff: Option<(std::time::Instant, std::time::Duration)> = None;

    // True when the recording has ended and the HTTP transcription is
    // in flight.  The render loop keeps running: empty columns are
    // pushed so the waterfall continues to scroll, and the phase
    // colour layer shows the HTTP lifecycle on top.
    let mut is_transcribing: bool = false;

    // True while the local speech model is downloading (one-time,
    // multi-second operation that blocks the first recording).
    // Mutually exclusive with `is_transcribing` and live recording:
    // the render path treats it identically to `is_transcribing`
    // (dimmed background + static text overlay) but draws
    // "DOWNLOADING MODEL" instead of "TRANSCRIBING".
    let mut is_downloading: bool = false;

    // ── Byte throughput state (Layer 3b) ─────────────────────────
    //
    // Three independent tracks that can overlap during transcription:
    //   upload   — grows DOWN from the phase line (top of spec)
    //   download — grows UP from the bottom of the spec area
    //   paste    — grows UP from the bottom alongside download
    //
    // Each track has its own cumulative counter, previous-value
    // snapshot, peak delta, and ring-buffer history.
    let mut current_upload_bytes: u64 = 0;
    let mut prev_upload_bytes: u64 = 0;
    let mut upload_peak_delta: u64 = 1;
    let mut upload_history: Vec<u64> = Vec::new();

    let mut current_download_bytes: u64 = 0;
    let mut prev_download_bytes: u64 = 0;
    let mut download_peak_delta: u64 = 1;
    let mut download_history: Vec<u64> = Vec::new();

    let mut current_paste_chars: u64 = 0;
    let mut prev_paste_chars: u64 = 0;
    let mut paste_peak_delta: u64 = 1;
    let mut paste_history: Vec<u64> = Vec::new();

    // Running total of columns ever pushed into the spectrogram
    // history since the last reset (`spectrogram_history.clear()`).
    // Used by the time-grid overlay to compute absolute column
    // indices — grid marks land on columns where
    // `index % COLUMNS_PER_GRID_MARK == 0`, so the counter must
    // reset together with the history to keep the first grid mark
    // aligned with the first visible column of each new session.
    let mut columns_pushed_total: u64 = 0;

    // Amplitude history for amplitude viz mode: one RMS value per frame.
    let amp_window_secs: f32 = 5.0;
    let amp_max_frames = (FPS as f32 * amp_window_secs) as usize;
    let mut amp_history: Vec<f32> = vec![0.0; amp_max_frames];
    let mut amp_peak: f32 = PEAK_FLOOR;
    // Spectrum peak for spectrum viz mode.
    let mut spectrum_peak: f32 = PEAK_FLOOR;
    let mut spec_peak: f32 = PEAK_FLOOR;
    // Dynamic frequency ceiling — grows as higher harmonics appear.
    let mut effective_freq_max: f32 = FREQ_INITIAL_MAX;

    // ── Event loop ───────────────────────────────────────────────────

    loop {
        // ── Idle / transcribing: block on commands ───────────────
        if !is_recording {
            let cmd = match rx.recv() {
                Ok(cmd) => cmd,
                Err(_) => break,
            };

            match cmd {
                Command::Show(IndicatorKind::Recording) => {
                    destroy_current(&conn, &mut current_window, &mut current_gc);
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);

                    let badge_x = mon_x + (mon_w as i16 / 2) - (BADGE_W as i16 / 2);
                    let badge_y = mon_y + 4;

                    let win = if let Some(ref ctx) = argb_ctx {
                        // 32-bit ARGB window with shape mask for rounded corners.
                        let w = create_argb_overlay_window(
                            &conn, root, ctx, badge_x, badge_y, BADGE_W, BADGE_H,
                        )?;
                        apply_rounded_shape(&conn, w, BADGE_W, BADGE_H, CORNER_RADIUS)?;
                        w
                    } else {
                        // Fallback: opaque window with shape mask.
                        let w = create_overlay_window(
                            &conn, screen, root, badge_x, badge_y, BADGE_W, BADGE_H,
                        )?;
                        apply_rounded_shape(&conn, w, BADGE_W, BADGE_H, CORNER_RADIUS)?;
                        w
                    };

                    conn.map_window(win)
                        .map_err(|e| TalkError::Config(format!("X11 map_window failed: {}", e)))?;
                    conn.sync()
                        .map_err(|e| TalkError::Config(format!("X11 sync failed: {}", e)))?;

                    let gc = conn
                        .generate_id()
                        .map_err(|e| TalkError::Config(format!("X11 generate_id: {}", e)))?;
                    conn.create_gc(gc, win, &CreateGCAux::new())
                        .map_err(|e| TalkError::Config(format!("X11 create_gc: {}", e)))?;

                    conn.flush()
                        .map_err(|e| TalkError::Config(format!("X11 flush: {}", e)))?;

                    current_window = Some(win);
                    current_gc = Some(gc);
                    is_recording = true;
                    is_transcribing = false;
                    is_downloading = false;
                    spectrogram_history.clear();
                    phase_history.clear();
                    upload_history.clear();
                    download_history.clear();
                    paste_history.clear();
                    current_upload_bytes = 0;
                    prev_upload_bytes = 0;
                    upload_peak_delta = 1;
                    current_download_bytes = 0;
                    prev_download_bytes = 0;
                    download_peak_delta = 1;
                    current_paste_chars = 0;
                    prev_paste_chars = 0;
                    paste_peak_delta = 1;
                    columns_pushed_total = 0;
                    current_phase = Phase::Idle;
                    current_retry = None;
                    current_backoff = None;
                    rms_peak = PEAK_FLOOR;
                    spec_peak = PEAK_FLOOR;
                    spectrum_peak = PEAK_FLOOR;
                    amp_peak = PEAK_FLOOR;
                    amp_history.clear();
                    amp_history.resize(amp_max_frames, 0.0);
                    effective_freq_max = FREQ_INITIAL_MAX;
                    dead_signal_frames = 0;
                    no_sound_active = false;
                    silence_notified = false;
                    quiet_frames = 0;
                    auto_paused = false;
                    pause_flag.store(false, std::sync::atomic::Ordering::Relaxed);
                    had_live_audio.store(false, std::sync::atomic::Ordering::Relaxed);
                }

                Command::Show(IndicatorKind::Transcribing) => {
                    destroy_current(&conn, &mut current_window, &mut current_gc);
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);
                    is_downloading = false;
                    show_transcribing(
                        &conn,
                        screen,
                        root,
                        &transcribing_img,
                        mon_x,
                        mon_y,
                        mon_w,
                        &mut current_window,
                    )?;
                }

                Command::Show(IndicatorKind::DownloadingModel) => {
                    // Mirror Show(Recording)'s window-creation path so the
                    // 60 fps render loop kicks in and draws the
                    // "DOWNLOADING MODEL" static text badge.  The three
                    // states (Recording / Transcribing / DownloadingModel)
                    // are mutually exclusive flags inside the render
                    // loop; here we set is_downloading=true and
                    // is_transcribing=false.
                    destroy_current(&conn, &mut current_window, &mut current_gc);
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);

                    let badge_x = mon_x + (mon_w as i16 / 2) - (BADGE_W as i16 / 2);
                    let badge_y = mon_y + 4;

                    let win = if let Some(ref ctx) = argb_ctx {
                        // 32-bit ARGB window with shape mask for rounded corners.
                        let w = create_argb_overlay_window(
                            &conn, root, ctx, badge_x, badge_y, BADGE_W, BADGE_H,
                        )?;
                        apply_rounded_shape(&conn, w, BADGE_W, BADGE_H, CORNER_RADIUS)?;
                        w
                    } else {
                        // Fallback: opaque window with shape mask.
                        let w = create_overlay_window(
                            &conn, screen, root, badge_x, badge_y, BADGE_W, BADGE_H,
                        )?;
                        apply_rounded_shape(&conn, w, BADGE_W, BADGE_H, CORNER_RADIUS)?;
                        w
                    };

                    conn.map_window(win)
                        .map_err(|e| TalkError::Config(format!("X11 map_window failed: {}", e)))?;
                    conn.sync()
                        .map_err(|e| TalkError::Config(format!("X11 sync failed: {}", e)))?;

                    let gc = conn
                        .generate_id()
                        .map_err(|e| TalkError::Config(format!("X11 generate_id: {}", e)))?;
                    conn.create_gc(gc, win, &CreateGCAux::new())
                        .map_err(|e| TalkError::Config(format!("X11 create_gc: {}", e)))?;

                    conn.flush()
                        .map_err(|e| TalkError::Config(format!("X11 flush: {}", e)))?;

                    current_window = Some(win);
                    current_gc = Some(gc);
                    is_recording = true;
                    is_transcribing = false;
                    is_downloading = true;
                    spectrogram_history.clear();
                    phase_history.clear();
                    upload_history.clear();
                    download_history.clear();
                    paste_history.clear();
                    current_upload_bytes = 0;
                    prev_upload_bytes = 0;
                    upload_peak_delta = 1;
                    current_download_bytes = 0;
                    prev_download_bytes = 0;
                    download_peak_delta = 1;
                    current_paste_chars = 0;
                    prev_paste_chars = 0;
                    paste_peak_delta = 1;
                    columns_pushed_total = 0;
                    current_phase = Phase::Idle;
                    current_retry = None;
                    current_backoff = None;
                    rms_peak = PEAK_FLOOR;
                    spec_peak = PEAK_FLOOR;
                    spectrum_peak = PEAK_FLOOR;
                    amp_peak = PEAK_FLOOR;
                    amp_history.clear();
                    amp_history.resize(amp_max_frames, 0.0);
                    effective_freq_max = FREQ_INITIAL_MAX;
                    dead_signal_frames = 0;
                    no_sound_active = false;
                    silence_notified = false;
                    quiet_frames = 0;
                    auto_paused = false;
                    pause_flag.store(false, std::sync::atomic::Ordering::Relaxed);
                    had_live_audio.store(false, std::sync::atomic::Ordering::Relaxed);
                }

                Command::Hide => {
                    destroy_current(&conn, &mut current_window, &mut current_gc);
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);
                }

                Command::Quit => {
                    destroy_current(&conn, &mut current_window, &mut current_gc);
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);
                    break;
                }
            }

            continue;
        }

        // ── Recording state: 60 fps render loop ─────────────────

        let frame_start = std::time::Instant::now();

        // Non-blocking command drain.
        let mut quit = false;
        loop {
            match rx.try_recv() {
                Ok(Command::Show(IndicatorKind::Recording)) => {
                    is_transcribing = false;
                    is_downloading = false;
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);
                    spectrogram_history.clear();
                    phase_history.clear();
                    upload_history.clear();
                    download_history.clear();
                    paste_history.clear();
                    current_upload_bytes = 0;
                    prev_upload_bytes = 0;
                    upload_peak_delta = 1;
                    current_download_bytes = 0;
                    prev_download_bytes = 0;
                    download_peak_delta = 1;
                    current_paste_chars = 0;
                    prev_paste_chars = 0;
                    paste_peak_delta = 1;
                    columns_pushed_total = 0;
                    current_phase = Phase::Idle;
                    current_retry = None;
                    current_backoff = None;
                    rms_peak = PEAK_FLOOR;
                    spec_peak = PEAK_FLOOR;
                    spectrum_peak = PEAK_FLOOR;
                    amp_peak = PEAK_FLOOR;
                    amp_history.clear();
                    amp_history.resize(amp_max_frames, 0.0);
                    effective_freq_max = FREQ_INITIAL_MAX;
                    dead_signal_frames = 0;
                    no_sound_active = false;
                    silence_notified = false;
                    quiet_frames = 0;
                    auto_paused = false;
                    pause_flag.store(false, std::sync::atomic::Ordering::Relaxed);
                    had_live_audio.store(false, std::sync::atomic::Ordering::Relaxed);
                }
                Ok(Command::Show(IndicatorKind::Transcribing)) => {
                    // Keep the render loop running instead of
                    // switching to the static PNG.  The waterfall
                    // continues to scroll (with empty columns since
                    // recording has stopped), and the phase colour
                    // layer renders the HTTP lifecycle on top.
                    is_transcribing = true;
                    is_downloading = false;
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);
                }
                Ok(Command::Show(IndicatorKind::DownloadingModel)) => {
                    // Mutually exclusive with the other two states:
                    // the render loop keeps running, the waterfall
                    // keeps scrolling with empty columns, and the
                    // static "DOWNLOADING MODEL" text overlay takes
                    // the place of "TRANSCRIBING" for the duration
                    // of the model download.
                    is_transcribing = false;
                    is_downloading = true;
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);
                }
                Ok(Command::Hide) => {
                    destroy_current(&conn, &mut current_window, &mut current_gc);
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);
                    is_recording = false;
                    break;
                }
                Ok(Command::Quit) | Err(mpsc::TryRecvError::Disconnected) => {
                    destroy_current(&conn, &mut current_window, &mut current_gc);
                    destroy_current(&conn, &mut centered_window, &mut centered_gc);
                    is_recording = false;
                    quit = true;
                    break;
                }
                Err(mpsc::TryRecvError::Empty) => break,
            }
        }

        if quit {
            break;
        }
        if !is_recording {
            continue;
        }

        // ── Drain telemetry events (non-blocking) ───────────
        //
        // The overlay thread is a plain OS thread (not async).
        // We use `try_recv()` to drain all pending events from
        // the broadcast channel without blocking the render loop.
        if let Some(ref mut trx) = telemetry_rx {
            loop {
                match trx.try_recv() {
                    Ok(event) => {
                        // Track counters for the three throughput tracks.
                        match &event {
                            TranscriptionEvent::UploadProgress { bytes_sent, .. } => {
                                current_upload_bytes = *bytes_sent;
                            }
                            TranscriptionEvent::DownloadProgress { bytes_received, .. } => {
                                current_download_bytes = *bytes_received;
                            }
                            TranscriptionEvent::PasteProgress { chars_pasted, .. } => {
                                current_paste_chars = *chars_pasted;
                            }
                            TranscriptionEvent::RequestStarted { .. } => {
                                // Reset upload + download for a new request.
                                current_upload_bytes = 0;
                                prev_upload_bytes = 0;
                                current_download_bytes = 0;
                                prev_download_bytes = 0;
                                // The actual transcription request is
                                // about to start — clear any retry
                                // counter left over from validate, so
                                // we don't show a stale digit during
                                // the transcription's first attempt.
                                current_retry = None;
                                current_backoff = None;
                            }
                            TranscriptionEvent::PreflightStarted { .. } => {
                                // Fresh preflight cycle — clear any
                                // retry counter that lingered from a
                                // previous attempt's terminal state.
                                current_retry = None;
                                current_backoff = None;
                            }
                            TranscriptionEvent::RetryScheduled {
                                kind,
                                attempt,
                                max,
                                delay,
                                t,
                                ..
                            } => {
                                // Surface the retry attempt to the
                                // overlay.  `RetryScheduled` is
                                // emitted both by the transport
                                // (transcription request) and by the
                                // validate-cache miss path; the
                                // counter is rendered in both cases
                                // (dimmed during validate, full
                                // opacity during transcription —
                                // controlled by the current phase).
                                current_retry = Some((*attempt, *max));
                                // A data retry carries a backoff
                                // delay; start the countdown from
                                // the event's own timestamp so a
                                // lagged broadcast doesn't stretch
                                // the bar.
                                current_backoff = match kind {
                                    crate::telemetry::RetryKind::Data => Some((*t, *delay)),
                                    crate::telemetry::RetryKind::Connection => None,
                                };
                            }
                            TranscriptionEvent::PasteStarted { .. } => {
                                current_paste_chars = 0;
                                prev_paste_chars = 0;
                            }
                            _ => {}
                        }
                        current_phase = current_phase.advance(&event);
                    }
                    Err(tokio::sync::broadcast::error::TryRecvError::Empty) => break,
                    Err(tokio::sync::broadcast::error::TryRecvError::Lagged(n)) => {
                        log::debug!("overlay telemetry: skipped {} lagged events", n);
                        continue;
                    }
                    Err(tokio::sync::broadcast::error::TryRecvError::Closed) => {
                        // Sender dropped — no more events coming.
                        telemetry_rx = None;
                        break;
                    }
                }
            }
        }

        // ── Read audio and compute visualization frame ──────

        let (frame_rms, magnitudes, frame_stuck_at_rail) = {
            let samples = ring
                .lock()
                .map(|g| g.read_last(FFT_SIZE.max(rms_chunk)))
                .unwrap_or_else(|_| vec![0.0; FFT_SIZE.max(rms_chunk)]);
            let rms_slice = &samples[samples.len().saturating_sub(rms_chunk.max(1))..];
            let fr = rms(rms_slice);
            // Detect the "stuck at the rail" signature of a dead /
            // disconnected device: a perfectly constant frame pinned
            // near the i16 rail (|sample| ≈ 1.0).  This avoids the old
            // variance heuristic, which mis-flagged the exact-zero
            // digital silence from Bluetooth HFP mics as a dead device.
            let stuck = is_stuck_at_rail(rms_slice, DEAD_SIGNAL_RAIL_FLOOR, DEAD_SIGNAL_FLAT_EPS);
            let mags = compute_spectrum(&samples);
            (fr, mags, stuck)
        };

        // Update RMS peak (fast attack, slow decay).
        rms_peak *= PEAK_DECAY;
        if frame_rms > rms_peak {
            rms_peak = frame_rms;
        }
        rms_peak = rms_peak.max(PEAK_FLOOR);

        // ── Diagnostic logging (once per second) ─────────────
        diag_frame_counter += 1;
        if diag_frame_counter >= DIAG_LOG_INTERVAL {
            diag_frame_counter = 0;
            log::debug!(
                "[audio-diag] rms={:.6} stuck_at_rail={}",
                frame_rms,
                frame_stuck_at_rail,
            );
        }

        // ── Dead-signal detection ────────────────────────────
        // A dead / disconnected device pins every sample at the i16
        // rail (constant ≈ -1.0): a flat frame at maximum magnitude.
        // Only that signature counts as a dead device.  Benign silence
        // (constant zero from an HFP mic, or a quiet room) is NOT dead.
        let was_no_sound = no_sound_active;
        if frame_stuck_at_rail {
            dead_signal_frames = dead_signal_frames.saturating_add(1);
        } else {
            if no_sound_active {
                if let Some(ref tx) = silence_tx {
                    let _ = tx.send(false);
                }
                // Resume the recording pipeline — the device is back.
                pause_flag.store(false, std::sync::atomic::Ordering::Relaxed);
            }
            dead_signal_frames = 0;
            no_sound_active = false;
            silence_notified = false;
        }
        // Mark the session as having captured real audio when the frame
        // carries actual signal (RMS above the auto-pause noise floor).
        // This is intentionally NOT set for silent-but-live frames so
        // the "skip transcription if nothing was ever spoken" guard in
        // streaming.rs keeps working.
        if frame_rms >= AUTOPAUSE_RMS_THRESHOLD {
            had_live_audio.store(true, std::sync::atomic::Ordering::Relaxed);
        }
        if dead_signal_frames >= DEAD_SIGNAL_TRIGGER_FRAMES {
            no_sound_active = true;
            if !silence_notified {
                if let Some(ref tx) = silence_tx {
                    let _ = tx.send(true);
                }
                // Pause the recording pipeline so dead-signal frames
                // are not forwarded to the OGG encoder / transcriber.
                pause_flag.store(true, std::sync::atomic::Ordering::Relaxed);
                silence_notified = true;
            }
        }

        // ── Centered no-sound overlay transitions ────────────
        if no_sound_active && !was_no_sound {
            // Transition to no-sound: show the centered overlay.
            if let Some(ref cpb) = centered_pb {
                if centered_window.is_none() {
                    let cx = mon_x + (mon_w as i16 / 2) - (centered_w as i16 / 2);
                    let cy = mon_y + (mon_h as i16 / 2) - (centered_h as i16 / 2);
                    let win = if let Some(ref ctx) = argb_ctx {
                        create_argb_overlay_window(&conn, root, ctx, cx, cy, centered_w, centered_h)
                    } else {
                        create_overlay_window(&conn, screen, root, cx, cy, centered_w, centered_h)
                    };
                    if let Ok(w) = win {
                        let _ = apply_rounded_shape(
                            &conn,
                            w,
                            centered_w,
                            centered_h,
                            CENTERED_CORNER_RADIUS,
                        );
                        let _ = conn.map_window(w);
                        let _ = conn.sync();
                        // Create GC and blit pre-rendered content.
                        if let Ok(gc) = conn.generate_id() {
                            let _ = conn.create_gc(gc, w, &CreateGCAux::new());
                            let _ = conn.put_image(
                                ImageFormat::Z_PIXMAP,
                                w,
                                gc,
                                centered_w,
                                centered_h,
                                0,
                                0,
                                0,
                                depth,
                                &cpb.data,
                            );
                            let _ = conn.flush();
                            centered_window = Some(w);
                            centered_gc = Some(gc);
                        }
                    }
                }
            }
        } else if !no_sound_active && was_no_sound {
            // Transition from no-sound: hide the centered overlay.
            destroy_current(&conn, &mut centered_window, &mut centered_gc);
        }

        // ── Auto-pause detection ─────────────────────────────
        // Only active when enabled and we have a working device (not dead signal).
        if auto_pause && !no_sound_active {
            if frame_rms < AUTOPAUSE_RMS_THRESHOLD {
                quiet_frames = quiet_frames.saturating_add(1);
            } else {
                quiet_frames = 0;
                if auto_paused {
                    auto_paused = false;
                    pause_flag.store(false, std::sync::atomic::Ordering::Relaxed);
                    log::debug!("auto-pause: resumed (speech detected)");
                }
            }
            if quiet_frames >= AUTOPAUSE_TRIGGER_FRAMES && !auto_paused {
                auto_paused = true;
                pause_flag.store(true, std::sync::atomic::Ordering::Relaxed);
                log::debug!("auto-pause: paused (silence detected)");
            }
        } else if !auto_pause {
            // Auto-pause disabled — ensure flag stays cleared.
            quiet_frames = 0;
        } else {
            // Dead signal takes priority — reset auto-pause state.
            quiet_frames = 0;
            if auto_paused {
                auto_paused = false;
                pause_flag.store(false, std::sync::atomic::Ordering::Relaxed);
            }
        }

        // Per-viz-mode peak tracking and frequency scaling — updated
        // every render frame (regardless of the slower column-push
        // cadence) so normalization stays smooth.  Peaks are still
        // frozen while the device is dead or auto-pause is active.
        if !auto_paused && !no_sound_active {
            if let Some(mode) = viz {
                use crate::config::VizMode;
                match mode {
                    VizMode::Waterfall => {
                        // Dynamic frequency scaling.
                        let nyquist = sample_rate as f32 / 2.0;
                        let n_mag = magnitudes.len();
                        for (i, &mag) in magnitudes.iter().enumerate().rev() {
                            if mag > FREQ_NOISE_FLOOR {
                                let freq = (i as f32 / n_mag as f32) * nyquist;
                                if freq > effective_freq_max {
                                    effective_freq_max = freq.min(FREQ_MAX);
                                }
                                break;
                            }
                        }
                        // All-time peak for opacity normalization.
                        let frame_spec_max = magnitudes.iter().copied().fold(0.0f32, f32::max);
                        if frame_spec_max > spec_peak {
                            spec_peak = frame_spec_max;
                        }
                    }
                    VizMode::Amplitude => {
                        if frame_rms > amp_peak {
                            amp_peak = frame_rms;
                        }
                    }
                    VizMode::Spectrum => {
                        spectrum_peak *= PEAK_DECAY;
                        let frame_peak = magnitudes.iter().copied().fold(0.0f32, f32::max);
                        if frame_peak > spectrum_peak {
                            spectrum_peak = frame_peak;
                        }
                        spectrum_peak = spectrum_peak.max(PEAK_FLOOR);
                    }
                }
            }
        }

        // ── Waterfall column advance ─────────────────────────
        //
        // The waterfall scrolls at a *constant* wall-clock rate
        // (one column every [`COLUMN_PERIOD_FRAMES`] render frames),
        // regardless of whether the user is currently speaking.
        //
        // During auto-pause, an *empty* column is pushed instead of
        // skipping the push entirely.  This keeps the scroll going
        // forward on the time axis so the growing "hole" in the
        // spectrogram visually represents the duration of the pause.
        // When speech resumes, the hole stops growing and real audio
        // columns fill in again.
        //
        // Peak tracking above is still frame-rate-driven so
        // normalization adapts smoothly even when the column rate
        // is slower.
        column_frame_counter = column_frame_counter.wrapping_add(1);
        // During transcription, the audio capture is stopped and the
        // dead-signal detector will fire (stale samples → variance 0
        // → no_sound_active = true).  We must keep pushing columns
        // regardless so the phase line and throughput bars continue
        // to advance on the time axis.
        if column_frame_counter.is_multiple_of(COLUMN_PERIOD_FRAMES)
            && (!no_sound_active || is_transcribing || is_downloading)
        {
            if let Some(mode) = viz {
                use crate::config::VizMode;
                match mode {
                    VizMode::Waterfall => {
                        let column = if auto_paused || is_transcribing || is_downloading {
                            // Empty column → no visible content, but the
                            // column still advances so the time axis
                            // keeps moving and the spectrogram "hole"
                            // grows with real elapsed time.
                            vec![0.0f32; SPEC_H]
                        } else {
                            map_spectrum_to_column(
                                &magnitudes,
                                SPEC_H,
                                sample_rate,
                                effective_freq_max,
                            )
                        };
                        spectrogram_history.push(column);
                        if spectrogram_history.len() > SPEC_W {
                            spectrogram_history.drain(..spectrogram_history.len() - SPEC_W);
                        }
                    }
                    VizMode::Amplitude => {
                        // 0.0 during pause / transcribing /
                        // model-download so the history also shows
                        // a visible gap.
                        let val = if auto_paused || is_transcribing || is_downloading {
                            0.0
                        } else {
                            frame_rms
                        };
                        amp_history.push(val);
                        if amp_history.len() > amp_max_frames {
                            amp_history.drain(..amp_history.len() - amp_max_frames);
                        }
                    }
                    VizMode::Spectrum => {
                        // Spectrum viz has no history; it renders a
                        // live snapshot of `magnitudes` each frame.
                    }
                }
            }
            // Every column push — even empty columns during pause —
            // advances the absolute-column counter the time-grid
            // overlay uses to space its vertical marks one per
            // wall-clock second.
            columns_pushed_total = columns_pushed_total.wrapping_add(1);

            // Record the current phase colour alongside the
            // spectrogram column so the phase overlay line stays
            // perfectly aligned with the waterfall time axis.
            phase_history.push(current_phase.color());
            if phase_history.len() > SPEC_W {
                phase_history.drain(..phase_history.len() - SPEC_W);
            }

            // Record per-column deltas for all three throughput tracks.
            let up_delta = current_upload_bytes.saturating_sub(prev_upload_bytes);
            prev_upload_bytes = current_upload_bytes;
            if up_delta > upload_peak_delta {
                upload_peak_delta = up_delta;
            }
            upload_history.push(up_delta);
            if upload_history.len() > SPEC_W {
                upload_history.drain(..upload_history.len() - SPEC_W);
            }

            let dl_delta = current_download_bytes.saturating_sub(prev_download_bytes);
            prev_download_bytes = current_download_bytes;
            if dl_delta > download_peak_delta {
                download_peak_delta = dl_delta;
            }
            download_history.push(dl_delta);
            if download_history.len() > SPEC_W {
                download_history.drain(..download_history.len() - SPEC_W);
            }

            let paste_delta = current_paste_chars.saturating_sub(prev_paste_chars);
            prev_paste_chars = current_paste_chars;
            if paste_delta > paste_peak_delta {
                paste_peak_delta = paste_delta;
            }
            paste_history.push(paste_delta);
            if paste_history.len() > SPEC_W {
                paste_history.drain(..paste_history.len() - SPEC_W);
            }
        }

        // ── Render badge ─────────────────────────────────────

        pb.clear(BG_COLOR);
        draw_rounded_border(&mut pb, BORDER_COLOR, CORNER_RADIUS as f32, BORDER_WIDTH);

        // Transcribing (and the mutually-exclusive "downloading model"
        // sibling) takes priority over the dead-signal (NO SOUND)
        // branch: after capture.stop() the audio ring buffer goes
        // stale and the dead-signal detector fires, but we WANT to
        // keep rendering the waterfall + phase line + throughput bars
        // rather than showing the NO SOUND prohibit icon.
        if is_transcribing || is_downloading {
            // ── TRANSCRIBING / DOWNLOADING MODEL mode:
            //    dimmed waterfall + phase ──────────────────────
            //
            // Same visual treatment as auto-pause (dimmed waterfall
            // keeps scrolling, empty columns create the "hole")
            // but the phase colour layer on top now shows the HTTP
            // lifecycle — connecting, uploading, waiting, receiving.
            if let Some(mode) = viz {
                use crate::config::VizMode;
                match mode {
                    VizMode::Waterfall => {
                        render_spectrogram(
                            &mut pb,
                            &spectrogram_history,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            spec_peak,
                            mono_palette,
                            DIM_FACTOR_PAUSED,
                        );
                    }
                    VizMode::Amplitude => {
                        render_amplitude_badge(
                            &mut pb,
                            &amp_history,
                            amp_peak,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            mono_palette,
                            DIM_FACTOR_PAUSED,
                        );
                    }
                    VizMode::Spectrum => {
                        render_spectrum_badge(
                            &mut pb,
                            &magnitudes,
                            spectrum_peak,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            mono_palette,
                            DIM_FACTOR_PAUSED,
                        );
                    }
                }
            }
            render_time_grid(
                &mut pb,
                SPEC_LEFT,
                SPEC_TOP,
                SPEC_W,
                SPEC_H,
                columns_pushed_total.saturating_sub(spectrogram_history.len() as u64),
                spectrogram_history.len(),
                COLUMNS_PER_GRID_MARK,
            );
            render_phase_line(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, &phase_history);
            // Server-backoff countdown over the phase line: a solid
            // amber band draining right-to-left across the wait.
            if current_phase == Phase::WaitingRetry {
                if let Some((started, delay)) = current_backoff {
                    let fraction =
                        backoff_remaining_fraction(std::time::Instant::now(), started, delay);
                    render_backoff_bar(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, fraction);
                }
            }
            render_throughput_tracks(
                &mut pb,
                SPEC_LEFT,
                SPEC_TOP,
                SPEC_W,
                SPEC_H,
                &upload_history,
                &download_history,
                &paste_history,
                &phase_history,
                upload_peak_delta,
                download_peak_delta,
                paste_peak_delta,
            );
            // "TRANSCRIBING" / "DOWNLOADING MODEL" text over the
            // dimmed waterfall (same pattern as "LISTENING" during
            // auto-pause).  The three flags is_recording (live),
            // is_transcribing, and is_downloading are mutually
            // exclusive; only one static-badge text fires here.
            if let Some(ref f) = badge_font {
                if is_downloading {
                    render_downloading_text(&mut pb, f, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H);
                } else if let (Phase::WaitingRetry, Some((attempt, max))) =
                    (current_phase, current_retry)
                {
                    // Provider backoff: the centre text carries the
                    // cause and the N/M count, so the small corner
                    // digit is redundant here and stays hidden.
                    render_backoff_text(
                        &mut pb,
                        f,
                        (attempt, max),
                        SPEC_LEFT,
                        SPEC_TOP,
                        SPEC_W,
                        SPEC_H,
                    );
                } else {
                    render_transcribing_text(&mut pb, f, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H);
                    // Retry-attempt indicator (1, 2, 3, …) drawn
                    // small at the top-left of the SPEC area so it
                    // doesn't collide with the centered TRANSCRIBING
                    // text.  Opacity follows the current phase:
                    // dimmed during validation, full during
                    // transcription retries.  Only meaningful while
                    // actually transcribing — the model-download
                    // phase has no retry counter.
                    if let Some((attempt, max)) = current_retry {
                        render_retry_counter(
                            &mut pb,
                            f,
                            SPEC_LEFT + 2,
                            SPEC_TOP + PHASE_LINE_HEIGHT,
                            attempt,
                            max,
                            current_phase.opacity(),
                        );
                    }
                }
            }
        } else if no_sound_active {
            // ── NO SOUND mode: prohibit icon + red text ──────
            if let Some(ref f) = badge_font {
                render_no_sound_text(&mut pb, f, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H);
            }
            clear_dot_gap(&mut pb, DOT_CX, DOT_CY, DOT_RADIUS_MAX + DOT_GAP);
            draw_prohibit_icon(&mut pb, DOT_CX, DOT_CY, PROHIBIT_ICON_RADIUS);
        } else if auto_paused {
            // ── AUTO-PAUSE mode: dimmed waterfall + LISTENING ─
            //
            // The waterfall keeps scrolling at constant time and the
            // growing "hole" (empty columns pushed above) shows how
            // long we've been listening.  We render it at reduced
            // opacity so the `LISTENING` indicator and pause icon
            // remain the dominant foreground.
            if let Some(mode) = viz {
                use crate::config::VizMode;
                match mode {
                    VizMode::Waterfall => {
                        render_spectrogram(
                            &mut pb,
                            &spectrogram_history,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            spec_peak,
                            mono_palette,
                            DIM_FACTOR_PAUSED,
                        );
                    }
                    VizMode::Amplitude => {
                        render_amplitude_badge(
                            &mut pb,
                            &amp_history,
                            amp_peak,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            mono_palette,
                            DIM_FACTOR_PAUSED,
                        );
                    }
                    VizMode::Spectrum => {
                        render_spectrum_badge(
                            &mut pb,
                            &magnitudes,
                            spectrum_peak,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            mono_palette,
                            DIM_FACTOR_PAUSED,
                        );
                    }
                }
            }
            // Time grid is drawn after the waterfall so its alpha
            // blend mixes visibly with whatever sits underneath.
            // Still visible during auto-pause so the user can see
            // how long the silent window has been growing.
            render_time_grid(
                &mut pb,
                SPEC_LEFT,
                SPEC_TOP,
                SPEC_W,
                SPEC_H,
                columns_pushed_total.saturating_sub(spectrogram_history.len() as u64),
                spectrogram_history.len(),
                COLUMNS_PER_GRID_MARK,
            );
            render_phase_line(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, &phase_history);
            // Server-backoff countdown over the phase line: a solid
            // amber band draining right-to-left across the wait.
            if current_phase == Phase::WaitingRetry {
                if let Some((started, delay)) = current_backoff {
                    let fraction =
                        backoff_remaining_fraction(std::time::Instant::now(), started, delay);
                    render_backoff_bar(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, fraction);
                }
            }
            render_throughput_tracks(
                &mut pb,
                SPEC_LEFT,
                SPEC_TOP,
                SPEC_W,
                SPEC_H,
                &upload_history,
                &download_history,
                &paste_history,
                &phase_history,
                upload_peak_delta,
                download_peak_delta,
                paste_peak_delta,
            );
            if let Some(ref f) = badge_font {
                render_listening_text(&mut pb, f, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H);
            }
            clear_dot_gap(&mut pb, DOT_CX, DOT_CY, DOT_RADIUS_MAX + DOT_GAP);
            draw_pause_icon(&mut pb, DOT_CX, DOT_CY, DOT_RADIUS_MAX);
        } else {
            // ── Normal mode: visualization + pulsing dot ─────
            if let Some(mode) = viz {
                use crate::config::VizMode;
                match mode {
                    VizMode::Waterfall => {
                        render_spectrogram(
                            &mut pb,
                            &spectrogram_history,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            spec_peak,
                            mono_palette,
                            1.0,
                        );
                    }
                    VizMode::Amplitude => {
                        render_amplitude_badge(
                            &mut pb,
                            &amp_history,
                            amp_peak,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            mono_palette,
                            1.0,
                        );
                    }
                    VizMode::Spectrum => {
                        render_spectrum_badge(
                            &mut pb,
                            &magnitudes,
                            spectrum_peak,
                            SPEC_LEFT,
                            SPEC_TOP,
                            SPEC_W,
                            SPEC_H,
                            mono_palette,
                            1.0,
                        );
                    }
                }
            }
            // Time grid overlays the waterfall with one dotted
            // yellow vertical mark per [`GRID_PERIOD_SECONDS`].
            // Drawn after the waterfall so the alpha blend combines
            // with the spectrogram colors beneath each dot.
            render_time_grid(
                &mut pb,
                SPEC_LEFT,
                SPEC_TOP,
                SPEC_W,
                SPEC_H,
                columns_pushed_total.saturating_sub(spectrogram_history.len() as u64),
                spectrogram_history.len(),
                COLUMNS_PER_GRID_MARK,
            );
            render_phase_line(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, &phase_history);
            // Server-backoff countdown over the phase line: a solid
            // amber band draining right-to-left across the wait.
            if current_phase == Phase::WaitingRetry {
                if let Some((started, delay)) = current_backoff {
                    let fraction =
                        backoff_remaining_fraction(std::time::Instant::now(), started, delay);
                    render_backoff_bar(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, fraction);
                }
            }
            render_throughput_tracks(
                &mut pb,
                SPEC_LEFT,
                SPEC_TOP,
                SPEC_W,
                SPEC_H,
                &upload_history,
                &download_history,
                &paste_history,
                &phase_history,
                upload_peak_delta,
                download_peak_delta,
                paste_peak_delta,
            );

            let vol_norm = if rms_peak > PEAK_FLOOR {
                (frame_rms / rms_peak).clamp(0.0, 1.0)
            } else {
                0.0
            };
            let dot_radius = DOT_RADIUS_MIN + (DOT_RADIUS_MAX - DOT_RADIUS_MIN) * vol_norm;
            let dot_brightness = DOT_MIN_BRIGHTNESS + (1.0 - DOT_MIN_BRIGHTNESS) * vol_norm;
            clear_dot_gap(&mut pb, DOT_CX, DOT_CY, dot_radius + DOT_GAP);
            draw_pulsing_dot(&mut pb, DOT_CX, DOT_CY, dot_radius, dot_brightness);
        }

        // ── Blit to X11 window ───────────────────────────────

        if let (Some(win), Some(gc)) = (current_window, current_gc) {
            let _ = conn.put_image(
                ImageFormat::Z_PIXMAP,
                win,
                gc,
                BADGE_W,
                BADGE_H,
                0,
                0,
                0,
                depth,
                &pb.data,
            );
            let _ = conn.flush();
        }

        // ── Frame timing ─────────────────────────────────────

        let elapsed = frame_start.elapsed();
        if elapsed < frame_dur {
            std::thread::sleep(frame_dur - elapsed);
        }
    }

    Ok(())
}

// ── Window helpers ───────────────────────────────────────────────────

/// Find a 32-bit TrueColor visual suitable for compositor alpha transparency.
///
/// Returns `Some(visual_id)` if one is available, `None` otherwise.
fn find_argb_visual(screen: &Screen) -> Option<Visualid> {
    screen
        .allowed_depths
        .iter()
        .filter(|d| d.depth == 32)
        .flat_map(|d| &d.visuals)
        .find(|v| v.class == VisualClass::TRUE_COLOR)
        .map(|v| v.visual_id)
}

/// ARGB window context: visual, colormap, and depth for 32-bit transparency.
struct ArgbContext {
    visual: Visualid,
    colormap: Colormap,
    depth: u8,
}

/// Create an override-redirect window with 32-bit ARGB visual.
///
/// The caller must free the colormap when the window is destroyed.
fn create_argb_overlay_window(
    conn: &impl Connection,
    root: u32,
    ctx: &ArgbContext,
    x: i16,
    y: i16,
    w: u16,
    h: u16,
) -> Result<u32, TalkError> {
    let win = conn
        .generate_id()
        .map_err(|e| TalkError::Config(format!("X11 generate_id failed: {}", e)))?;

    let values = CreateWindowAux::new()
        .background_pixel(0) // transparent
        .border_pixel(0) // required for non-default visual
        .override_redirect(1u32)
        .event_mask(EventMask::EXPOSURE)
        .colormap(ctx.colormap);

    conn.create_window(
        ctx.depth,
        win,
        root,
        x,
        y,
        w,
        h,
        0,
        WindowClass::INPUT_OUTPUT,
        ctx.visual,
        &values,
    )
    .map_err(|e| TalkError::Config(format!("X11 create_window failed: {}", e)))?;

    Ok(win)
}

/// Create an override-redirect X11 window at the given position.
fn create_overlay_window(
    conn: &impl Connection,
    screen: &Screen,
    root: u32,
    x: i16,
    y: i16,
    w: u16,
    h: u16,
) -> Result<u32, TalkError> {
    let win = conn
        .generate_id()
        .map_err(|e| TalkError::Config(format!("X11 generate_id failed: {}", e)))?;

    let values = CreateWindowAux::new()
        .background_pixel(screen.black_pixel)
        .border_pixel(0)
        .override_redirect(1u32)
        .event_mask(EventMask::EXPOSURE);

    conn.create_window(
        COPY_DEPTH_FROM_PARENT,
        win,
        root,
        x,
        y,
        w,
        h,
        0,
        WindowClass::INPUT_OUTPUT,
        0,
        &values,
    )
    .map_err(|e| TalkError::Config(format!("X11 create_window failed: {}", e)))?;

    Ok(win)
}

/// Show the static transcribing badge.
#[allow(clippy::too_many_arguments)]
fn show_transcribing(
    conn: &impl Connection,
    screen: &Screen,
    root: u32,
    img: &RgbaImage,
    mon_x: i16,
    mon_y: i16,
    mon_w: u16,
    current_window: &mut Option<u32>,
) -> Result<(), TalkError> {
    let w = img.width as u16;
    let h = img.height as u16;
    let x = mon_x + (mon_w as i16 / 2) - (w as i16 / 2);
    let y = mon_y + 4;

    let win = create_overlay_window(conn, screen, root, x, y, w, h)?;
    apply_alpha_shape_mask(conn, win, img, w, h)?;

    conn.map_window(win)
        .map_err(|e| TalkError::Config(format!("X11 map_window failed: {}", e)))?;
    conn.sync()
        .map_err(|e| TalkError::Config(format!("X11 sync failed: {}", e)))?;

    draw_image(conn, win, screen, img)?;

    conn.flush()
        .map_err(|e| TalkError::Config(format!("X11 flush failed: {}", e)))?;

    *current_window = Some(win);
    Ok(())
}

/// Destroy the current overlay window and free its GC if present.
fn destroy_current(conn: &impl Connection, window: &mut Option<u32>, gc: &mut Option<u32>) {
    if let Some(g) = gc.take() {
        let _ = conn.free_gc(g);
    }
    if let Some(win) = window.take() {
        let _ = conn.destroy_window(win);
        let _ = conn.flush();
    }
}

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

    // ── Dead-signal (stuck-at-rail) detection ────────────────────────
    //
    // These mirror the production constants used by `run_overlay_loop`.
    // Samples are normalized f32 (i16 / 32768); a disconnected device
    // emits constant i16::MIN (-32768) → -1.0.
    const RAIL_FLOOR: f32 = 0.9;
    const FLAT_EPS: f32 = 1e-6;

    #[test]
    fn stuck_at_rail_detects_disconnected_device() {
        // Real-world signature: every sample pinned at -32768 → -1.0.
        let frame = vec![-1.0f32; 266];
        assert!(is_stuck_at_rail(&frame, RAIL_FLOOR, FLAT_EPS));
    }

    #[test]
    fn stuck_at_rail_detects_positive_rail() {
        // A device stuck at the positive rail (+32767 → ~1.0) is dead
        // just the same.
        let frame = vec![1.0f32; 266];
        assert!(is_stuck_at_rail(&frame, RAIL_FLOOR, FLAT_EPS));
    }

    #[test]
    fn stuck_at_rail_ignores_zero_silence() {
        // Exact-zero digital silence (Bluetooth HFP between speech) is
        // flat but at magnitude 0 — must NOT be flagged as dead.
        let frame = vec![0.0f32; 266];
        assert!(!is_stuck_at_rail(&frame, RAIL_FLOOR, FLAT_EPS));
    }

    #[test]
    fn stuck_at_rail_ignores_quiet_noise_floor() {
        // An analog / old HFP mic in a quiet room: tiny fluctuating
        // noise floor (peaks ~8–10 in i16 ≈ 0.0003 normalized).  Flat?
        // No — it varies — and far from the rail.  Not dead.
        let frame: Vec<f32> = (0..266)
            .map(|i| if i % 2 == 0 { 8.0 } else { -10.0 } / 32768.0)
            .collect();
        assert!(!is_stuck_at_rail(&frame, RAIL_FLOOR, FLAT_EPS));
    }

    #[test]
    fn stuck_at_rail_ignores_loud_speech() {
        // Loud speech can momentarily hit the rail on a few samples,
        // but it is not *constant* — spread is large.  Not dead.
        let frame: Vec<f32> = (0..266)
            .map(|i| if i % 3 == 0 { 1.0 } else { -0.5 })
            .collect();
        assert!(!is_stuck_at_rail(&frame, RAIL_FLOOR, FLAT_EPS));
    }

    #[test]
    fn stuck_at_rail_ignores_constant_midlevel() {
        // A constant non-rail DC offset (e.g. 0.5) is flat but not near
        // the rail — treated as benign, not a dead device.
        let frame = vec![0.5f32; 266];
        assert!(!is_stuck_at_rail(&frame, RAIL_FLOOR, FLAT_EPS));
    }

    #[test]
    fn stuck_at_rail_empty_is_not_dead() {
        assert!(!is_stuck_at_rail(&[], RAIL_FLOOR, FLAT_EPS));
    }

    // ── PNG decoding ─────────────────────────────────────────────────

    #[test]
    fn test_decode_transcribing_png() {
        let img = decode_png(TRANSCRIBING_PNG).expect("decode transcribing PNG");
        assert_eq!(img.width, 210);
        assert_eq!(img.height, 52);
        assert_eq!(img.data.len(), 210 * 52 * 4);
    }

    #[test]
    fn test_transcribing_png_has_opaque_pixels() {
        let img = decode_png(TRANSCRIBING_PNG).expect("decode");
        let opaque_count = (0..img.width * img.height)
            .filter(|&i| img.data[(i * 4 + 3) as usize] > 128)
            .count();
        assert!(
            opaque_count > 1000,
            "expected >1000 opaque pixels, got {}",
            opaque_count
        );
    }

    // ── Spectrogram mapping ──────────────────────────────────────────

    #[test]
    fn map_spectrum_column_length() {
        let magnitudes = vec![1.0f32; 512];
        let column = map_spectrum_to_column(&magnitudes, SPEC_H, 48000, FREQ_MAX);
        assert_eq!(column.len(), SPEC_H);
    }

    #[test]
    fn map_spectrum_empty_magnitudes() {
        let column = map_spectrum_to_column(&[], SPEC_H, 48000, FREQ_MAX);
        assert_eq!(column.len(), SPEC_H);
        assert!(column.iter().all(|&v| v == 0.0));
    }

    #[test]
    fn map_spectrum_low_freq_comes_first() {
        // Create magnitudes that are loud at low bins and quiet at high.
        let mut magnitudes = vec![0.0f32; 512];
        for m in magnitudes.iter_mut().take(10) {
            *m = 10.0;
        }
        let column = map_spectrum_to_column(&magnitudes, SPEC_H, 48000, FREQ_MAX);
        // First row (low freq) should be louder than last (high freq).
        assert!(
            column[0] > column[SPEC_H - 1],
            "low freq row ({}) should be louder than high freq row ({})",
            column[0],
            column[SPEC_H - 1]
        );
    }

    // ── Spectrogram rendering ────────────────────────────────────────

    #[test]
    fn render_spectrogram_no_panic() {
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);

        let history: Vec<Vec<f32>> = (0..SPEC_W)
            .map(|i| vec![(i as f32 * 0.01).sin().abs(); SPEC_H])
            .collect();
        render_spectrogram(
            &mut pb, &history, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H, 1.0, None, 1.0,
        );

        let mut non_bg = 0;
        for y in SPEC_TOP..SPEC_BOTTOM {
            for x in SPEC_LEFT..SPEC_RIGHT {
                let off = (y * pb.width + x) * 4;
                if pb.data[off..off + 4] != BG_COLOR {
                    non_bg += 1;
                }
            }
        }
        assert!(non_bg > 0, "spectrogram should produce non-bg pixels");
    }

    #[test]
    fn render_spectrogram_empty_history_no_panic() {
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);
        render_spectrogram(
            &mut pb,
            &[],
            SPEC_LEFT,
            SPEC_TOP,
            SPEC_W,
            SPEC_H,
            1.0,
            None,
            1.0,
        );
    }

    #[test]
    fn render_time_grid_draws_dotted_yellow_at_first_mark_on_blank_buffer() {
        // On a blank (black) buffer, 65 visible columns starting at
        // absolute index 0 → grid marks at abs idx 0, 30, 60.
        // Right-aligned: columns 0..64 land at x = SPEC_LEFT + SPEC_W
        // - 65 + col_idx.  So:
        //     abs_idx=0  → col_idx=0  → x = SPEC_LEFT + SPEC_W - 65
        //     abs_idx=30 → col_idx=30 → x = SPEC_LEFT + SPEC_W - 35
        //     abs_idx=60 → col_idx=60 → x = SPEC_LEFT + SPEC_W - 5
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);

        render_time_grid(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H, 0, 65, 30);

        // Expected dot at (SPEC_LEFT + SPEC_W - 65, SPEC_TOP) — row 0 is
        // the first dot in the 1-on-1-off pattern.
        let first_x = SPEC_LEFT + SPEC_W - 65;
        let off = (SPEC_TOP * pb.width + first_x) * 4;
        // BG is opaque black → blend of 70 % black + 30 % pure yellow
        // (BGRA [0, 255, 255, _]) ⇒ B stays 0, G ≈ 76, R ≈ 76.
        assert_eq!(pb.data[off], 0, "grid blue channel unchanged by yellow");
        assert!(
            pb.data[off + 1] > 0 && pb.data[off + 1] < 200,
            "grid green should show blended yellow, got {}",
            pb.data[off + 1]
        );
        assert!(
            pb.data[off + 2] > 0 && pb.data[off + 2] < 200,
            "grid red should show blended yellow, got {}",
            pb.data[off + 2]
        );

        // Row 1 of the same column must still be background (1-off
        // in the 1-on-1-off pattern).
        let off_gap = ((SPEC_TOP + 1) * pb.width + first_x) * 4;
        assert_eq!(
            &pb.data[off_gap..off_gap + 4],
            &BG_COLOR,
            "row 1 of grid column should be untouched (dot gap)"
        );

        // Row 2 of the same column should be another dot.
        let off_dot2 = ((SPEC_TOP + 2) * pb.width + first_x) * 4;
        assert!(
            pb.data[off_dot2 + 1] > 0 && pb.data[off_dot2 + 2] > 0,
            "row 2 of grid column should be another dot"
        );

        // A non-grid column (say col_idx=5) must still be background.
        let non_grid_x = SPEC_LEFT + SPEC_W - 65 + 5;
        let off_ng = (SPEC_TOP * pb.width + non_grid_x) * 4;
        assert_eq!(
            &pb.data[off_ng..off_ng + 4],
            &BG_COLOR,
            "non-grid column should remain background"
        );
    }

    #[test]
    fn render_time_grid_blends_with_existing_waterfall_pixels() {
        // Start with a fully-white pixel buffer in the spec area.
        // The grid blend should make those pixels slightly tinted
        // toward yellow (green stays high, red stays high, blue
        // drops because yellow's blue channel is 0).
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        // Fill the whole spec area with opaque white.
        for y in SPEC_TOP..SPEC_BOTTOM {
            for x in SPEC_LEFT..SPEC_RIGHT {
                pb.set_pixel(x, y, [255, 255, 255, 255]);
            }
        }

        render_time_grid(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H, 0, 1, 30);

        // abs_idx=0 → col_idx=0 → x = SPEC_LEFT + SPEC_W - 1 (right edge).
        let x = SPEC_LEFT + SPEC_W - 1;
        let off = (SPEC_TOP * pb.width + x) * 4;
        // White (255) blended with yellow (B=0, G=255, R=255) at 30 %:
        //   B: 255*0.7 + 0*0.3   = 178
        //   G: 255*0.7 + 255*0.3 = 255
        //   R: 255*0.7 + 255*0.3 = 255
        assert!(
            pb.data[off] < 200,
            "grid dot blue should drop below white (got {})",
            pb.data[off]
        );
        assert!(pb.data[off + 1] >= 250, "green should stay high");
        assert!(pb.data[off + 2] >= 250, "red should stay high");
    }

    #[test]
    fn render_time_grid_no_marks_when_fewer_than_one_period_visible() {
        // Only 5 visible columns → no abs_idx is a multiple of 30
        // except idx 0 itself.  With first_visible_abs_idx=1, the
        // visible range is 1..=5, none of which hit idx 0, 30, 60,...
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);
        render_time_grid(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H, 1, 5, 30);

        // Nothing drawn: whole spec area still BG.
        for y in SPEC_TOP..SPEC_BOTTOM {
            for x in SPEC_LEFT..SPEC_RIGHT {
                let off = (y * pb.width + x) * 4;
                assert_eq!(
                    &pb.data[off..off + 4],
                    &BG_COLOR,
                    "no marks should have been drawn at ({},{})",
                    x,
                    y
                );
            }
        }
    }

    #[test]
    fn render_time_grid_noop_for_zero_visible_columns() {
        // Sanity: should not panic or modify the buffer.
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);
        render_time_grid(&mut pb, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H, 0, 0, 30);
        // Buffer should still be entirely BG.
        for y in SPEC_TOP..SPEC_BOTTOM {
            for x in SPEC_LEFT..SPEC_RIGHT {
                let off = (y * pb.width + x) * 4;
                assert_eq!(&pb.data[off..off + 4], &BG_COLOR);
            }
        }
    }

    #[test]
    fn render_spectrogram_dim_produces_darker_pixels_than_full() {
        // Same history, two different dim factors: the dim render
        // should produce strictly lower channel intensities at the
        // same pixel coordinates.  This validates the Phase 0
        // auto-pause dimming layer.
        let history: Vec<Vec<f32>> = (0..SPEC_W).map(|_| vec![1.0; SPEC_H]).collect();

        let mut pb_full = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb_full.clear(BG_COLOR);
        render_spectrogram(
            &mut pb_full,
            &history,
            SPEC_LEFT,
            SPEC_TOP,
            SPEC_W,
            SPEC_H,
            1.0,
            None,
            1.0,
        );

        let mut pb_dim = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb_dim.clear(BG_COLOR);
        render_spectrogram(
            &mut pb_dim,
            &history,
            SPEC_LEFT,
            SPEC_TOP,
            SPEC_W,
            SPEC_H,
            1.0,
            None,
            DIM_FACTOR_PAUSED,
        );

        // Sample the middle column, middle row.
        let sample_x = SPEC_LEFT + SPEC_W / 2;
        let sample_y = SPEC_TOP + SPEC_H / 2;
        let off = (sample_y * pb_full.width + sample_x) * 4;

        let full_intensity =
            pb_full.data[off] as u32 + pb_full.data[off + 1] as u32 + pb_full.data[off + 2] as u32;
        let dim_intensity =
            pb_dim.data[off] as u32 + pb_dim.data[off + 1] as u32 + pb_dim.data[off + 2] as u32;

        assert!(
            full_intensity > 0,
            "full-bright spectrogram pixel should have non-zero intensity"
        );
        assert!(
            dim_intensity < full_intensity,
            "dim ({}) must be strictly less than full ({})",
            dim_intensity,
            full_intensity
        );
    }

    #[test]
    fn render_spectrogram_zero_column_produces_no_pixels() {
        // A column of all zeros (as pushed during auto-pause) should
        // render no visible content at that column's x position.
        // This validates the Phase 0 "empty column / hole" behaviour.
        let history: Vec<Vec<f32>> = vec![vec![0.0f32; SPEC_H]; SPEC_W];
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);
        render_spectrogram(
            &mut pb, &history, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H, 1.0, None, 1.0,
        );

        // No pixel in the spec area should have been modified from
        // the background color.
        let mut non_bg = 0;
        for y in SPEC_TOP..SPEC_BOTTOM {
            for x in SPEC_LEFT..SPEC_RIGHT {
                let off = (y * pb.width + x) * 4;
                if pb.data[off..off + 4] != BG_COLOR {
                    non_bg += 1;
                }
            }
        }
        assert_eq!(
            non_bg, 0,
            "all-zero columns should produce no non-background pixels (got {})",
            non_bg
        );
    }

    #[test]
    fn render_spectrogram_right_aligned() {
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);

        // Only 5 columns of history — should right-align.
        let history: Vec<Vec<f32>> = (0..5).map(|_| vec![1.0; SPEC_H]).collect();
        render_spectrogram(
            &mut pb, &history, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H, 1.0, None, 1.0,
        );

        // Leftmost columns of spectrogram area should still be BG.
        let check_col = SPEC_LEFT;
        let mid_y = SPEC_TOP + SPEC_H / 2;
        let off = (mid_y * pb.width + check_col) * 4;
        assert_eq!(
            &pb.data[off..off + 4],
            &BG_COLOR,
            "leftmost spectrogram column should remain background when history is short"
        );

        // Rightmost columns should have content (non-zero alpha).
        let right_col = SPEC_LEFT + SPEC_W - 1; // last column of spectrogram area
        let off2 = (mid_y * pb.width + right_col) * 4;
        assert!(
            pb.data[off2 + 3] > 0,
            "rightmost spectrogram column should have non-zero alpha"
        );
    }

    // ── Red dot rendering ────────────────────────────────────────────

    #[test]
    fn draw_pulsing_dot_no_panic() {
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);
        draw_pulsing_dot(&mut pb, DOT_CX, DOT_CY, DOT_RADIUS_MAX, 0.8);

        let off = (DOT_CY * pb.width + DOT_CX) * 4;
        assert!(
            pb.data[off + 2] > 0,
            "dot centre red channel should be non-zero"
        );
    }

    #[test]
    fn draw_pulsing_dot_dim_vs_bright() {
        let mut pb_dim = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb_dim.clear(BG_COLOR);
        draw_pulsing_dot(
            &mut pb_dim,
            DOT_CX,
            DOT_CY,
            DOT_RADIUS_MAX,
            DOT_MIN_BRIGHTNESS,
        );
        let off = (DOT_CY * pb_dim.width + DOT_CX) * 4;
        let dim_r = pb_dim.data[off + 2];

        let mut pb_bright = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb_bright.clear(BG_COLOR);
        draw_pulsing_dot(&mut pb_bright, DOT_CX, DOT_CY, DOT_RADIUS_MAX, 1.0);
        let bright_r = pb_bright.data[off + 2];

        assert!(
            bright_r > dim_r,
            "bright dot ({}) should have higher red than dim ({})",
            bright_r,
            dim_r
        );
    }

    // ── Badge constants coherence ────────────────────────────────────

    #[test]
    fn spectrogram_area_fits_in_badge() {
        let bw = BADGE_W as usize;
        let bh = BADGE_H as usize;
        assert!(
            SPEC_RIGHT <= bw,
            "spectrogram right edge exceeds badge width"
        );
        assert!(
            SPEC_BOTTOM <= bh,
            "spectrogram bottom edge exceeds badge height"
        );
    }

    #[test]
    fn dot_fits_in_badge() {
        let r = DOT_RADIUS_MAX.ceil() as usize;
        assert!(DOT_CX >= r);
        assert!(DOT_CY >= r);
        assert!(DOT_CX + r < BADGE_W as usize);
        assert!(DOT_CY + r < BADGE_H as usize);
    }

    #[test]
    fn indicator_kind_clone_eq() {
        let a = IndicatorKind::Recording;
        let b = a;
        assert_eq!(a, b);
        assert_ne!(IndicatorKind::Recording, IndicatorKind::Transcribing);
        assert_ne!(IndicatorKind::Recording, IndicatorKind::DownloadingModel);
        assert_ne!(IndicatorKind::Transcribing, IndicatorKind::DownloadingModel);
        let c = IndicatorKind::DownloadingModel;
        let d = c;
        assert_eq!(c, d);
    }

    // ── Border rendering ───────────────────────────────────────────────

    #[test]
    fn rounded_rect_sdf_centre_is_negative() {
        let w = BADGE_W as f32;
        let h = BADGE_H as f32;
        let d = rounded_rect_sdf(w / 2.0, h / 2.0, w, h, CORNER_RADIUS as f32);
        assert!(
            d < 0.0,
            "centre of badge should be inside (negative SDF), got {}",
            d
        );
    }

    #[test]
    fn rounded_rect_sdf_outside_is_positive() {
        let w = BADGE_W as f32;
        let h = BADGE_H as f32;
        // Well outside the badge.
        let d = rounded_rect_sdf(w + 10.0, h + 10.0, w, h, CORNER_RADIUS as f32);
        assert!(
            d > 0.0,
            "point outside badge should have positive SDF, got {}",
            d
        );
    }

    #[test]
    fn draw_rounded_border_produces_border_pixels() {
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);
        draw_rounded_border(&mut pb, BORDER_COLOR, CORNER_RADIUS as f32, BORDER_WIDTH);

        // The top edge centre should have border pixels.
        let mid_x = BADGE_W as usize / 2;
        let off = mid_x * 4;
        assert!(
            pb.data[off + 3] > 0,
            "top edge centre should have non-zero alpha from border"
        );

        // Interior centre should remain at background color (no border there).
        let cx = BADGE_W as usize / 2;
        let cy = BADGE_H as usize / 2;
        let off_centre = (cy * pb.width + cx) * 4;
        assert_eq!(
            &pb.data[off_centre..off_centre + 4],
            &BG_COLOR,
            "badge interior should remain at background color"
        );
    }

    // ── Full badge render (integration) ──────────────────────────────

    #[test]
    fn full_badge_render_produces_content() {
        let mut pb = PixelBuffer::new(BADGE_W as usize, BADGE_H as usize);
        pb.clear(BG_COLOR);
        draw_rounded_border(&mut pb, BORDER_COLOR, CORNER_RADIUS as f32, BORDER_WIDTH);
        draw_pulsing_dot(&mut pb, DOT_CX, DOT_CY, DOT_RADIUS_MAX, 0.7);

        let history: Vec<Vec<f32>> = (0..SPEC_W)
            .map(|i| vec![(i as f32 * 0.05).sin().abs(); SPEC_H])
            .collect();
        render_spectrogram(
            &mut pb, &history, SPEC_LEFT, SPEC_TOP, SPEC_W, SPEC_H, 1.0, None, 1.0,
        );

        // Count pixels with non-zero alpha (visible content).
        let visible = pb.data.chunks_exact(4).filter(|p| p[3] > 0).count();

        assert!(
            visible > 500,
            "full badge render should produce significant visible content, got {} pixels with alpha > 0",
            visible
        );
    }

    // ── Phase state machine ─────────────────────────────────────

    /// Spec: `PreflightStarted` enters the dimmed validating phase.
    #[test]
    fn phase_advance_preflight_started_enters_validating() {
        use std::time::Instant;
        let now = Instant::now();
        let after = Phase::Idle.advance(&TranscriptionEvent::PreflightStarted { t: now });
        assert_eq!(after, Phase::Validating);
    }

    /// Spec: a successful preflight drops back to `Idle` (the next
    /// `RequestStarted` will move us forward to `Connecting`); we
    /// don't go directly to `Connecting` to avoid emitting a
    /// connecting stripe before the actual transcription request
    /// fires.
    #[test]
    fn phase_advance_preflight_completed_success_returns_to_idle() {
        use std::time::Instant;
        let after = Phase::Validating.advance(&TranscriptionEvent::PreflightCompleted {
            success: true,
            t: Instant::now(),
        });
        assert_eq!(after, Phase::Idle);
    }

    /// Spec: a failed preflight transitions to `Error` so the user
    /// sees red, not just a quiet drop-back to idle.
    #[test]
    fn phase_advance_preflight_completed_failure_enters_error() {
        use std::time::Instant;
        let after = Phase::Validating.advance(&TranscriptionEvent::PreflightCompleted {
            success: false,
            t: Instant::now(),
        });
        assert_eq!(after, Phase::Error);
    }

    /// Spec: a `RetryScheduled` while inside `Validating` keeps
    /// us in `Validating` (so the dimmed stripe persists across
    /// the validate retry attempts), unlike a retry inside the
    /// transcription path which falls back to `Connecting`.
    #[test]
    fn phase_advance_retry_during_validating_stays_validating() {
        use std::time::Instant;
        let after = Phase::Validating.advance(&TranscriptionEvent::RetryScheduled {
            kind: crate::telemetry::RetryKind::Connection,
            attempt: 2,
            max: 5,
            reason: "timeout".into(),
            delay: std::time::Duration::ZERO,
            t: Instant::now(),
        });
        assert_eq!(after, Phase::Validating);
    }

    /// Spec: a `RetryScheduled` outside `Validating` drops to
    /// `Connecting` (a new attempt is about to fire) — preserves
    /// the existing pre-Preflight behaviour.
    #[test]
    fn phase_advance_retry_outside_validating_returns_to_connecting() {
        use std::time::Instant;
        let after = Phase::Receiving.advance(&TranscriptionEvent::RetryScheduled {
            kind: crate::telemetry::RetryKind::Connection,
            attempt: 2,
            max: 5,
            reason: "timeout".into(),
            delay: std::time::Duration::ZERO,
            t: Instant::now(),
        });
        assert_eq!(after, Phase::Connecting);
    }

    // ── Phase color/opacity ─────────────────────────────────────

    /// Spec: `Validating` reuses the same green as `Done` but at
    /// half opacity, so the visualization is visibly different
    /// without choosing a colour that competes with success or
    /// connection states.
    #[test]
    fn phase_color_validating_is_green_at_half_opacity() {
        let (color, opacity) = Phase::Validating.color().expect("validating has a color");
        assert_eq!(color, PHASE_GREEN);
        assert!(
            (opacity - VALIDATING_OPACITY).abs() < f32::EPSILON,
            "expected {}, got {}",
            VALIDATING_OPACITY,
            opacity
        );
    }

    /// Spec: `Done` uses the same green at full opacity.
    #[test]
    fn phase_color_done_is_green_at_full_opacity() {
        let (color, opacity) = Phase::Done.color().expect("done has a color");
        assert_eq!(color, PHASE_GREEN);
        assert!((opacity - 1.0).abs() < f32::EPSILON);
    }

    /// Spec: `Idle` has no colour — overlay renders nothing.
    #[test]
    fn phase_color_idle_is_none() {
        assert!(Phase::Idle.color().is_none());
    }

    /// Spec: every non-validating, non-idle phase renders at full
    /// opacity (1.0).  Catches future refactors that accidentally
    /// dim a non-validation phase.
    #[test]
    fn phase_color_all_non_validating_phases_render_at_full_opacity() {
        for phase in [
            Phase::Connecting,
            Phase::Uploading,
            Phase::WaitingResponse,
            Phase::Receiving,
            Phase::Done,
            Phase::Error,
        ] {
            let (_, opacity) = phase.color().expect("non-idle phase has color");
            assert!(
                (opacity - 1.0).abs() < f32::EPSILON,
                "phase {:?} should render at full opacity, got {}",
                phase,
                opacity
            );
        }
    }

    // ── Provider-overload backoff (server retry) ───────────────

    use std::time::{Duration, Instant};

    /// Read back one BGRA pixel (test-only; production code never
    /// needs random access reads).
    fn pixel(pb: &PixelBuffer, x: usize, y: usize) -> [u8; 4] {
        let off = (y * pb.width + x) * 4;
        [
            pb.data[off],
            pb.data[off + 1],
            pb.data[off + 2],
            pb.data[off + 3],
        ]
    }

    fn data_retry(delay_secs: u64) -> TranscriptionEvent {
        TranscriptionEvent::RetryScheduled {
            kind: crate::telemetry::RetryKind::Data,
            attempt: 3,
            max: 6,
            reason: "503 high load".into(),
            delay: Duration::from_secs(delay_secs),
            t: Instant::now(),
        }
    }

    /// Spec: a data-phase (server busy) retry enters
    /// `WaitingRetry` from any transcription phase, while a
    /// connection retry keeps the historical `Connecting` fallback.
    #[test]
    fn phase_advance_data_retry_enters_waiting_retry() {
        for from in [
            Phase::Connecting,
            Phase::Uploading,
            Phase::WaitingResponse,
            Phase::Receiving,
        ] {
            assert_eq!(
                from.advance(&data_retry(30)),
                Phase::WaitingRetry,
                "from {:?}",
                from
            );
        }
        let conn = TranscriptionEvent::RetryScheduled {
            kind: crate::telemetry::RetryKind::Connection,
            attempt: 2,
            max: 6,
            reason: "timeout".into(),
            delay: Duration::ZERO,
            t: Instant::now(),
        };
        assert_eq!(Phase::Receiving.advance(&conn), Phase::Connecting);
    }

    /// Spec: a data retry during validation stays dimmed-validating
    /// (same rule as connection retries) — the preflight stripe is
    /// not the place to advertise provider backoff.
    #[test]
    fn phase_advance_data_retry_during_validating_stays_validating() {
        assert_eq!(
            Phase::Validating.advance(&data_retry(30)),
            Phase::Validating
        );
    }

    /// Spec: the next attempt's `RequestStarted` leaves
    /// `WaitingRetry` for `Connecting`, so the amber stripe ends
    /// exactly when the wait ends.
    #[test]
    fn phase_advance_waiting_retry_returns_to_connecting_on_request_started() {
        let after = Phase::WaitingRetry.advance(&TranscriptionEvent::RequestStarted {
            endpoint: "https://x".into(),
            t: Instant::now(),
        });
        assert_eq!(after, Phase::Connecting);
    }

    /// Spec: `WaitingRetry` is amber — the same hue family as
    /// `WaitingResponse` ("the server's turn"), distinct from every
    /// blue (our turn), red (failed) and green (done) phase — but at
    /// `BACKOFF_TRAIL_OPACITY`, so the full-opacity countdown band
    /// drawn on top by [`render_backoff_bar`] stays visibly distinct
    /// from the dim "time already spent waiting" trail underneath.
    #[test]
    fn phase_color_waiting_retry_is_dim_amber() {
        let (color, opacity) = Phase::WaitingRetry.color().expect("has colour");
        assert_eq!(color, PHASE_AMBER);
        assert!((opacity - BACKOFF_TRAIL_OPACITY).abs() < f32::EPSILON);
        assert!(opacity < 1.0 && opacity > 0.0);
        for other in [
            Phase::Connecting,
            Phase::Uploading,
            Phase::Receiving,
            Phase::Done,
            Phase::Error,
        ] {
            let (c, _) = other.color().expect("has colour");
            assert_ne!(
                c, PHASE_AMBER,
                "{:?} must not share the backoff amber",
                other
            );
        }
    }

    /// Spec: the drained fraction of the backoff bar is linear in
    /// elapsed time — 1.0 when the wait starts, 0.5 halfway, 0.0
    /// once the delay has elapsed, and never negative afterwards.
    #[test]
    fn backoff_remaining_fraction_drains_linearly_and_clamps() {
        let started = Instant::now();
        let delay = Duration::from_secs(40);
        let at = |secs: u64| {
            backoff_remaining_fraction(started + Duration::from_secs(secs), started, delay)
        };
        assert!((at(0) - 1.0).abs() < 1e-6);
        assert!((at(20) - 0.5).abs() < 1e-6);
        assert!((at(40) - 0.0).abs() < 1e-6);
        assert!((at(90) - 0.0).abs() < 1e-6, "must clamp after the delay");
    }

    /// Spec: a zero delay (connection retry) has nothing to drain —
    /// the fraction is 0.0 immediately so no bar is drawn.
    #[test]
    fn backoff_remaining_fraction_zero_delay_is_empty() {
        let started = Instant::now();
        assert!((backoff_remaining_fraction(started, started, Duration::ZERO) - 0.0).abs() < 1e-6);
    }

    /// Spec: the backoff bar is drawn right-to-left as a solid amber
    /// band `fraction * w` pixels wide, anchored at the left edge of
    /// the spec area, `PHASE_LINE_HEIGHT` tall.  At fraction 0.5 on
    /// a 100 px area, columns 0..50 are amber and 50..100 untouched.
    #[test]
    fn render_backoff_bar_fills_left_portion_proportionally() {
        let mut pb = PixelBuffer::new(120, 20);
        render_backoff_bar(&mut pb, 10, 5, 100, 0.5);
        assert_eq!(pixel(&pb, 10, 5), PHASE_AMBER, "left edge amber");
        assert_eq!(pixel(&pb, 59, 6), PHASE_AMBER, "last filled column amber");
        assert_eq!(
            pixel(&pb, 60, 5),
            [0, 0, 0, 0],
            "first drained column untouched"
        );
        assert_eq!(pixel(&pb, 109, 5), [0, 0, 0, 0], "right edge untouched");
        assert_eq!(
            pixel(&pb, 10, 5 + PHASE_LINE_HEIGHT),
            [0, 0, 0, 0],
            "below the band untouched"
        );
    }

    /// Spec: the centre badge text during a server backoff names
    /// the cause and the progress: `BUSY · RETRY 3/6`.
    #[test]
    fn backoff_badge_label_names_cause_and_progress() {
        assert_eq!(backoff_badge_label(3, 6), "BUSY · RETRY 3/6");
    }

    /// Spec: `Phase::opacity` is a thin accessor for the opacity
    /// component, returning 1.0 for `Idle` (no colour, no dimming
    /// for the retry counter that calls this method).
    #[test]
    fn phase_opacity_idle_is_full() {
        assert!((Phase::Idle.opacity() - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn phase_opacity_validating_is_half() {
        assert!((Phase::Validating.opacity() - VALIDATING_OPACITY).abs() < f32::EPSILON);
    }

    // ── render_retry_counter ────────────────────────────────────

    /// Spec: attempt 0 renders nothing — the counter is reserved
    /// for actual retry attempts (1, 2, 3, …).  No pixels written.
    #[test]
    fn retry_counter_attempt_zero_writes_no_pixels() {
        let font = match decode_font_or_skip() {
            Some(f) => f,
            None => return,
        };
        let mut pb = PixelBuffer::new(SPEC_W, SPEC_H);
        // Pre-fill so any change is detectable.
        pb.clear([0, 0, 0, 0]);
        render_retry_counter(&mut pb, &font, 2, 4, 0, 5, 1.0);
        let any_painted = pb.data.iter().any(|&b| b != 0);
        assert!(!any_painted, "attempt=0 must not paint anything");
    }

    /// Spec: attempt >= 1 paints visible pixels at the requested
    /// position.  Doesn't assert which glyphs; just that *some*
    /// foreground pixels appear, confirming the renderer fires.
    #[test]
    fn retry_counter_attempt_one_writes_visible_pixels() {
        let font = match decode_font_or_skip() {
            Some(f) => f,
            None => return,
        };
        let mut pb = PixelBuffer::new(SPEC_W, SPEC_H);
        pb.clear([0, 0, 0, 0]);
        render_retry_counter(&mut pb, &font, 2, 4, 1, 5, 1.0);
        let any_painted = pb.data.iter().any(|&b| b != 0);
        assert!(any_painted, "attempt>=1 must produce visible pixels");
    }

    /// Spec: lower opacity produces dimmer (smaller-magnitude)
    /// pixel values for the same glyph than full opacity.  This
    /// is the invariant the validating-phase counter depends on.
    #[test]
    fn retry_counter_dimmer_at_half_opacity() {
        let font = match decode_font_or_skip() {
            Some(f) => f,
            None => return,
        };
        let mut full = PixelBuffer::new(SPEC_W, SPEC_H);
        full.clear([0, 0, 0, 0]);
        let mut half = PixelBuffer::new(SPEC_W, SPEC_H);
        half.clear([0, 0, 0, 0]);
        render_retry_counter(&mut full, &font, 2, 4, 1, 5, 1.0);
        render_retry_counter(&mut half, &font, 2, 4, 1, 5, 0.5);

        let full_brightness: u64 = full.data.iter().map(|&b| b as u64).sum();
        let half_brightness: u64 = half.data.iter().map(|&b| b as u64).sum();
        assert!(
            half_brightness < full_brightness,
            "half-opacity counter should be dimmer; got full={} half={}",
            full_brightness,
            half_brightness
        );
        assert!(
            half_brightness > 0,
            "half-opacity counter should still be visible"
        );
    }

    /// Try to load the system badge font.  Tests that exercise
    /// glyph rasterisation skip themselves cleanly when no
    /// suitable system font is available (e.g. minimal CI
    /// environments without DejaVu / Liberation / Noto).
    fn decode_font_or_skip() -> Option<fontdue::Font> {
        super::super::render_util::load_system_font(RETRY_COUNTER_FONT_SIZE)
    }
}