perf-sentinel 0.8.1

CLI for perf-sentinel: polyglot performance anti-pattern detector
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
//! Terminal UI for interactive trace and finding inspection.
//!
//! Three top-level views form a single drill-down — `Analyze` (summary),
//! `Inspect` (the multi-panel browser: traces list, findings, correlations
//! and a detail span tree) and `Explain` (the selected trace's span tree
//! full screen). Enter descends `Analyze -> Inspect -> Explain`, Esc
//! ascends back.

use std::collections::HashMap;
use std::io;
use std::time::Duration;

use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::{Frame, Terminal};

use sentinel_core::correlate::Trace;
#[cfg(feature = "daemon")]
use sentinel_core::daemon::query_api::AckSource;
use sentinel_core::detect::correlate_cross::CrossTraceCorrelation;
use sentinel_core::detect::{DetectConfig, Finding, FindingType, Severity};
use sentinel_core::explain;
use sentinel_core::report::interpret::InterpretationLevel;
use sentinel_core::report::periodic::schema::{Confidentiality, ReportIntent};
use sentinel_core::report::{Analysis, GreenSummary, QualityGate};
use sentinel_core::text_safety::sanitize_for_terminal;

use crate::disclose::{CustomField, DiscloseState, Granularity, Tone};

#[cfg(feature = "daemon")]
use chrono::{DateTime, Utc};
#[cfg(feature = "daemon")]
use tokio::sync::mpsc;
/// Panel that currently has focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Panel {
    Traces,
    Findings,
    Detail,
    Correlations,
}

/// Top-level view in the drill-down. Enter descends
/// `Analyze -> Inspect -> Explain`, Esc ascends back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
    /// Summary dashboard (`GreenOps` waste, top offenders, quality gate).
    Analyze,
    /// Multi-panel browser: traces, findings, correlations, detail.
    Inspect,
    /// The selected trace's annotated span tree, full screen.
    Explain,
    /// Read-only `disclose` preview: calendar stepper over the period,
    /// live intent/confidentiality toggles, aggregated summary, equivalent
    /// command. Standalone — no drill-down to the other views.
    Disclose,
}

/// Summary data backing the Analyze view. Supplied by the launcher when
/// available; `None` degrades the view to a hint (e.g. an older daemon
/// without `/api/export/report`).
pub struct AnalyzeSummary {
    pub green_summary: GreenSummary,
    pub quality_gate: QualityGate,
    pub analysis: Analysis,
}

/// Application state for the TUI.
pub struct App {
    pub traces: Vec<Trace>,
    pub detect_config: DetectConfig,
    /// All findings from the report (owned, flat list).
    all_findings: Vec<Finding>,
    /// Per-trace finding indices into `all_findings`.
    findings_by_trace: Vec<Vec<usize>>,
    trace_ids: Vec<String>,
    trace_index: HashMap<String, usize>,

    /// Active top-level view. The panel-level `active_panel` only matters
    /// while `view == View::Inspect`.
    pub view: View,
    /// Summary backing the Analyze view. `None` renders a degraded hint.
    summary: Option<AnalyzeSummary>,
    /// Rendered line count of the Analyze body, precomputed once in
    /// `with_summary` (the summary is immutable for the App's lifetime) so
    /// the per-keypress scroll clamp does not rebuild the line vector.
    analyze_line_count: u16,

    pub selected_trace: usize,
    pub selected_finding: usize,
    pub active_panel: Panel,
    pub scroll_offset: u16,
    /// Cached detail tree text per trace: (`trace_idx`, rendered tree).
    cached_detail: Option<(usize, String)>,
    /// Pre-rendered span trees keyed by `trace_id`, populated by callers
    /// that don't have raw spans in memory (e.g. `query inspect` which
    /// fetches trees from the daemon's `/api/explain/{trace_id}` endpoint).
    /// When `Some(text)`, takes precedence over the `detect + build_tree`
    /// path that requires `traces[i].spans` to be populated.
    pre_rendered_trees: HashMap<String, String>,
    /// Cross-trace correlations to display in the Correlations panel.
    /// Empty in batch mode (correlator is daemon-only). Populated by
    /// `query inspect` from `/api/correlations`.
    correlations: Vec<CrossTraceCorrelation>,
    pub selected_correlation: usize,
    /// Panel that brought the user into Detail. Read by `escape` to
    /// return to the source panel (Findings or Correlations).
    detail_origin: Panel,

    /// Daemon URL when running under `query inspect`. `None` in batch
    /// mode (`inspect --input`), which disables `a`/`u` keys.
    #[cfg(feature = "daemon")]
    pub daemon_url: Option<String>,
    /// Resolved API key (env var or `--api-key-file`). `None` is a
    /// legitimate value when the daemon has no `[daemon.ack] api_key`.
    /// Used as the `X-API-Key` header on POST/DELETE ack writes.
    #[cfg(feature = "daemon")]
    pub api_key: Option<String>,
    /// Per-finding ack annotations keyed by signature. Populated at
    /// boot from `FindingResponse.acknowledged_by` and refreshed after
    /// every successful submit by `refetch_acks`.
    #[cfg(feature = "daemon")]
    pub acks_by_signature: HashMap<String, AckSource>,
    /// Modal overlay state for the ack/revoke flow. Hidden when not
    /// active. Drives `draw_ack_modal` and `handle_modal_key`.
    #[cfg(feature = "daemon")]
    pub ack_modal: AckModalState,

    /// Present only under `disclose --tui`. When `Some`, the tab bar shows
    /// just the standalone Disclose tab and the app opens on it; the
    /// analyze/inspect/explain drill-down is unused.
    disclose: Option<DiscloseState>,
}

impl App {
    /// Create a new app from analysis findings and traces.
    #[must_use]
    pub fn new(
        findings: Vec<Finding>,
        mut traces: Vec<Trace>,
        detect_config: DetectConfig,
    ) -> Self {
        // Sort traces by trace_id so the trace list panel has a stable,
        // predictable display order across runs. The upstream `correlate`
        // stage iterates a `HashMap<String, Vec<_>>` which yields traces
        // in randomized hash order, which is fine for batch analysis but
        // makes the interactive TUI non-reproducible (the same input file
        // shows traces in a different order on every launch, breaking
        // muscle memory for users who come back to investigate a trace
        // they just saw).
        //
        // `sort_unstable_by` is preferred over `sort_by`: the correlate
        // stage guarantees unique `trace_id` per `Trace` (all spans with
        // the same trace_id are folded into one entry), so sort stability
        // has no semantic value here and the unstable variant avoids the
        // merge-sort allocation.
        traces.sort_unstable_by(|a, b| a.trace_id.cmp(&b.trace_id));

        let trace_ids: Vec<String> = traces.iter().map(|t| t.trace_id.clone()).collect();
        let trace_index: HashMap<String, usize> = traces
            .iter()
            .enumerate()
            .map(|(i, t)| (t.trace_id.clone(), i))
            .collect();

        // Build per-trace index lists (indices into all_findings)
        let mut findings_by_trace: Vec<Vec<usize>> = vec![Vec::new(); traces.len()];
        for (idx, finding) in findings.iter().enumerate() {
            if let Some(&trace_vec_idx) = trace_index.get(&finding.trace_id) {
                findings_by_trace[trace_vec_idx].push(idx);
            }
        }

        Self {
            traces,
            detect_config,
            all_findings: findings,
            findings_by_trace,
            trace_ids,
            trace_index,
            view: View::Inspect,
            summary: None,
            analyze_line_count: 0,
            selected_trace: 0,
            selected_finding: 0,
            active_panel: Panel::Traces,
            scroll_offset: 0,
            cached_detail: None,
            pre_rendered_trees: HashMap::new(),
            correlations: Vec::new(),
            selected_correlation: 0,
            detail_origin: Panel::Findings,
            #[cfg(feature = "daemon")]
            daemon_url: None,
            #[cfg(feature = "daemon")]
            api_key: None,
            #[cfg(feature = "daemon")]
            acks_by_signature: HashMap::new(),
            #[cfg(feature = "daemon")]
            ack_modal: AckModalState::default(),
            disclose: None,
        }
    }

    /// Attach the `disclose --tui` preview state. The caller pairs this with
    /// `with_initial_view(View::Disclose)`; the App is otherwise built with
    /// empty findings/traces.
    pub(crate) fn with_disclose(mut self, state: DiscloseState) -> Self {
        self.disclose = Some(state);
        self
    }

    /// Attach a daemon handle so `a`/`u` keys are active. Used by
    /// `query inspect` to wire the TUI into the live daemon ack flow.
    /// Without this, the TUI is read-only and the keys are no-op.
    #[cfg(feature = "daemon")]
    pub(crate) fn with_daemon_handle(
        mut self,
        daemon_url: String,
        api_key: Option<String>,
        acks_by_signature: HashMap<String, AckSource>,
    ) -> Self {
        self.daemon_url = Some(daemon_url);
        self.api_key = api_key;
        self.acks_by_signature = acks_by_signature;
        self
    }

    /// Attach pre-rendered span trees keyed by `trace_id`. Used by
    /// `query inspect` to populate the detail panel from daemon
    /// responses when the CLI has no raw spans.
    ///
    /// `pub(crate)` because the TUI module is internal to the
    /// `perf-sentinel` binary crate, not a published library API.
    pub(crate) fn with_pre_rendered_trees(mut self, trees: HashMap<String, String>) -> Self {
        self.pre_rendered_trees = trees;
        self
    }

    /// Attach cross-trace correlations fetched from a daemon. The
    /// Correlations panel renders them as a navigable list.
    pub(crate) fn with_correlations(mut self, correlations: Vec<CrossTraceCorrelation>) -> Self {
        self.correlations = correlations;
        self
    }

    /// Attach the summary backing the Analyze view (`GreenOps` waste, top
    /// offenders, quality gate). Without it the view shows a hint.
    pub(crate) fn with_summary(mut self, summary: AnalyzeSummary) -> Self {
        self.summary = Some(summary);
        // Build the body once to cache its line count; the summary and
        // findings are immutable afterwards, so the count never changes.
        self.analyze_line_count =
            u16::try_from(self.build_analyze_lines().len()).unwrap_or(u16::MAX);
        self
    }

    /// Set the view the TUI opens on. `analyze --tui` lands on Analyze,
    /// `explain --tui` on Explain, `inspect` keeps the default Inspect.
    pub(crate) fn with_initial_view(mut self, view: View) -> Self {
        self.view = view;
        self
    }

    /// Pre-select a trace by id so the opening view (e.g. Explain for
    /// `explain --tui`) lands on it. No-op when the id is unknown.
    pub(crate) fn with_focus_trace(mut self, trace_id: &str) -> Self {
        if let Some(&idx) = self.trace_index.get(trace_id) {
            self.selected_trace = idx;
            self.selected_finding = 0;
            self.cached_detail = None;
        }
        self
    }

    /// Number of correlations available in the Correlations panel.
    #[must_use]
    pub fn correlation_count(&self) -> usize {
        self.correlations.len()
    }

    /// Number of traces available.
    #[must_use]
    pub fn trace_count(&self) -> usize {
        self.trace_ids.len()
    }

    /// Number of findings for the currently selected trace.
    #[must_use]
    pub fn finding_count(&self) -> usize {
        self.current_finding_indices().len()
    }

    /// Finding indices for the currently selected trace.
    fn current_finding_indices(&self) -> &[usize] {
        self.findings_by_trace
            .get(self.selected_trace)
            .map_or(&[], Vec::as_slice)
    }

    /// Currently selected finding, if any.
    pub(crate) fn current_finding(&self) -> Option<&Finding> {
        let indices = self.current_finding_indices();
        indices
            .get(self.selected_finding)
            .map(|&idx| &self.all_findings[idx])
    }

    /// Count the logical lines the Detail panel will render for the
    /// currently selected finding.
    ///
    /// Mirrors the line construction in [`draw_detail_panel`]: 7 always-
    /// present metadata rows (type header, template, occurrences, service,
    /// endpoint, suggestion, plus the blank between the header and the
    /// body), +1 when the finding carries a `green_impact`, then either
    /// the cached span tree (+2 for the header, +N for the tree lines)
    /// or the unavailability hint (+5 for the blank, header, and 3 hint
    /// lines pointing at `inspect --input <events>.json` and `query
    /// inspect`).
    ///
    /// Used by [`App::move_down`] to clamp the Detail-panel scroll offset
    /// so `Down`/`j` cannot scroll past the content. Long wrapped lines
    /// count as one logical line, so the clamp is slightly conservative
    /// on wrapped output, the tradeoff vs. reading the panel width at
    /// event-handling time (which ratatui does not expose) is accepted.
    fn detail_panel_line_count(&self) -> u16 {
        let Some(finding) = self.current_finding() else {
            return 0;
        };
        // 6 always-present metadata rows + 1 blank after the type header.
        let mut count: u16 = 7;
        // +1 for the optional "Source:" row that `draw_detail_panel` inserts
        // when the finding carries a non-empty code location, else the clamp
        // under-counts by 1 and the last span-tree line stays unreachable.
        if finding
            .code_location
            .as_ref()
            .is_some_and(|loc| !loc.display_string().is_empty())
        {
            count = count.saturating_add(1);
        }
        if finding.green_impact.is_some() {
            count = count.saturating_add(1);
        }
        if let Some((ct, ref text)) = self.cached_detail
            && ct == self.selected_trace
        {
            // +2 for blank + "Span tree:" header, +N for the tree lines.
            let tree_count = u16::try_from(text.lines().count()).unwrap_or(u16::MAX);
            count = count.saturating_add(2).saturating_add(tree_count);
        } else {
            // +2 for blank + "Span tree:" header, +3 for the hint lines.
            count = count.saturating_add(5);
        }
        count
    }

    /// Get the cached detail tree text, computing it if needed.
    ///
    /// Cached per trace (not per finding) since the tree is the same for all
    /// findings in a trace, `build_tree` annotates all findings inline.
    fn detail_tree_text(&mut self) -> Option<String> {
        let trace_idx = self.selected_trace;

        if let Some((ct, ref text)) = self.cached_detail
            && ct == trace_idx
        {
            return Some(text.clone());
        }

        let trace_id = self.trace_ids.get(trace_idx)?.clone();

        // Prefer the pre-rendered tree (populated by `query inspect` from
        // daemon API responses) over the local detect + build_tree path.
        // This lets the TUI display real span trees even when the caller
        // has no raw spans in memory.
        if let Some(text) = self.pre_rendered_trees.get(&trace_id) {
            let text = text.clone();
            self.cached_detail = Some((trace_idx, text.clone()));
            return Some(text);
        }

        let trace_vec_idx = self.trace_index.get(&trace_id).copied()?;
        let trace = &self.traces[trace_vec_idx];
        // When spans are empty (e.g. stub traces from `query inspect` without
        // pre-rendered trees), skip the build_tree path that would produce
        // an empty, confusing panel.
        if trace.spans.is_empty() {
            return None;
        }
        let per_trace_findings =
            sentinel_core::detect::detect(std::slice::from_ref(trace), &self.detect_config);
        let tree = explain::build_tree(trace, &per_trace_findings);
        let text = explain::format_tree_text(&tree, false);
        self.cached_detail = Some((trace_idx, text.clone()));
        Some(text)
    }

    /// Move selection up in the active panel.
    pub fn move_up(&mut self) {
        match self.active_panel {
            Panel::Traces => {
                if self.selected_trace > 0 {
                    self.selected_trace -= 1;
                    self.selected_finding = 0;
                    self.scroll_offset = 0;
                    self.cached_detail = None;
                }
            }
            Panel::Findings => {
                if self.selected_finding > 0 {
                    self.selected_finding -= 1;
                    self.scroll_offset = 0;
                }
            }
            Panel::Detail => {
                self.scroll_offset = self.scroll_offset.saturating_sub(1);
            }
            Panel::Correlations => {
                if self.selected_correlation > 0 {
                    self.selected_correlation -= 1;
                }
            }
        }
    }

    /// Move selection down in the active panel.
    pub fn move_down(&mut self) {
        match self.active_panel {
            Panel::Traces => {
                if self.selected_trace + 1 < self.trace_count() {
                    self.selected_trace += 1;
                    self.selected_finding = 0;
                    self.scroll_offset = 0;
                    self.cached_detail = None;
                }
            }
            Panel::Findings => {
                if self.selected_finding + 1 < self.finding_count() {
                    self.selected_finding += 1;
                    self.scroll_offset = 0;
                }
            }
            Panel::Detail => {
                // Clamp to `line_count - 1` so the last logical line stays
                // at least partially visible at the top of the viewport
                // when fully scrolled down. Prevents infinite scroll past
                // the content, which used to leave the panel blank.
                let max_offset = self.detail_panel_line_count().saturating_sub(1);
                if self.scroll_offset < max_offset {
                    self.scroll_offset = self.scroll_offset.saturating_add(1);
                }
            }
            Panel::Correlations => {
                if self.selected_correlation + 1 < self.correlation_count() {
                    self.selected_correlation += 1;
                }
            }
        }
    }

    /// Move focus to the next panel.
    pub fn next_panel(&mut self) {
        self.active_panel = match self.active_panel {
            Panel::Traces => Panel::Findings,
            Panel::Findings => Panel::Detail,
            Panel::Detail => Panel::Correlations,
            Panel::Correlations => Panel::Traces,
        };
    }

    /// Move focus to the previous panel.
    pub fn prev_panel(&mut self) {
        self.active_panel = match self.active_panel {
            Panel::Traces => Panel::Correlations,
            Panel::Findings => Panel::Traces,
            Panel::Detail => Panel::Findings,
            Panel::Correlations => Panel::Detail,
        };
    }

    /// Handle Enter key: drill into the next panel.
    ///
    /// - Traces -> Findings (when there are findings)
    /// - Findings -> Detail
    /// - Correlations -> Detail (jumps to `sample_trace_id` if known locally)
    /// - Detail -> Explain view (zooms the span tree full screen)
    pub fn enter(&mut self) {
        match self.active_panel {
            Panel::Traces => {
                if self.finding_count() > 0 {
                    self.active_panel = Panel::Findings;
                    self.selected_finding = 0;
                }
            }
            Panel::Findings => {
                self.enter_detail(Panel::Findings);
            }
            Panel::Correlations => {
                self.jump_to_correlation_sample_trace();
            }
            Panel::Detail => {
                // Deepest panel: zoom the span tree to the full-screen
                // Explain view.
                self.view = View::Explain;
                self.scroll_offset = 0;
            }
        }
    }

    /// Single entry point for any drill-down to `Panel::Detail`. Pairs
    /// `active_panel` with `detail_origin` so `escape` returns to the
    /// source panel. New drill-downs MUST route through this helper.
    fn enter_detail(&mut self, origin: Panel) {
        self.active_panel = Panel::Detail;
        self.detail_origin = origin;
        self.scroll_offset = 0;
    }

    /// Jump from Correlations to Detail for the selected correlation's
    /// `sample_trace_id`. No-op if the trace is unknown locally.
    fn jump_to_correlation_sample_trace(&mut self) {
        let Some(correlation) = self.correlations.get(self.selected_correlation) else {
            return;
        };
        let Some(sample_trace_id) = correlation.sample_trace_id.as_deref() else {
            return;
        };
        let Some(&position) = self.trace_index.get(sample_trace_id) else {
            return;
        };
        if position != self.selected_trace {
            self.selected_trace = position;
            self.cached_detail = None;
        }
        self.selected_finding = 0;
        self.enter_detail(Panel::Correlations);
    }

    /// Handle Escape: go back to previous panel. Detail returns to
    /// `detail_origin` (Findings or Correlations) so the operator lands
    /// back where the drill-down started.
    pub fn escape(&mut self) {
        match self.active_panel {
            // Top-level panels (reached by Tab cycling, not drilled into):
            // ascend to the Analyze view. The active panel is preserved so
            // descending lands back here, and both honor the tab-bar "Esc up"
            // hint rather than leaving Correlations a dead end.
            Panel::Traces | Panel::Correlations => {
                self.view = View::Analyze;
                self.scroll_offset = 0;
            }
            Panel::Findings => self.active_panel = Panel::Traces,
            Panel::Detail => self.active_panel = self.detail_origin,
        }
    }

    /// Logical line count of the Analyze view body, used to clamp the
    /// scroll offset. Returns the value cached by `with_summary` so the
    /// per-keypress clamp does not rebuild the line vector (the degraded
    /// no-summary hint is short and never needs scrolling, hence 0).
    fn analyze_content_line_count(&self) -> u16 {
        self.analyze_line_count
    }

    /// Logical line count of the Explain view body (the cached span tree
    /// for the selected trace, or the short unavailability hint).
    fn explain_content_line_count(&self) -> u16 {
        match &self.cached_detail {
            Some((ct, text)) if *ct == self.selected_trace => {
                u16::try_from(text.lines().count()).unwrap_or(u16::MAX)
            }
            _ => 2,
        }
    }

    /// Per-severity finding counts `(critical, warning, info)` over all
    /// findings, for the Analyze view header.
    fn severity_counts(&self) -> (usize, usize, usize) {
        let mut counts = (0usize, 0usize, 0usize);
        for finding in &self.all_findings {
            match finding.severity {
                Severity::Critical => counts.0 += 1,
                Severity::Warning => counts.1 += 1,
                Severity::Info => counts.2 += 1,
            }
        }
        counts
    }

    /// Build the Analyze view body as owned ratatui lines. Mirrors the
    /// sections of the CLI report (`render.rs`) — analysis metadata,
    /// findings by severity, I/O waste, top offenders, quality gate — but
    /// as widgets. All externally-sourced strings (endpoint, service) are
    /// sanitized for the terminal. Falls back to a hint when no summary
    /// was supplied (e.g. an older daemon without `/api/export/report`).
    fn build_analyze_lines(&self) -> Vec<Line<'static>> {
        let dim = Style::default().fg(Color::DarkGray);
        let Some(summary) = &self.summary else {
            return vec![
                Line::from(Span::styled("Summary unavailable.".to_string(), dim)),
                Line::from(Span::styled(
                    "No analysis summary was supplied (older daemon without /api/export/report?)."
                        .to_string(),
                    dim,
                )),
                Line::from(""),
                Line::from(Span::styled(
                    "Press Enter to inspect traces and findings.".to_string(),
                    dim,
                )),
            ];
        };
        let gs = &summary.green_summary;
        let (crit, warn, info) = self.severity_counts();
        let total = self.all_findings.len();
        let mut lines: Vec<Line<'static>> = Vec::new();

        lines.push(Line::from(vec![
            Span::styled("Traces analyzed: ".to_string(), dim),
            Span::raw(summary.analysis.traces_analyzed.to_string()),
            Span::styled("   Events: ".to_string(), dim),
            Span::raw(summary.analysis.events_processed.to_string()),
            Span::styled("   Duration: ".to_string(), dim),
            Span::raw(format!("{} ms", summary.analysis.duration_ms)),
        ]));
        lines.push(Line::from(""));

        lines.push(Line::from(vec![
            Span::styled("Findings: ".to_string(), dim),
            Span::styled(
                total.to_string(),
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::raw("   "),
            Span::styled(format!("{crit} critical"), Style::default().fg(Color::Red)),
            Span::raw(", "),
            Span::styled(
                format!("{warn} warning"),
                Style::default().fg(Color::Yellow),
            ),
            Span::raw(", "),
            Span::styled(format!("{info} info"), Style::default().fg(Color::Cyan)),
        ]));
        lines.push(Line::from(""));

        let band = gs.io_waste_ratio_band;
        lines.push(Line::from(vec![
            Span::styled("I/O waste ratio: ".to_string(), dim),
            // Percentage form, matching the CLI report (`print_green_summary`)
            // so the same metric does not read as a bare fraction here.
            Span::styled(
                format!("{:.1}%", gs.io_waste_ratio * 100.0),
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::raw(" "),
            Span::styled(
                format!("({})", band.short_label()),
                Style::default().fg(interpret_band_color(band)),
            ),
        ]));
        lines.push(Line::from(vec![
            Span::styled("Avoidable I/O: ".to_string(), dim),
            Span::raw(format!(
                "{} of {} ops",
                gs.avoidable_io_ops, gs.total_io_ops
            )),
        ]));
        if gs.energy_kwh > 0.0 {
            lines.push(Line::from(vec![
                Span::styled("Energy: ".to_string(), dim),
                Span::raw(format!("{:.6} kWh", gs.energy_kwh)),
                // `energy_model` is free text on the daemon snapshot path
                // (`query inspect`), so sanitize like the other daemon-sourced
                // strings below.
                Span::styled(
                    format!("  ({})", sanitize_for_terminal(&gs.energy_model)),
                    dim,
                ),
            ]));
        }
        // Structured CO2 report, mirroring the CLI `print_green_summary`
        // carbon block so the Analyze view does not silently omit the
        // headline carbon figures in carbon-configured deployments.
        if let Some(carbon) = gs.co2.as_ref() {
            // model/methodology are free `String`s on the daemon snapshot path
            // (`query inspect` reads them from /api/export/report), so sanitize
            // like the other daemon-sourced strings rendered above.
            let model = sanitize_for_terminal(&carbon.total.model);
            let methodology = sanitize_for_terminal(&carbon.total.methodology);
            lines.push(Line::from(Span::raw(format!(
                "Est. CO\u{2082}: {:.6} g (low {:.6}, high {:.6}, model {model})",
                carbon.total.mid, carbon.total.low, carbon.total.high,
            ))));
            lines.push(Line::from(Span::raw(format!(
                "Avoidable CO\u{2082}: {:.6} g (low {:.6}, high {:.6})",
                carbon.avoidable.mid, carbon.avoidable.low, carbon.avoidable.high,
            ))));
            lines.push(Line::from(Span::raw(format!(
                "Operational: {:.6} g   Embodied: {:.6} g   Methodology: {methodology}",
                carbon.operational_gco2, carbon.embodied_gco2,
            ))));
            if let Some(transport) = carbon.transport_gco2 {
                lines.push(Line::from(Span::raw(format!(
                    "Transport: {transport:.6} g (cross-region network bytes)"
                ))));
            }
        }
        lines.push(Line::from(""));

        if !gs.top_offenders.is_empty() {
            lines.push(Line::from(Span::styled(
                "Top offenders:".to_string(),
                Style::default().add_modifier(Modifier::BOLD),
            )));
            for offender in &gs.top_offenders {
                let oband = offender.io_intensity_band;
                let co2 = offender
                    .co2_grams
                    .map_or(String::new(), |c| format!(", {c:.6} gCO2"));
                lines.push(Line::from(vec![
                    Span::raw("  - ".to_string()),
                    Span::raw(sanitize_for_terminal(&offender.endpoint).into_owned()),
                    Span::styled(format!("  IIS {:.1} ", offender.io_intensity_score), dim),
                    Span::styled(
                        format!("({})", oband.short_label()),
                        Style::default().fg(interpret_band_color(oband)),
                    ),
                    Span::styled(
                        format!(
                            "  service: {}{}",
                            sanitize_for_terminal(&offender.service),
                            co2
                        ),
                        dim,
                    ),
                ]));
            }
            lines.push(Line::from(""));
        }

        let gate = &summary.quality_gate;
        // An empty rule set means the gate was never evaluated, e.g. a daemon
        // `/api/export/report` snapshot (which hardcodes passed=true, rules=[]).
        // Render that honestly rather than a misleading green PASSED sitting
        // next to live critical findings under `query inspect`.
        let (gate_label, gate_color) = if gate.rules.is_empty() {
            ("not evaluated", Color::DarkGray)
        } else if gate.passed {
            ("PASSED", Color::Green)
        } else {
            ("FAILED", Color::Red)
        };
        lines.push(Line::from(vec![
            Span::styled(
                "Quality gate: ".to_string(),
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                gate_label.to_string(),
                Style::default().fg(gate_color).add_modifier(Modifier::BOLD),
            ),
        ]));
        for rule in &gate.rules {
            let (rule_label, rule_color) = if rule.passed {
                ("PASS", Color::Green)
            } else {
                ("FAIL", Color::Red)
            };
            lines.push(Line::from(vec![
                Span::raw(format!("  - {}: ", sanitize_for_terminal(&rule.rule))),
                Span::styled(
                    format!("{:.2} (actual {:.2}) ", rule.threshold, rule.actual),
                    dim,
                ),
                Span::styled(rule_label.to_string(), Style::default().fg(rule_color)),
            ]));
        }

        // Mandatory uncertainty disclaimer whenever CO2 estimates are shown,
        // matching the CLI report.
        if gs.co2.is_some() {
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                "Note: CO\u{2082} estimates have ~2\u{00d7} multiplicative uncertainty (low = mid/2, high = mid\u{00d7}2). See docs/LIMITATIONS.md.".to_string(),
                dim,
            )));
        }
        // The bands use fixed heuristic thresholds, not the operator's config,
        // and the full per-region / scoring-config detail lives in the CLI
        // report. Flag both so the view is not mistaken for the full report.
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "Note: (healthy/moderate/high/critical) bands use fixed heuristic thresholds, independent of your config overrides.".to_string(),
            dim,
        )));
        lines.push(Line::from(Span::styled(
            "Per-region carbon breakdown and scoring config: run `analyze` for the full report."
                .to_string(),
            dim,
        )));
        lines
    }
}

/// State for the ack/revoke modal overlay. Lives on `App.ack_modal`.
/// `Default` is the hidden state, the modal is opened by `open_ack` /
/// `open_unack` from the `a` and `u` key handlers in `run_loop`.
#[cfg(feature = "daemon")]
#[derive(Debug, Default)]
pub struct AckModalState {
    pub mode: AckModalMode,
    /// Reason input buffer (max 256 chars, single-line).
    pub reason_buf: String,
    /// Expires input buffer (free text, parsed at submit time).
    pub expires_buf: String,
    /// Acknowledger identity buffer (max 128 chars). Pre-filled from $USER.
    pub by_buf: String,
    pub focus: AckFormField,
    /// Error message displayed at the bottom of the modal.
    pub error_message: Option<String>,
    /// Whether a request is currently in flight.
    pub submitting: bool,
}

#[cfg(feature = "daemon")]
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub enum AckModalMode {
    #[default]
    Hidden,
    /// Creating an ack for the given signature.
    Ack { signature: String },
    /// Revoking an existing ack for the given signature.
    Unack { signature: String },
}

#[cfg(feature = "daemon")]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum AckFormField {
    #[default]
    Reason,
    Expires,
    By,
    Submit,
    Cancel,
}

// Modal text-buffer character caps. Capping in chars (not bytes) so
// multi-byte UTF-8 input fills the buffer at the same rate the user
// sees typed characters. The daemon enforces server-side limits on
// reason / by anyway, these caps just keep the modal layout stable.
#[cfg(feature = "daemon")]
const REASON_MAX: usize = 256;
#[cfg(feature = "daemon")]
const EXPIRES_MAX: usize = 64;
#[cfg(feature = "daemon")]
const BY_MAX: usize = 128;

#[cfg(feature = "daemon")]
impl AckModalState {
    #[must_use]
    pub fn is_visible(&self) -> bool {
        !matches!(self.mode, AckModalMode::Hidden)
    }

    /// Open the modal in Ack mode with empty buffers and focus on
    /// Reason. `by_buf` is pre-filled from `$USER` (empty if unset).
    pub fn open_ack(&mut self, signature: String) {
        self.mode = AckModalMode::Ack { signature };
        self.reason_buf.clear();
        self.expires_buf.clear();
        self.by_buf = std::env::var("USER").unwrap_or_default();
        self.focus = AckFormField::Reason;
        self.error_message = None;
        self.submitting = false;
    }

    /// Open the modal in Unack mode (confirmation only, no form).
    /// Focus starts on Submit so a single Enter confirms the revoke.
    pub fn open_unack(&mut self, signature: String) {
        self.mode = AckModalMode::Unack { signature };
        self.reason_buf.clear();
        self.expires_buf.clear();
        self.by_buf.clear();
        self.focus = AckFormField::Submit;
        self.error_message = None;
        self.submitting = false;
    }

    pub fn close(&mut self) {
        self.mode = AckModalMode::Hidden;
        self.error_message = None;
        self.submitting = false;
    }

    pub fn next_field(&mut self) {
        self.focus = step_focus(self.focus_cycle(), self.focus, 1_isize);
    }

    pub fn prev_field(&mut self) {
        self.focus = step_focus(self.focus_cycle(), self.focus, -1_isize);
    }

    /// Tab-cycle for the current modal mode. Unack mode only exposes
    /// Submit/Cancel buttons, Ack mode walks the full form.
    fn focus_cycle(&self) -> &'static [AckFormField] {
        match self.mode {
            AckModalMode::Unack { .. } => &UNACK_FOCUS_CYCLE,
            _ => &ACK_FOCUS_CYCLE,
        }
    }
}

#[cfg(feature = "daemon")]
const ACK_FOCUS_CYCLE: [AckFormField; 5] = [
    AckFormField::Reason,
    AckFormField::Expires,
    AckFormField::By,
    AckFormField::Submit,
    AckFormField::Cancel,
];

#[cfg(feature = "daemon")]
const UNACK_FOCUS_CYCLE: [AckFormField; 2] = [AckFormField::Submit, AckFormField::Cancel];

/// Move along a focus cycle by `step` positions (positive forward,
/// negative backward), wrapping at both ends. Falls back to the first
/// entry when `current` is not in the cycle (e.g. opening a Unack
/// modal while the previous focus was on Reason).
#[cfg(feature = "daemon")]
fn step_focus(cycle: &[AckFormField], current: AckFormField, step: isize) -> AckFormField {
    let len = i32::try_from(cycle.len()).unwrap_or(1).max(1);
    let step = i32::try_from(step).unwrap_or(0);
    let idx = cycle
        .iter()
        .position(|f| *f == current)
        .and_then(|p| i32::try_from(p).ok())
        .unwrap_or(0);
    let next = (idx + step).rem_euclid(len);
    let next_usize = usize::try_from(next).unwrap_or(0);
    cycle[next_usize]
}

/// Outcome of a single key press inside the modal. The run loop reacts
/// by closing, submitting, or doing nothing.
#[cfg(feature = "daemon")]
#[derive(Debug, PartialEq, Eq)]
pub enum ModalAction {
    None,
    Cancel,
    Submit,
}

/// Result of an ack/revoke roundtrip executed off the run loop.
/// The async task sends one of these through the outcome channel,
/// `apply_ack_outcome` applies it the next time the loop tick drains.
/// `Success.refreshed_acks` is `None` when the post-write refetch failed
/// (keep the previous snapshot), `Some(map)` otherwise even if empty
/// (legitimate "all acks expired" state).
#[cfg(feature = "daemon")]
#[derive(Debug)]
pub(crate) enum AckOutcome {
    Success {
        refreshed_acks: Option<HashMap<String, AckSource>>,
    },
    Failure {
        message: String,
    },
}

/// Snapshot of every modal/app field the spawned task needs.
/// Owned and `'static` so the future can outlive the run loop borrow.
/// Manual `Debug` so a future `tracing!("{payload:?}")` cannot leak the
/// API key, mirroring the discipline in `AuthHeader::Debug` and
/// `redact_endpoint`.
#[cfg(feature = "daemon")]
pub(crate) struct AckSubmitPayload {
    daemon_url: String,
    signature: String,
    api_key: Option<String>,
    op: AckSubmitOp,
}

#[cfg(feature = "daemon")]
impl std::fmt::Debug for AckSubmitPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AckSubmitPayload")
            .field("daemon_url", &self.daemon_url)
            .field("signature", &self.signature)
            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
            .field("op", &self.op)
            .finish()
    }
}

#[cfg(feature = "daemon")]
#[derive(Debug)]
pub(crate) enum AckSubmitOp {
    Create {
        by: String,
        reason: String,
        expires_at: Option<DateTime<Utc>>,
    },
    Revoke,
}

#[cfg(feature = "daemon")]
impl AckSubmitPayload {
    /// Capture the modal state and validate `expires_buf` synchronously.
    /// A parse error short-circuits before any spawn happens, so the
    /// `Validation` variant lands in `error_message` without a network
    /// round-trip.
    pub(crate) fn from_modal(app: &App) -> Result<Self, crate::ack::AckSubmitError> {
        let daemon_url = app.daemon_url.clone().ok_or_else(|| {
            crate::ack::AckSubmitError::Validation("daemon not configured".into())
        })?;
        let signature = signature_for_modal_mode(&app.ack_modal.mode)
            .map(str::to_string)
            .ok_or_else(|| crate::ack::AckSubmitError::Validation("modal not visible".into()))?;
        let api_key = app.api_key.clone();
        let op = match app.ack_modal.mode {
            AckModalMode::Ack { .. } => {
                let expires_at = if app.ack_modal.expires_buf.trim().is_empty() {
                    None
                } else {
                    match crate::ack::parse_expires(&app.ack_modal.expires_buf) {
                        Ok(dt) => Some(dt),
                        Err(e) => {
                            return Err(crate::ack::AckSubmitError::Validation(format!(
                                "expires: {e}"
                            )));
                        }
                    }
                };
                AckSubmitOp::Create {
                    by: app.ack_modal.by_buf.clone(),
                    reason: app.ack_modal.reason_buf.clone(),
                    expires_at,
                }
            }
            AckModalMode::Unack { .. } => AckSubmitOp::Revoke,
            AckModalMode::Hidden => unreachable!("guarded by signature_for_modal_mode above"),
        };
        Ok(Self {
            daemon_url,
            signature,
            api_key,
            op,
        })
    }
}

/// Pure function that maps a `KeyCode` to a `ModalAction` while mutating
/// the form buffers. Tested without spinning up a real terminal.
#[cfg(feature = "daemon")]
pub fn handle_modal_key(modal: &mut AckModalState, code: KeyCode) -> ModalAction {
    match code {
        KeyCode::Esc => ModalAction::Cancel,
        KeyCode::Tab => {
            modal.next_field();
            ModalAction::None
        }
        KeyCode::BackTab => {
            modal.prev_field();
            ModalAction::None
        }
        KeyCode::Enter => match modal.focus {
            AckFormField::Submit => ModalAction::Submit,
            AckFormField::Cancel => ModalAction::Cancel,
            _ => {
                modal.next_field();
                ModalAction::None
            }
        },
        KeyCode::Char(c) => {
            push_char_into_focused_buffer(modal, c);
            ModalAction::None
        }
        KeyCode::Backspace => {
            match modal.focus {
                AckFormField::Reason => {
                    modal.reason_buf.pop();
                }
                AckFormField::Expires => {
                    modal.expires_buf.pop();
                }
                AckFormField::By => {
                    modal.by_buf.pop();
                }
                AckFormField::Submit | AckFormField::Cancel => {}
            }
            ModalAction::None
        }
        _ => ModalAction::None,
    }
}

#[cfg(feature = "daemon")]
fn push_char_into_focused_buffer(modal: &mut AckModalState, c: char) {
    // Defense-in-depth: refuse C0/C1 controls and bidi overrides on
    // typed input. The daemon strips them server-side too, but a
    // bracketed paste of an attacker-crafted signature could otherwise
    // skew the modal layout for the operator who is approving it.
    if !is_modal_input_char_acceptable(c) {
        return;
    }
    match modal.focus {
        AckFormField::Reason if modal.reason_buf.chars().count() < REASON_MAX => {
            modal.reason_buf.push(c);
        }
        AckFormField::Expires if modal.expires_buf.chars().count() < EXPIRES_MAX => {
            modal.expires_buf.push(c);
        }
        AckFormField::By if modal.by_buf.chars().count() < BY_MAX => {
            modal.by_buf.push(c);
        }
        _ => {}
    }
}

#[cfg(feature = "daemon")]
fn is_modal_input_char_acceptable(c: char) -> bool {
    // C0 / C1 / DEL controls would corrupt the rendered modal.
    if c.is_control() {
        return false;
    }
    // Bidi overrides and isolates can flip the visible order of the
    // surrounding text, including the modal labels and buttons.
    !matches!(c as u32, 0x202A..=0x202E | 0x2066..=0x2069)
}

/// Install a panic hook that restores the terminal before the
/// standard hook prints the panic message. Without this, a panic
/// inside `run_loop` (e.g. from a future ratatui upgrade or from a
/// `block_on` in `submit_ack_modal`) leaves the operator with raw
/// mode + alternate screen still active, forcing a `reset` in their
/// shell.
///
/// Wrapped in `Once` so that calling `run` twice in the same process
/// (test re-entry, future embedding) does not stack hooks. The chain
/// to the previous hook is captured at first install and persists for
/// the process lifetime.
fn install_terminal_restore_panic_hook() {
    static INSTALL: std::sync::Once = std::sync::Once::new();
    INSTALL.call_once(|| {
        let prev_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            let _ = disable_raw_mode();
            let _ = crossterm::execute!(io::stdout(), LeaveAlternateScreen);
            prev_hook(info);
        }));
    });
}

/// Run the TUI event loop.
///
/// # Errors
///
/// Returns an error if terminal setup or event reading fails.
pub fn run(app: &mut App) -> io::Result<()> {
    install_terminal_restore_panic_hook();
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    crossterm::execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let result = run_loop(&mut terminal, app);

    disable_raw_mode()?;
    crossterm::execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    result
}

/// Outcome of a single keystroke at the run-loop level. The loop
/// returns `Quit` to break out, `Continue` to repaint and wait for the
/// next event.
#[derive(Debug)]
enum KeyOutcome {
    Continue,
    Quit,
}

fn run_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
) -> io::Result<()> {
    // Channel: spawned ack/revoke tasks send their outcome here, the
    // loop drains it before each redraw so the modal closes (or shows
    // the error) without blocking on the HTTP roundtrip.
    #[cfg(feature = "daemon")]
    let (tx_outcome, mut rx_outcome) = mpsc::unbounded_channel::<AckOutcome>();
    loop {
        #[cfg(feature = "daemon")]
        while let Ok(outcome) = rx_outcome.try_recv() {
            apply_ack_outcome(app, outcome);
        }
        // Pre-compute detail tree text (requires &mut self) before immutable
        // draw. Only the Inspect (Detail panel) and Explain views render it,
        // so skip the detect + build_tree + clone work in the Analyze view.
        if matches!(app.view, View::Inspect | View::Explain) {
            app.detail_tree_text();
        }
        terminal.draw(|f| draw(f, app))?;

        // Block on `event::read` when no ack is in flight (0fps idle,
        // matches the pre-refactor power profile). Poll with a short
        // timeout only when a spawned task may push an outcome we need
        // to apply quickly.
        #[cfg(feature = "daemon")]
        let submitting = app.ack_modal.submitting;
        #[cfg(not(feature = "daemon"))]
        let submitting = false;
        if submitting && !event::poll(Duration::from_millis(50))? {
            continue;
        }
        if let Event::Key(key) = event::read()?
            && key.kind == KeyEventKind::Press
        {
            #[cfg(feature = "daemon")]
            let outcome = handle_keystroke(app, key.code, &tx_outcome);
            #[cfg(not(feature = "daemon"))]
            let outcome = handle_keystroke(app, key.code);
            if matches!(outcome, KeyOutcome::Quit) {
                return Ok(());
            }
        }
    }
}

/// Dispatch a single keystroke. Modal-visible keys route to the form
/// handler, otherwise the standard panel-navigation keys + the
/// `a`/`u` ack shortcuts apply.
fn handle_keystroke(
    app: &mut App,
    code: KeyCode,
    #[cfg(feature = "daemon")] tx_outcome: &mpsc::UnboundedSender<AckOutcome>,
) -> KeyOutcome {
    #[cfg(feature = "daemon")]
    if app.ack_modal.is_visible() {
        dispatch_modal_key(app, code, tx_outcome);
        return KeyOutcome::Continue;
    }
    match app.view {
        View::Analyze => dispatch_analyze_key(app, code),
        View::Inspect => dispatch_panel_key(app, code),
        View::Explain => dispatch_explain_key(app, code),
        View::Disclose => dispatch_disclose_key(app, code),
    }
}

/// Keys for the standalone Disclose preview: `g` cycles granularity,
/// `\u{2190}/\u{2192}` (`h`/`l`) step the period (or the active custom edge by a day),
/// `[`/`]` move the active custom edge by a month, `Tab` switches the
/// custom edge, `i`/`c` toggle intent/confidentiality, `\u{2191}/\u{2193}` (`j`/`k`)
/// scroll the summary. No view switching (the tab is autonomous).
fn dispatch_disclose_key(app: &mut App, code: KeyCode) -> KeyOutcome {
    let Some(state) = app.disclose.as_mut() else {
        return KeyOutcome::Continue;
    };
    match code {
        KeyCode::Char('q') => return KeyOutcome::Quit,
        KeyCode::Char('g') => state.cycle_granularity(),
        KeyCode::Left | KeyCode::Char('h') => state.step(false),
        KeyCode::Right | KeyCode::Char('l') => state.step(true),
        KeyCode::Char('[') => state.step_month(false),
        KeyCode::Char(']') => state.step_month(true),
        KeyCode::Tab | KeyCode::BackTab => state.toggle_custom_field(),
        KeyCode::Char('i') => state.toggle_intent(),
        KeyCode::Char('c') => state.toggle_confidentiality(),
        KeyCode::Up | KeyCode::Char('k') => state.scroll(false),
        KeyCode::Down | KeyCode::Char('j') => state.scroll(true),
        _ => {}
    }
    KeyOutcome::Continue
}

/// Keys for the Analyze view: scroll the summary, Enter descends to the
/// Inspect view (keeping the active panel), Esc is a no-op (top of the
/// drill-down).
fn dispatch_analyze_key(app: &mut App, code: KeyCode) -> KeyOutcome {
    match code {
        KeyCode::Char('q') => return KeyOutcome::Quit,
        KeyCode::Up | KeyCode::Char('k') => {
            app.scroll_offset = app.scroll_offset.saturating_sub(1);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            let max = app.analyze_content_line_count().saturating_sub(1);
            if app.scroll_offset < max {
                app.scroll_offset = app.scroll_offset.saturating_add(1);
            }
        }
        KeyCode::Enter => {
            // Descend to Inspect, keeping active_panel as-is so an
            // Esc-then-Enter round-trip lands back on the panel ascended from
            // (Traces or Correlations). A fresh `analyze --tui` launch already
            // has active_panel == Traces by default.
            app.view = View::Inspect;
            app.scroll_offset = 0;
        }
        _ => {}
    }
    KeyOutcome::Continue
}

/// Keys for the Explain view: scroll the span tree, Esc ascends back to
/// the Inspect view's Detail panel.
fn dispatch_explain_key(app: &mut App, code: KeyCode) -> KeyOutcome {
    match code {
        KeyCode::Char('q') => return KeyOutcome::Quit,
        KeyCode::Up | KeyCode::Char('k') => {
            app.scroll_offset = app.scroll_offset.saturating_sub(1);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            let max = app.explain_content_line_count().saturating_sub(1);
            if app.scroll_offset < max {
                app.scroll_offset = app.scroll_offset.saturating_add(1);
            }
        }
        KeyCode::Esc => {
            app.view = View::Inspect;
            app.active_panel = Panel::Detail;
            app.scroll_offset = 0;
        }
        _ => {}
    }
    KeyOutcome::Continue
}

#[cfg(feature = "daemon")]
fn dispatch_modal_key(
    app: &mut App,
    code: KeyCode,
    tx_outcome: &mpsc::UnboundedSender<AckOutcome>,
) {
    match handle_modal_key(&mut app.ack_modal, code) {
        ModalAction::None => {}
        ModalAction::Cancel => app.ack_modal.close(),
        ModalAction::Submit => submit_ack_modal(app, tx_outcome),
    }
}

fn dispatch_panel_key(app: &mut App, code: KeyCode) -> KeyOutcome {
    match code {
        KeyCode::Char('q') => return KeyOutcome::Quit,
        KeyCode::Up | KeyCode::Char('k') => app.move_up(),
        KeyCode::Down | KeyCode::Char('j') => app.move_down(),
        KeyCode::Right | KeyCode::Tab | KeyCode::Char('l') => app.next_panel(),
        KeyCode::Left | KeyCode::BackTab | KeyCode::Char('h') => app.prev_panel(),
        KeyCode::Enter => app.enter(),
        KeyCode::Esc => app.escape(),
        #[cfg(feature = "daemon")]
        KeyCode::Char('a') => open_ack_modal_for_current(app, false),
        #[cfg(feature = "daemon")]
        KeyCode::Char('u') => open_ack_modal_for_current(app, true),
        _ => {}
    }
    KeyOutcome::Continue
}

#[cfg(feature = "daemon")]
fn open_ack_modal_for_current(app: &mut App, revoke: bool) {
    if app.daemon_url.is_none() {
        return;
    }
    let Some(sig) = app.current_finding().map(|f| f.signature.clone()) else {
        return;
    };
    if revoke {
        app.ack_modal.open_unack(sig);
    } else {
        app.ack_modal.open_ack(sig);
    }
}

fn draw(f: &mut Frame, app: &App) {
    // One-line tab bar on top, the active view fills the rest.
    let outer = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(0)])
        .split(f.area());

    draw_tab_bar(f, app, outer[0]);
    match app.view {
        View::Analyze => draw_analyze_view(f, app, outer[1]),
        View::Inspect => draw_inspect_view(f, app, outer[1]),
        View::Explain => draw_explain_view(f, app, outer[1]),
        View::Disclose => draw_disclose_view(f, app, outer[1]),
    }

    #[cfg(feature = "daemon")]
    if app.ack_modal.is_visible() {
        draw_ack_modal(f, app);
    }
}

/// Top tab bar: the three views with the active one highlighted, plus the
/// view-level navigation hint. Purely a visual orientation aid — the keys
/// that switch views are Enter (down) and Esc (up), bound per view.
fn draw_tab_bar(f: &mut Frame, app: &App, area: Rect) {
    let dim = Style::default().fg(Color::DarkGray);
    // The standalone Disclose tab replaces the drill-down bar entirely.
    if app.disclose.is_some() {
        let spans = vec![
            Span::raw(" "),
            Span::styled(
                " Disclose ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD | Modifier::REVERSED),
            ),
            Span::styled(
                "    g granularity \u{00b7} \u{2190}/\u{2192} period \u{00b7} i intent \u{00b7} c confidentiality \u{00b7} q quit"
                    .to_string(),
                dim,
            ),
        ];
        f.render_widget(Paragraph::new(Line::from(spans)), area);
        return;
    }
    let mut spans = vec![Span::raw(" ")];
    for (i, (view, label)) in [
        (View::Analyze, "Analyze"),
        (View::Inspect, "Inspect"),
        (View::Explain, "Explain"),
    ]
    .iter()
    .enumerate()
    {
        if i > 0 {
            spans.push(Span::styled(" \u{25b8} ", dim));
        }
        let style = if app.view == *view {
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD | Modifier::REVERSED)
        } else {
            dim
        };
        spans.push(Span::styled(format!(" {label} "), style));
    }
    spans.push(Span::styled(
        "    Enter \u{2193} \u{00b7} Esc \u{2191} \u{00b7} q quit".to_string(),
        dim,
    ));
    f.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// The Inspect view: the 4-panel browser (traces, findings, correlations,
/// detail). Body of the former top-level `draw`.
fn draw_inspect_view(f: &mut Frame, app: &App, area: Rect) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(area);

    let top = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(20),
            Constraint::Percentage(45),
            Constraint::Percentage(35),
        ])
        .split(chunks[0]);

    draw_traces_panel(f, app, top[0]);
    draw_findings_panel(f, app, top[1]);
    draw_correlations_panel(f, app, top[2]);
    draw_detail_panel(f, app, chunks[1]);
}

/// The Analyze view: `GreenOps` summary dashboard, scrollable.
fn draw_analyze_view(f: &mut Frame, app: &App, area: Rect) {
    let block = Block::default()
        .title(" Analyze ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan));
    let paragraph = Paragraph::new(app.build_analyze_lines())
        .block(block)
        .wrap(Wrap { trim: false })
        .scroll((app.scroll_offset, 0));
    f.render_widget(paragraph, area);
}

/// The Explain view: the selected trace's annotated span tree, full
/// screen and scrollable. Reuses the per-trace tree cached for the Detail
/// panel (pre-computed before each draw in `run_loop`).
fn draw_explain_view(f: &mut Frame, app: &App, area: Rect) {
    let trace_id = app
        .trace_ids
        .get(app.selected_trace)
        .map_or("-", String::as_str);
    let block = Block::default()
        .title(format!(
            " Explain \u{00b7} {} ",
            sanitize_for_terminal(trace_id)
        ))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan));

    let lines: Vec<Line> = match &app.cached_detail {
        // Borrow the cached tree lines for the frame instead of allocating a
        // fresh String per visible line on every repaint.
        Some((ct, text)) if *ct == app.selected_trace => text.lines().map(Line::from).collect(),
        _ => vec![
            Line::from(Span::styled(
                "Span tree not available for this trace.",
                Style::default().fg(Color::DarkGray),
            )),
            Line::from(Span::styled(
                "Reports do not carry raw spans. Launch `inspect --input <events>.json` or `query inspect`.",
                Style::default().fg(Color::DarkGray),
            )),
        ],
    };

    let paragraph = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false })
        .scroll((app.scroll_offset, 0));
    f.render_widget(paragraph, area);
}

/// The standalone Disclose preview view: a fixed settings header, the
/// scrollable aggregated summary, and a footer with the equivalent
/// `disclose` command to copy.
fn draw_disclose_view(f: &mut Frame, app: &App, area: Rect) {
    let Some(state) = app.disclose.as_ref() else {
        return;
    };
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(6),
            Constraint::Min(0),
            Constraint::Length(4),
        ])
        .split(area);

    draw_disclose_settings(f, state, chunks[0]);

    let summary_lines: Vec<Line> = state
        .summary_lines()
        .iter()
        .map(|l| Line::from(Span::styled(l.text.clone(), tone_style(l.tone))))
        .collect();
    let summary = Paragraph::new(summary_lines)
        .block(
            Block::default()
                .title(" Summary ")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Cyan)),
        )
        .wrap(Wrap { trim: false })
        .scroll((state.scroll_offset(), 0));
    f.render_widget(summary, chunks[1]);

    let command = sanitize_for_terminal(&state.equivalent_command()).into_owned();
    let footer = Paragraph::new(command)
        .block(
            Block::default()
                .title(" Equivalent command (run it to write the hashed report) ")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::DarkGray)),
        )
        .wrap(Wrap { trim: false });
    f.render_widget(footer, chunks[2]);
}

fn draw_disclose_settings(f: &mut Frame, state: &DiscloseState, area: Rect) {
    let dim = Style::default().fg(Color::DarkGray);
    let cyan = Style::default().fg(Color::Cyan);
    let (from, to) = state.resolved_dates();

    let mut lines = vec![
        Line::from(vec![
            Span::styled("Granularity: ", dim),
            Span::styled(
                format!("\u{2039} {} \u{203a}", state.granularity().label()),
                cyan.add_modifier(Modifier::BOLD),
            ),
            Span::styled("    Intent: ", dim),
            Span::styled(intent_label(state.intent()), Style::default()),
            Span::styled("    Confidentiality: ", dim),
            Span::styled(
                confidentiality_label(state.confidentiality()),
                Style::default(),
            ),
        ]),
        Line::from(vec![
            Span::styled("Period: ", dim),
            Span::styled(
                format!("{from} \u{2192} {to}"),
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::styled(format!("  ({} days)", state.days_covered()), dim),
        ]),
    ];

    let archive = match state.archive_range() {
        Some((min, max)) => format!("Archive: {} .. {}", min.date_naive(), max.date_naive()),
        None => "Archive: empty".to_string(),
    };
    lines.push(Line::from(Span::styled(archive, dim)));

    if state.granularity() == Granularity::Custom {
        let (from_focus, to_focus) = match state.custom_field() {
            CustomField::From => (cyan.add_modifier(Modifier::REVERSED), dim),
            CustomField::To => (dim, cyan.add_modifier(Modifier::REVERSED)),
        };
        lines.push(Line::from(vec![
            Span::styled("Editing: ", dim),
            Span::styled(" from ", from_focus),
            Span::styled("  ", dim),
            Span::styled(" to ", to_focus),
            Span::styled(
                "    Tab switch \u{00b7} \u{2190}/\u{2192} \u{00b1}1 day \u{00b7} [ ] \u{00b1}1 month",
                dim,
            ),
        ]));
    }

    let paragraph = Paragraph::new(lines).block(
        Block::default()
            .title(" Settings ")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Cyan)),
    );
    f.render_widget(paragraph, area);
}

fn intent_label(intent: ReportIntent) -> &'static str {
    match intent {
        ReportIntent::Internal => "internal",
        ReportIntent::Official => "official",
        ReportIntent::Audited => "audited",
    }
}

fn confidentiality_label(confidentiality: Confidentiality) -> &'static str {
    match confidentiality {
        Confidentiality::Internal => "internal (G1)",
        Confidentiality::Public => "public (G2)",
    }
}

fn tone_style(tone: Tone) -> Style {
    match tone {
        Tone::Header => Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
        Tone::Normal => Style::default(),
        Tone::Dim => Style::default().fg(Color::DarkGray),
        Tone::Good => Style::default().fg(Color::Green),
        Tone::Warn => Style::default().fg(Color::Yellow),
        Tone::Bad => Style::default().fg(Color::Red),
    }
}

/// Map an interpretation band to a terminal color, matching the CLI
/// report's `interpret_color` (`render.rs`) exactly so the same band reads
/// the same in `analyze` stdout and the TUI: Critical red, High yellow,
/// Moderate uncolored (it is a non-empirical rule of thumb, kept neutral so
/// it does not compete with High), Healthy green.
fn interpret_band_color(level: InterpretationLevel) -> Color {
    match level {
        InterpretationLevel::Healthy => Color::Green,
        InterpretationLevel::Moderate => Color::Reset,
        InterpretationLevel::High => Color::Yellow,
        InterpretationLevel::Critical => Color::Red,
    }
}

fn panel_style(app: &App, panel: Panel) -> Style {
    if app.active_panel == panel {
        Style::default().fg(Color::Cyan)
    } else {
        Style::default().fg(Color::DarkGray)
    }
}

fn draw_traces_panel(f: &mut Frame, app: &App, area: Rect) {
    let items: Vec<ListItem> = app
        .trace_ids
        .iter()
        .enumerate()
        .map(|(i, tid)| {
            let finding_count = app.findings_by_trace.get(i).map_or(0, Vec::len);
            let label = if finding_count > 0 {
                format!("{tid} ({finding_count})")
            } else {
                tid.clone()
            };
            ListItem::new(Line::from(label))
        })
        .collect();

    let block = Block::default()
        .title(" Traces ")
        .borders(Borders::ALL)
        .border_style(panel_style(app, Panel::Traces));

    let mut state = ListState::default();
    state.select(Some(app.selected_trace));

    let list = List::new(items).block(block).highlight_style(
        Style::default()
            .add_modifier(Modifier::BOLD)
            .add_modifier(Modifier::REVERSED),
    );

    f.render_stateful_widget(list, area, &mut state);
}

fn draw_findings_panel(f: &mut Frame, app: &App, area: Rect) {
    let indices = app.current_finding_indices();
    let items: Vec<ListItem> = indices
        .iter()
        .enumerate()
        .map(|(i, &idx)| {
            let finding = &app.all_findings[idx];
            let severity_color = severity_color(&finding.severity);
            let type_label = finding_type_label(&finding.finding_type);
            let mut spans = vec![
                Span::styled(
                    format!("[{}] ", i + 1),
                    Style::default().fg(Color::DarkGray),
                ),
                Span::styled(
                    format!("{type_label} "),
                    Style::default()
                        .fg(severity_color)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    severity_label(&finding.severity),
                    Style::default().fg(severity_color),
                ),
            ];
            #[cfg(feature = "daemon")]
            if let Some(ack) = app.acks_by_signature.get(&finding.signature) {
                let by = match ack {
                    AckSource::Toml {
                        acknowledged_by, ..
                    } => acknowledged_by.as_str(),
                    AckSource::Daemon { by, .. } => by.as_str(),
                };
                spans.push(Span::raw(" "));
                spans.push(Span::styled(
                    format!("[acked by {}]", sanitize_for_terminal(by)),
                    Style::default()
                        .fg(Color::DarkGray)
                        .add_modifier(Modifier::ITALIC),
                ));
            }
            ListItem::new(Line::from(spans))
        })
        .collect();

    let block = Block::default()
        .title(" Findings ")
        .borders(Borders::ALL)
        .border_style(panel_style(app, Panel::Findings));

    let mut state = ListState::default();
    if !indices.is_empty() {
        state.select(Some(app.selected_finding));
    }

    let list = List::new(items).block(block).highlight_style(
        Style::default()
            .add_modifier(Modifier::BOLD)
            .add_modifier(Modifier::REVERSED),
    );

    f.render_stateful_widget(list, area, &mut state);
}

fn draw_correlations_panel(f: &mut Frame, app: &App, area: Rect) {
    let block = Block::default()
        .title(" Correlations ")
        .borders(Borders::ALL)
        .border_style(panel_style(app, Panel::Correlations));

    if app.correlations.is_empty() {
        let hint = Paragraph::new(
            "No correlations available.\n\nLaunch via 'query inspect' against a daemon to see cross-trace pairs.",
        )
        .block(block)
        .wrap(Wrap { trim: true })
        .style(Style::default().fg(Color::DarkGray));
        f.render_widget(hint, area);
        return;
    }

    let items: Vec<ListItem> = app
        .correlations
        .iter()
        .map(|c| {
            let line = Line::from(vec![
                Span::styled(
                    format!(
                        "{}:{} ",
                        sanitize_for_terminal(&c.source.service),
                        c.source.finding_type.as_str()
                    ),
                    Style::default().fg(Color::Yellow),
                ),
                Span::raw("-> "),
                Span::styled(
                    format!(
                        "{}:{}  ",
                        sanitize_for_terminal(&c.target.service),
                        c.target.finding_type.as_str()
                    ),
                    Style::default().fg(Color::Cyan),
                ),
                Span::styled(
                    format!("{:.0}% ", c.confidence * 100.0),
                    Style::default().add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    format!("{:.0}ms ", c.median_lag_ms),
                    Style::default().fg(Color::DarkGray),
                ),
                Span::raw(format!("({}x)", c.co_occurrence_count)),
            ]);
            ListItem::new(line)
        })
        .collect();

    let mut state = ListState::default();
    state.select(Some(app.selected_correlation));

    let list = List::new(items).block(block).highlight_style(
        Style::default()
            .add_modifier(Modifier::BOLD)
            .add_modifier(Modifier::REVERSED),
    );

    f.render_stateful_widget(list, area, &mut state);
}

fn draw_detail_panel(f: &mut Frame, app: &App, area: Rect) {
    let block = Block::default()
        .title(" Detail ")
        .borders(Borders::ALL)
        .border_style(panel_style(app, Panel::Detail));

    let Some(finding) = app.current_finding() else {
        let help = Paragraph::new("Select a finding to see details.\n\nKeys: ↑↓/jk navigate · ←→/hl/Tab panels · Enter deeper · Esc up · q quit")
            .block(block)
            .wrap(Wrap { trim: false });
        f.render_widget(help, area);
        return;
    };

    let severity_color = severity_color(&finding.severity);
    let type_label = finding_type_label(&finding.finding_type);

    let mut lines = vec![
        Line::from(vec![
            Span::styled(
                format!("{type_label} "),
                Style::default()
                    .fg(severity_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                severity_label(&finding.severity),
                Style::default().fg(severity_color),
            ),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled("Template: ", Style::default().fg(Color::DarkGray)),
            Span::raw(&finding.pattern.template),
        ]),
        Line::from(vec![
            Span::styled("Occurrences: ", Style::default().fg(Color::DarkGray)),
            Span::raw(format!(
                "{}, {} distinct params, {}ms window",
                finding.pattern.occurrences,
                finding.pattern.distinct_params,
                finding.pattern.window_ms
            )),
        ]),
        Line::from(vec![
            Span::styled("Service: ", Style::default().fg(Color::DarkGray)),
            Span::raw(&finding.service),
        ]),
        Line::from(vec![
            Span::styled("Endpoint: ", Style::default().fg(Color::DarkGray)),
            Span::raw(&finding.source_endpoint),
        ]),
        Line::from(vec![
            Span::styled("Suggestion: ", Style::default().fg(Color::Cyan)),
            Span::raw(&finding.suggestion),
        ]),
    ];

    if let Some(ref loc) = finding.code_location {
        let src = loc.display_string();
        if !src.is_empty() {
            lines.insert(
                6,
                Line::from(vec![
                    Span::styled("Source:   ", Style::default().fg(Color::DarkGray)),
                    Span::raw(src),
                ]),
            );
        }
    }

    if let Some(ref impact) = finding.green_impact {
        lines.push(Line::from(vec![
            Span::styled("Extra I/O: ", Style::default().fg(Color::DarkGray)),
            Span::raw(format!("{} avoidable ops", impact.estimated_extra_io_ops)),
        ]));
    }

    // Add span tree from cache (pre-computed before draw, cached per trace)
    if let Some((ct, ref tree_text)) = app.cached_detail
        && ct == app.selected_trace
    {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "Span tree:",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )));
        for tree_line in tree_text.lines() {
            lines.push(Line::from(tree_line.to_string()));
        }
    } else {
        // No span tree available: the input was a Report (no embedded
        // spans) or a daemon trace that the explain endpoint did not
        // return. Surface the two paths that produce a real tree so
        // the user knows what to try next.
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "Span tree:",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )));
        lines.push(Line::from(Span::styled(
            "Not available for this trace. Reports do not carry raw spans.",
            Style::default().fg(Color::DarkGray),
        )));
        lines.push(Line::from(Span::styled(
            "  - perf-sentinel inspect --input <events>.json  (raw events)",
            Style::default().fg(Color::DarkGray),
        )));
        lines.push(Line::from(Span::styled(
            "  - perf-sentinel query inspect                  (live daemon)",
            Style::default().fg(Color::DarkGray),
        )));
    }

    let paragraph = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false })
        .scroll((app.scroll_offset, 0));

    f.render_widget(paragraph, area);
}

#[cfg(feature = "daemon")]
fn draw_ack_modal(f: &mut Frame, app: &App) {
    let area = f.area();
    // 70 cols accommodate the footer hint and the unack confirmation
    // message at full width on a typical terminal. Clamped down on
    // narrow terminals to keep the modal inside the screen.
    let modal_w = 70.min(area.width.saturating_sub(4));
    let modal_h: u16 = match app.ack_modal.mode {
        AckModalMode::Ack { .. } => 16,
        AckModalMode::Unack { .. } => 8,
        AckModalMode::Hidden => return,
    };
    let modal_area = centered_rect(modal_w, modal_h, area);
    f.render_widget(Clear, modal_area);

    let title = match app.ack_modal.mode {
        AckModalMode::Ack { .. } => " Acknowledge finding ",
        AckModalMode::Unack { .. } => " Revoke acknowledgment ",
        AckModalMode::Hidden => return,
    };
    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan));
    let inner = block.inner(modal_area);
    f.render_widget(block, modal_area);

    match app.ack_modal.mode {
        AckModalMode::Ack { ref signature } => draw_ack_form(f, app, inner, signature),
        AckModalMode::Unack { ref signature } => draw_unack_form(f, app, inner, signature),
        AckModalMode::Hidden => {}
    }
}

#[cfg(feature = "daemon")]
fn draw_ack_form(f: &mut Frame, app: &App, area: Rect, signature: &str) {
    let constraints = [
        Constraint::Length(1), // signature
        Constraint::Length(1), // blank
        Constraint::Length(1), // reason label
        Constraint::Length(1), // reason input
        Constraint::Length(1), // expires label
        Constraint::Length(1), // expires input
        Constraint::Length(1), // by label
        Constraint::Length(1), // by input
        Constraint::Length(1), // blank
        Constraint::Length(1), // buttons
        Constraint::Min(1),    // error / hint
    ];
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(area);

    render_finding_signature_line(f, rows[0], signature);
    render_field_label(
        f,
        rows[2],
        "Reason (required)",
        app.ack_modal.focus,
        AckFormField::Reason,
    );
    render_field_input(
        f,
        rows[3],
        &app.ack_modal.reason_buf,
        app.ack_modal.focus == AckFormField::Reason,
    );
    render_field_label(
        f,
        rows[4],
        "Expires (e.g. 24h, 7d, ISO8601)",
        app.ack_modal.focus,
        AckFormField::Expires,
    );
    render_field_input(
        f,
        rows[5],
        &app.ack_modal.expires_buf,
        app.ack_modal.focus == AckFormField::Expires,
    );
    render_field_label(f, rows[6], "By", app.ack_modal.focus, AckFormField::By);
    render_field_input(
        f,
        rows[7],
        &app.ack_modal.by_buf,
        app.ack_modal.focus == AckFormField::By,
    );
    render_modal_buttons(f, rows[9], &app.ack_modal);
    render_modal_footer(f, rows[10], app.ack_modal.error_message.as_deref());
}

#[cfg(feature = "daemon")]
fn draw_unack_form(f: &mut Frame, app: &App, area: Rect, signature: &str) {
    let constraints = [
        Constraint::Length(1), // signature
        Constraint::Length(1), // blank
        Constraint::Length(1), // confirm message
        Constraint::Length(1), // blank
        Constraint::Length(1), // buttons
        Constraint::Min(1),    // error
    ];
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(area);
    render_finding_signature_line(f, rows[0], signature);
    f.render_widget(
        Paragraph::new("Revoke this acknowledgment? Press Enter to confirm, Esc to cancel.")
            .style(Style::default().fg(Color::Yellow)),
        rows[2],
    );
    render_modal_buttons(f, rows[4], &app.ack_modal);
    render_modal_footer(f, rows[5], app.ack_modal.error_message.as_deref());
}

#[cfg(feature = "daemon")]
fn render_finding_signature_line(f: &mut Frame, area: Rect, signature: &str) {
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled("Finding: ", Style::default().fg(Color::DarkGray)),
            Span::raw(sanitize_for_terminal(signature)),
        ])),
        area,
    );
}

#[cfg(feature = "daemon")]
fn render_field_label(
    f: &mut Frame,
    area: Rect,
    label: &str,
    focus: AckFormField,
    field: AckFormField,
) {
    let style = if focus == field {
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    f.render_widget(Paragraph::new(label).style(style), area);
}

#[cfg(feature = "daemon")]
fn render_field_input(f: &mut Frame, area: Rect, value: &str, focused: bool) {
    // Borrow when possible: the focused branch needs to append a
    // cursor char so it allocates, the empty placeholder is `'static`
    // and the unfocused branch just borrows `value`.
    let display: std::borrow::Cow<'_, str> = if value.is_empty() && !focused {
        std::borrow::Cow::Borrowed("(empty)")
    } else if focused {
        std::borrow::Cow::Owned(format!("{value}_"))
    } else {
        std::borrow::Cow::Borrowed(value)
    };
    let style = if focused {
        Style::default().fg(Color::White).bg(Color::DarkGray)
    } else {
        Style::default().fg(Color::White)
    };
    f.render_widget(Paragraph::new(display).style(style), area);
}

#[cfg(feature = "daemon")]
fn render_modal_buttons(f: &mut Frame, area: Rect, modal: &AckModalState) {
    let submit_label = if modal.submitting {
        "[Submitting...]"
    } else {
        "[Submit]"
    };
    let line = Line::from(vec![
        Span::styled(
            submit_label,
            button_style(Color::Green, modal.focus == AckFormField::Submit),
        ),
        Span::raw("   "),
        Span::styled(
            "[Cancel]",
            button_style(Color::Red, modal.focus == AckFormField::Cancel),
        ),
        Span::raw("   "),
        Span::styled(
            "Tab/Shift-Tab to switch, Esc to cancel",
            Style::default().fg(Color::DarkGray),
        ),
    ]);
    f.render_widget(Paragraph::new(line), area);
}

/// Style a modal action button. Focused buttons reverse the color
/// (black foreground on the action color background) and bold; the
/// unfocused state uses the action color as foreground only.
#[cfg(feature = "daemon")]
fn button_style(action_color: Color, focused: bool) -> Style {
    if focused {
        Style::default()
            .fg(Color::Black)
            .bg(action_color)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(action_color)
    }
}

#[cfg(feature = "daemon")]
fn render_modal_footer(f: &mut Frame, area: Rect, error: Option<&str>) {
    if let Some(msg) = error {
        f.render_widget(
            Paragraph::new(sanitize_for_terminal(msg))
                .style(Style::default().fg(Color::Red))
                .wrap(Wrap { trim: true }),
            area,
        );
    }
}

#[cfg(feature = "daemon")]
fn centered_rect(width: u16, height: u16, area: Rect) -> Rect {
    let x = area.x + area.width.saturating_sub(width) / 2;
    let y = area.y + area.height.saturating_sub(height) / 2;
    Rect {
        x,
        y,
        width: width.min(area.width),
        height: height.min(area.height),
    }
}

fn severity_color(severity: &Severity) -> Color {
    match severity {
        Severity::Critical => Color::Red,
        Severity::Warning => Color::Yellow,
        Severity::Info => Color::Cyan,
    }
}

fn severity_label(severity: &Severity) -> &'static str {
    match severity {
        Severity::Critical => "CRITICAL",
        Severity::Warning => "WARNING",
        Severity::Info => "INFO",
    }
}

fn finding_type_label(ft: &FindingType) -> &'static str {
    ft.display_label()
}

/// Validate the modal state and spawn the async ack/revoke roundtrip on
/// the tokio runtime. Returns immediately so the run loop keeps redrawing
/// while the request is in flight. The result lands later through
/// `tx_outcome`, which `apply_ack_outcome` consumes the next time the
/// loop tick drains.
#[cfg(feature = "daemon")]
fn submit_ack_modal(app: &mut App, tx_outcome: &mpsc::UnboundedSender<AckOutcome>) {
    // Gate concurrent submits: a held Enter (autorepeat) or a double tap
    // would otherwise spawn two roundtrips and the second hits HTTP 409.
    if app.ack_modal.submitting {
        return;
    }
    if !app.ack_modal.is_visible() {
        tracing::error!(target: "tui::ack", "submit called on hidden modal, dropped");
        return;
    }
    let payload = match AckSubmitPayload::from_modal(app) {
        Ok(p) => p,
        Err(e) => {
            app.ack_modal.error_message = Some(e.to_string());
            return;
        }
    };
    app.ack_modal.submitting = true;
    let tx = tx_outcome.clone();
    tokio::runtime::Handle::current().spawn(execute_ack_submit(payload, tx));
}

/// Execute the POST/DELETE roundtrip and the post-success refetch, then
/// push a single `AckOutcome` through the channel. Refetch failure on a
/// successful write keeps the previous `acks_by_signature` snapshot, the
/// indicator may briefly look stale but the write itself succeeded.
#[cfg(feature = "daemon")]
async fn execute_ack_submit(payload: AckSubmitPayload, tx: mpsc::UnboundedSender<AckOutcome>) {
    let write_result = match &payload.op {
        AckSubmitOp::Create {
            by,
            reason,
            expires_at,
        } => {
            crate::ack::post_ack_via_daemon(
                &payload.daemon_url,
                &payload.signature,
                by,
                reason,
                *expires_at,
                payload.api_key.as_deref(),
            )
            .await
        }
        AckSubmitOp::Revoke => {
            crate::ack::delete_ack_via_daemon(
                &payload.daemon_url,
                &payload.signature,
                payload.api_key.as_deref(),
            )
            .await
        }
    };
    let outcome = match write_result {
        Ok(()) => {
            match refetch_acks_from_daemon(&payload.daemon_url, payload.api_key.as_deref()).await {
                Ok(refreshed_acks) => AckOutcome::Success {
                    refreshed_acks: Some(refreshed_acks),
                },
                Err(e) => {
                    tracing::warn!(
                        error = %sanitize_for_terminal(&e),
                        "ack submit succeeded but refetch failed, indicator may be stale"
                    );
                    AckOutcome::Success {
                        refreshed_acks: None,
                    }
                }
            }
        }
        Err(crate::ack::AckSubmitError::Unauthorized) => AckOutcome::Failure {
            message: "API key required: set PERF_SENTINEL_DAEMON_API_KEY or pass \
                 --api-key-file when launching `query inspect`."
                .to_string(),
        },
        Err(e) => AckOutcome::Failure {
            message: e.to_string(),
        },
    };
    if let Err(e) = tx.send(outcome) {
        // Receiver dropped because the run loop has already exited
        // (operator pressed `q` mid-flight). Trace it so a future
        // regression on shutdown ordering is observable.
        tracing::trace!(error = %e, "ack outcome dropped, run loop has exited");
    }
}

/// Apply an `AckOutcome` to the app state. Idempotent against an
/// already-closed modal (Esc-while-submitting): Success still refreshes
/// the global ack map when present so the Findings indicator updates,
/// Failure logs at WARN before being dropped so a misconfigured
/// `[daemon.ack] api_key` does not stay hidden in the operator's logs.
#[cfg(feature = "daemon")]
fn apply_ack_outcome(app: &mut App, outcome: AckOutcome) {
    match outcome {
        AckOutcome::Success { refreshed_acks } => {
            // None signals refetch failed, keep the previous snapshot.
            // Some(map), even empty, replaces it (legitimate "no acks").
            if let Some(refreshed) = refreshed_acks {
                app.acks_by_signature = refreshed;
            }
            if app.ack_modal.is_visible() {
                app.ack_modal.close();
            }
        }
        AckOutcome::Failure { message } => {
            if app.ack_modal.is_visible() {
                app.ack_modal.error_message = Some(message);
                app.ack_modal.submitting = false;
            } else {
                tracing::warn!(
                    target: "tui::ack",
                    error = %sanitize_for_terminal(&message),
                    "ack outcome dropped after modal cancelled, may mask 401/403"
                );
            }
        }
    }
}

#[cfg(feature = "daemon")]
fn signature_for_modal_mode(mode: &AckModalMode) -> Option<&str> {
    match mode {
        AckModalMode::Ack { signature } | AckModalMode::Unack { signature } => {
            Some(signature.as_str())
        }
        AckModalMode::Hidden => None,
    }
}

/// Fetch `/api/findings?include_acked=true&limit={FINDINGS_FETCH_LIMIT}`
/// and rebuild the `acks_by_signature` map. Called after every
/// successful submit so the Findings panel indicator and modal
/// gating stay in sync.
#[cfg(feature = "daemon")]
async fn refetch_acks_from_daemon(
    daemon_url: &str,
    api_key: Option<&str>,
) -> Result<HashMap<String, AckSource>, String> {
    let client = sentinel_core::http_client::build_client_with_body();
    let limit = crate::ack::FINDINGS_FETCH_LIMIT;
    let url = format!("{daemon_url}/api/findings?include_acked=true&limit={limit}");
    let (status, body) = crate::ack::http_call(
        &client,
        hyper::Method::GET,
        &url,
        api_key,
        bytes::Bytes::new(),
    )
    .await
    .map_err(|e| e.to_string())?;
    if status.as_u16() != 200 {
        return Err(format!("HTTP {} on findings refetch", status.as_u16()));
    }
    let responses: Vec<sentinel_core::daemon::query_api::FindingResponse> =
        serde_json::from_slice(&body).map_err(|e| e.to_string())?;
    Ok(responses
        .into_iter()
        .filter_map(|r| {
            r.acknowledged_by
                .map(|src| (r.stored.finding.signature, src))
        })
        .collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::assert_matches;
    use sentinel_core::detect::{Confidence, GreenImpact, Pattern};

    fn make_test_app() -> App {
        let findings = vec![
            Finding {
                finding_type: FindingType::NPlusOneSql,
                severity: Severity::Critical,
                trace_id: "trace-1".to_string(),
                service: "order-svc".to_string(),
                source_endpoint: "POST /api/orders/42/submit".to_string(),
                pattern: Pattern {
                    template: "SELECT * FROM order_item WHERE order_id = ?".to_string(),
                    occurrences: 6,
                    window_ms: 200,
                    distinct_params: 6,
                    ..Default::default()
                },
                suggestion: "Use WHERE ... IN (?)".to_string(),
                first_timestamp: "2025-07-10T14:32:01.000Z".to_string(),
                last_timestamp: "2025-07-10T14:32:01.250Z".to_string(),
                green_impact: Some(GreenImpact {
                    estimated_extra_io_ops: 5,
                    io_intensity_score: 6.0,
                    io_intensity_band: InterpretationLevel::for_iis(6.0),
                }),
                confidence: Confidence::default(),
                classification_method: None,
                code_location: None,
                instrumentation_scopes: Vec::new(),
                suggested_fix: None,
                signature: String::new(),
            },
            Finding {
                finding_type: FindingType::RedundantSql,
                severity: Severity::Warning,
                trace_id: "trace-2".to_string(),
                service: "user-svc".to_string(),
                source_endpoint: "GET /api/users/123".to_string(),
                pattern: Pattern {
                    template: "SELECT * FROM config WHERE key = ?".to_string(),
                    occurrences: 3,
                    window_ms: 100,
                    distinct_params: 1,
                    ..Default::default()
                },
                suggestion: "Cache result".to_string(),
                first_timestamp: "2025-07-10T14:32:02.000Z".to_string(),
                last_timestamp: "2025-07-10T14:32:02.100Z".to_string(),
                green_impact: None,
                confidence: Confidence::default(),
                classification_method: None,
                code_location: None,
                instrumentation_scopes: Vec::new(),
                suggested_fix: None,
                signature: String::new(),
            },
        ];

        let detect_config = DetectConfig {
            n_plus_one_threshold: 5,
            window_ms: 500,
            slow_threshold_ms: 500,
            slow_min_occurrences: 3,
            max_fanout: 20,
            chatty_service_min_calls: 15,
            pool_saturation_concurrent_threshold: 10,
            serialized_min_sequential: 3,
            sanitizer_aware_classification:
                sentinel_core::detect::sanitizer_aware::SanitizerAwareMode::default(),
        };

        let traces = vec![
            Trace {
                trace_id: "trace-1".to_string(),
                spans: vec![],
            },
            Trace {
                trace_id: "trace-2".to_string(),
                spans: vec![],
            },
        ];

        App::new(findings, traces, detect_config)
    }

    #[test]
    fn app_initial_state() {
        let app = make_test_app();
        assert_eq!(app.trace_count(), 2);
        assert_eq!(app.selected_trace, 0);
        assert_eq!(app.selected_finding, 0);
        assert_eq!(app.active_panel, Panel::Traces);
    }

    #[test]
    fn move_down_traces() {
        let mut app = make_test_app();
        app.move_down();
        assert_eq!(app.selected_trace, 1);
        // Past the end should not go further
        app.move_down();
        assert_eq!(app.selected_trace, 1);
    }

    #[test]
    fn move_up_traces() {
        let mut app = make_test_app();
        // At 0, should stay at 0
        app.move_up();
        assert_eq!(app.selected_trace, 0);
        app.move_down();
        app.move_up();
        assert_eq!(app.selected_trace, 0);
    }

    #[test]
    fn next_panel_cycles() {
        let mut app = make_test_app();
        assert_eq!(app.active_panel, Panel::Traces);
        app.next_panel();
        assert_eq!(app.active_panel, Panel::Findings);
        app.next_panel();
        assert_eq!(app.active_panel, Panel::Detail);
        app.next_panel();
        assert_eq!(app.active_panel, Panel::Correlations);
        app.next_panel();
        assert_eq!(app.active_panel, Panel::Traces);
    }

    #[test]
    fn prev_panel_cycles() {
        let mut app = make_test_app();
        app.prev_panel();
        assert_eq!(app.active_panel, Panel::Correlations);
        app.prev_panel();
        assert_eq!(app.active_panel, Panel::Detail);
        app.prev_panel();
        assert_eq!(app.active_panel, Panel::Findings);
    }

    #[test]
    fn enter_drills_into_findings() {
        let mut app = make_test_app();
        app.enter();
        assert_eq!(app.active_panel, Panel::Findings);
        app.enter();
        assert_eq!(app.active_panel, Panel::Detail);
    }

    #[test]
    fn escape_goes_back() {
        let mut app = make_test_app();
        app.active_panel = Panel::Detail;
        app.escape();
        assert_eq!(app.active_panel, Panel::Findings);
        app.escape();
        assert_eq!(app.active_panel, Panel::Traces);
        // At Traces (top of the inspect drill-down), escape ascends to the
        // Analyze view; the active panel stays Traces so descending lands
        // back here.
        assert_eq!(app.view, View::Inspect);
        app.escape();
        assert_eq!(app.active_panel, Panel::Traces);
        assert_eq!(app.view, View::Analyze);
    }

    #[test]
    fn escape_from_correlations_ascends_to_analyze() {
        // Correlations is a top-level panel (Tab-reachable); Esc must ascend
        // to Analyze like Traces, honoring the tab-bar "Esc up" hint rather
        // than being a dead end.
        let mut app = make_test_app();
        app.active_panel = Panel::Correlations;
        app.escape();
        assert_eq!(app.view, View::Analyze);
        assert_eq!(app.active_panel, Panel::Correlations);
    }

    #[test]
    fn analyze_enter_descends_to_inspect_traces() {
        let mut app = make_test_app();
        app.view = View::Analyze;
        let out = dispatch_analyze_key(&mut app, KeyCode::Enter);
        assert_matches!(out, KeyOutcome::Continue);
        assert_eq!(app.view, View::Inspect);
        assert_eq!(app.active_panel, Panel::Traces);
    }

    #[test]
    fn detail_enter_zooms_to_explain() {
        let mut app = make_test_app();
        app.active_panel = Panel::Detail;
        app.enter();
        assert_eq!(app.view, View::Explain);
    }

    #[test]
    fn explain_escape_returns_to_inspect_detail() {
        let mut app = make_test_app();
        app.view = View::Explain;
        let out = dispatch_explain_key(&mut app, KeyCode::Esc);
        assert_matches!(out, KeyOutcome::Continue);
        assert_eq!(app.view, View::Inspect);
        assert_eq!(app.active_panel, Panel::Detail);
    }

    #[test]
    fn full_drilldown_round_trip() {
        // Analyze -> Inspect/Traces -> Findings -> Detail -> Explain, then
        // all the way back up the same path.
        let mut app = make_test_app();
        app.view = View::Analyze;

        dispatch_analyze_key(&mut app, KeyCode::Enter);
        assert_eq!((app.view, app.active_panel), (View::Inspect, Panel::Traces));
        app.enter(); // trace-1 has a finding -> Findings
        assert_eq!(app.active_panel, Panel::Findings);
        app.enter();
        assert_eq!(app.active_panel, Panel::Detail);
        app.enter();
        assert_eq!(app.view, View::Explain);

        dispatch_explain_key(&mut app, KeyCode::Esc);
        assert_eq!((app.view, app.active_panel), (View::Inspect, Panel::Detail));
        app.escape(); // Detail -> origin (Findings)
        assert_eq!(app.active_panel, Panel::Findings);
        app.escape(); // Findings -> Traces
        assert_eq!(app.active_panel, Panel::Traces);
        app.escape(); // Traces -> Analyze
        assert_eq!(app.view, View::Analyze);
    }

    #[test]
    fn hjkl_parity_with_arrows_for_panels() {
        let mut app = make_test_app();
        assert_eq!(app.active_panel, Panel::Traces);
        dispatch_panel_key(&mut app, KeyCode::Char('l'));
        assert_eq!(app.active_panel, Panel::Findings);
        dispatch_panel_key(&mut app, KeyCode::Char('h'));
        assert_eq!(app.active_panel, Panel::Traces);
        // Arrows behave identically.
        dispatch_panel_key(&mut app, KeyCode::Right);
        assert_eq!(app.active_panel, Panel::Findings);
        dispatch_panel_key(&mut app, KeyCode::Left);
        assert_eq!(app.active_panel, Panel::Traces);
    }

    #[test]
    fn initial_view_and_focus_trace() {
        let app = make_test_app()
            .with_initial_view(View::Explain)
            .with_focus_trace("trace-2");
        assert_eq!(app.view, View::Explain);
        assert_eq!(app.trace_ids[app.selected_trace], "trace-2");
    }

    fn line_text(lines: &[Line]) -> String {
        lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn analyze_view_without_summary_shows_hint() {
        let app = make_test_app();
        let text = line_text(&app.build_analyze_lines());
        assert!(text.contains("unavailable"), "got: {text}");
    }

    #[test]
    fn analyze_view_renders_gate_and_offenders() {
        let green_summary: GreenSummary = serde_json::from_str(
            r#"{"total_io_ops":100,"avoidable_io_ops":42,"io_waste_ratio":0.42,"io_waste_ratio_band":"high","top_offenders":[{"endpoint":"GET /api/x","service":"svc-a","io_intensity_score":7.5,"io_intensity_band":"high"}]}"#,
        )
        .unwrap();
        let quality_gate: QualityGate = serde_json::from_str(
            r#"{"passed":false,"rules":[{"rule":"io_waste_ratio_max","threshold":0.3,"actual":0.42,"passed":false}]}"#,
        )
        .unwrap();
        let analysis: Analysis =
            serde_json::from_str(r#"{"duration_ms":12,"events_processed":50,"traces_analyzed":2}"#)
                .unwrap();
        let app = make_test_app().with_summary(AnalyzeSummary {
            green_summary,
            quality_gate,
            analysis,
        });
        let text = line_text(&app.build_analyze_lines());
        assert!(text.contains("Quality gate"), "got: {text}");
        assert!(text.contains("FAILED"), "got: {text}");
        assert!(text.contains("Top offenders"), "got: {text}");
        assert!(text.contains("GET /api/x"), "got: {text}");
        // Waste ratio is shown as a percentage, matching the CLI report.
        assert!(text.contains("42.0%"), "got: {text}");
        assert!(
            !text.contains("0.42 "),
            "must not show the bare fraction: {text}"
        );
        // Heuristic-band disclaimer is always present.
        assert!(text.contains("fixed heuristic thresholds"), "got: {text}");
    }

    #[test]
    fn analyze_view_renders_carbon_block_and_uncertainty_note() {
        let green_summary: GreenSummary = serde_json::from_str(
            r#"{"total_io_ops":100,"avoidable_io_ops":42,"io_waste_ratio":0.42,"io_waste_ratio_band":"high","top_offenders":[],"co2":{"total":{"low":0.5,"mid":1.0,"high":2.0,"model":"io_proxy_v3","methodology":"sci_v1"},"avoidable":{"low":0.2,"mid":0.4,"high":0.8,"model":"io_proxy_v3","methodology":"sci_v1"},"operational_gco2":0.9,"embodied_gco2":0.1}}"#,
        )
        .unwrap();
        let quality_gate: QualityGate =
            serde_json::from_str(r#"{"passed":true,"rules":[]}"#).unwrap();
        let analysis: Analysis =
            serde_json::from_str(r#"{"duration_ms":1,"events_processed":1,"traces_analyzed":1}"#)
                .unwrap();
        let app = make_test_app().with_summary(AnalyzeSummary {
            green_summary,
            quality_gate,
            analysis,
        });
        let text = line_text(&app.build_analyze_lines());
        assert!(text.contains("Est. CO"), "carbon block missing: {text}");
        assert!(
            text.contains("multiplicative uncertainty"),
            "mandatory uncertainty note missing: {text}"
        );
    }

    #[test]
    fn interpret_band_color_matches_cli_palette() {
        // Must mirror render.rs `interpret_color`: Critical red, High yellow,
        // Moderate uncolored (Reset), Healthy green. Guards against the two
        // surfaces drifting on the band gradient.
        assert_eq!(
            interpret_band_color(InterpretationLevel::Critical),
            Color::Red
        );
        assert_eq!(
            interpret_band_color(InterpretationLevel::High),
            Color::Yellow
        );
        assert_eq!(
            interpret_band_color(InterpretationLevel::Moderate),
            Color::Reset
        );
        assert_eq!(
            interpret_band_color(InterpretationLevel::Healthy),
            Color::Green
        );
    }

    #[test]
    fn analyze_view_gate_not_evaluated_when_rules_empty() {
        // A daemon `/api/export/report` snapshot carries an empty rule set;
        // the view must not paint a misleading green PASSED.
        let green_summary: GreenSummary = serde_json::from_str(
            r#"{"total_io_ops":10,"avoidable_io_ops":5,"io_waste_ratio":0.5,"io_waste_ratio_band":"critical","top_offenders":[]}"#,
        )
        .unwrap();
        let quality_gate: QualityGate =
            serde_json::from_str(r#"{"passed":true,"rules":[]}"#).unwrap();
        let analysis: Analysis =
            serde_json::from_str(r#"{"duration_ms":1,"events_processed":1,"traces_analyzed":1}"#)
                .unwrap();
        let app = make_test_app().with_summary(AnalyzeSummary {
            green_summary,
            quality_gate,
            analysis,
        });
        let text = line_text(&app.build_analyze_lines());
        assert!(text.contains("Quality gate: not evaluated"), "got: {text}");
        assert!(
            !text.contains("PASSED"),
            "must not show a misleading PASSED with no rules: {text}"
        );
    }

    #[test]
    fn analyze_enter_preserves_active_panel_for_round_trip() {
        // Esc from Correlations ascends to Analyze keeping active_panel;
        // Enter must descend back to that same panel, not force Traces.
        let mut app = make_test_app();
        app.active_panel = Panel::Correlations;
        app.view = View::Analyze;
        dispatch_analyze_key(&mut app, KeyCode::Enter);
        assert_eq!(app.view, View::Inspect);
        assert_eq!(app.active_panel, Panel::Correlations);
    }

    #[test]
    fn detail_line_count_counts_code_location_row() {
        use sentinel_core::event::CodeLocation;
        let mut app = make_test_app();
        app.active_panel = Panel::Detail;
        let without = app.detail_panel_line_count();
        // current_finding() resolves to all_findings[0] for the default
        // selection; give it a code location so draw_detail_panel inserts
        // the "Source:" row.
        app.all_findings[0].code_location = Some(CodeLocation {
            function: Some("load_orders".to_string()),
            filepath: Some("svc/orders.rs".to_string()),
            lineno: Some(42),
            namespace: None,
        });
        let with = app.detail_panel_line_count();
        assert_eq!(
            with,
            without + 1,
            "the inserted Source: row must be counted in the scroll clamp"
        );
    }

    #[test]
    fn finding_count_for_traces() {
        let app = make_test_app();
        assert_eq!(app.finding_count(), 1); // trace-1 has 1 finding
    }

    #[test]
    fn select_second_trace_shows_its_findings() {
        let mut app = make_test_app();
        app.move_down(); // select trace-2
        assert_eq!(app.finding_count(), 1); // trace-2 has 1 finding
        assert_eq!(
            app.current_finding().unwrap().finding_type,
            FindingType::RedundantSql
        );
    }

    #[test]
    fn scroll_in_detail_panel() {
        let mut app = make_test_app();
        app.active_panel = Panel::Detail;
        assert_eq!(app.scroll_offset, 0);
        app.move_down();
        assert_eq!(app.scroll_offset, 1);
        app.move_down();
        assert_eq!(app.scroll_offset, 2);
        app.move_up();
        assert_eq!(app.scroll_offset, 1);
    }

    #[test]
    fn scroll_in_detail_panel_clamps_at_content_end() {
        let mut app = make_test_app();
        app.active_panel = Panel::Detail;

        // The test app's finding carries `green_impact` but has no cached
        // span tree, so the detail panel renders 8 logical lines (6 meta
        // rows + type header + blank + extra I/O). The scroll offset must
        // clamp at 7 (line_count - 1) no matter how many Down keys fire.
        let expected_max = app.detail_panel_line_count().saturating_sub(1);
        assert!(expected_max > 0, "test app should have detail content");

        // Hammer Down far beyond the content height.
        for _ in 0..100 {
            app.move_down();
        }

        assert_eq!(
            app.scroll_offset, expected_max,
            "scroll_offset should clamp at `line_count - 1`, got {}",
            app.scroll_offset
        );

        // move_up still works from the clamp ceiling.
        app.move_up();
        assert_eq!(app.scroll_offset, expected_max.saturating_sub(1));
    }

    #[test]
    fn scroll_clamps_with_cached_span_tree() {
        // Exercises the `cached_detail.is_some()` branch of
        // `detail_panel_line_count`: when a span tree is cached for the
        // selected trace, the clamp must include its line count.
        //
        // Without this test, a regression that misroutes the +2 "Span tree:"
        // header offset or the tree line count would only be caught on
        // actual trace data, not in CI.
        let mut app = make_test_app();
        app.active_panel = Panel::Detail;

        // Inject a synthetic cached tree: 5 lines for the current trace.
        // 7 base meta lines + 1 green_impact (the test fixture sets it)
        // + 2 (blank + "Span tree:" header) + 5 (tree lines) = 15 logical
        // rows, so the clamp should plateau at 14.
        app.cached_detail = Some((
            app.selected_trace,
            "line1\nline2\nline3\nline4\nline5".to_string(),
        ));

        let expected_max = app.detail_panel_line_count().saturating_sub(1);
        assert_eq!(
            expected_max, 14,
            "base 7 + green_impact 1 + header 2 + tree 5 - 1 = 14"
        );

        for _ in 0..100 {
            app.move_down();
        }

        assert_eq!(
            app.scroll_offset, expected_max,
            "scroll_offset must include cached tree lines in the clamp"
        );
    }

    #[test]
    fn switching_trace_resets_finding_and_scroll() {
        let mut app = make_test_app();
        app.scroll_offset = 5;
        app.selected_finding = 0;
        // Switch to trace-2
        app.move_down();
        assert_eq!(app.selected_trace, 1);
        assert_eq!(app.selected_finding, 0);
        assert_eq!(app.scroll_offset, 0);
    }

    #[test]
    fn pre_rendered_trees_take_precedence_over_detect_path() {
        // `query inspect` fetches explain trees from the daemon and passes
        // them via `with_pre_rendered_trees`. This path must be preferred
        // over the local `detect + build_tree` path so users see real span
        // trees when the CLI has no raw spans.
        let mut app = make_test_app();
        let mut trees = HashMap::new();
        let trace_id = app.trace_ids[0].clone();
        trees.insert(trace_id, "pre-rendered tree from daemon".to_string());
        app.pre_rendered_trees = trees;

        let text = app.detail_tree_text();
        assert_eq!(text.as_deref(), Some("pre-rendered tree from daemon"));
    }

    #[test]
    fn empty_spans_without_pre_rendered_tree_returns_none() {
        // Without pre-rendered trees, a stub trace with no spans should
        // not produce an empty tree panel. `make_test_app` ships with
        // `spans: vec![]` on every trace, matching the `query inspect` flow.
        let mut app = make_test_app();
        let text = app.detail_tree_text();
        assert!(text.is_none(), "empty spans must not produce a tree");
    }

    #[test]
    fn with_pre_rendered_trees_builder_populates_field() {
        let mut trees = HashMap::new();
        trees.insert("trace-a".to_string(), "tree-a".to_string());
        let app = make_test_app().with_pre_rendered_trees(trees);
        assert_eq!(
            app.pre_rendered_trees.get("trace-a").map(String::as_str),
            Some("tree-a")
        );
    }

    // ── Rendering tests via TestBackend ────────────────────────────
    //
    // ratatui ships a headless `TestBackend` that lets us exercise the
    // `draw` function and its helpers without a real terminal. These
    // tests verify that the three panels render without panicking and
    // include the expected content, covering the render code paths
    // that a coverage tool would otherwise flag as untested.

    fn render_once(app: &mut App, width: u16, height: u16) -> ratatui::buffer::Buffer {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("terminal init");
        // Pre-compute the detail tree text as the real run loop does.
        app.detail_tree_text();
        terminal
            .draw(|f| draw(f, app))
            .expect("draw should not fail");
        terminal.backend().buffer().clone()
    }

    /// Extract all text content from a buffer for substring assertions.
    fn buffer_text(buf: &ratatui::buffer::Buffer) -> String {
        let mut out = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                let cell = &buf[(x, y)];
                out.push_str(cell.symbol());
            }
            out.push('\n');
        }
        out
    }

    #[test]
    fn draw_renders_all_three_panels() {
        let mut app = make_test_app();
        let buf = render_once(&mut app, 120, 40);
        let text = buffer_text(&buf);
        // Three panel titles should be visible.
        assert!(text.contains("Traces"), "trace panel missing");
        assert!(text.contains("Findings"), "findings panel missing");
        assert!(text.contains("Detail"), "detail panel missing");
    }

    #[test]
    fn draw_renders_selected_trace_findings() {
        let mut app = make_test_app();
        // Fixture has trace-1 selected by default.
        let buf = render_once(&mut app, 120, 40);
        let text = buffer_text(&buf);
        // The N+1 finding's type should appear somewhere in the findings panel.
        assert!(
            text.contains("n_plus_one_sql") || text.contains("N+1"),
            "expected N+1 finding to render; got: {text}"
        );
    }

    #[test]
    fn draw_reflects_selected_trace_change() {
        let mut app = make_test_app();
        let before = buffer_text(&render_once(&mut app, 120, 40));
        app.move_down(); // select next trace (still on Traces panel)
        let after = buffer_text(&render_once(&mut app, 120, 40));
        assert_ne!(
            before, after,
            "buffer should differ after switching selected trace"
        );
    }

    #[test]
    fn draw_renders_with_pre_rendered_tree() {
        let mut app = make_test_app();
        let mut trees = HashMap::new();
        let trace_id = app.trace_ids[0].clone();
        trees.insert(trace_id, "pre-rendered tree from daemon".to_string());
        app.pre_rendered_trees = trees;

        let buf = render_once(&mut app, 120, 40);
        let text = buffer_text(&buf);
        assert!(
            text.contains("pre-rendered tree from daemon") || text.contains("Span tree"),
            "pre-rendered tree should surface in the detail panel"
        );
    }

    #[test]
    fn draw_handles_small_terminal_without_panic() {
        // Minimum viable terminal size should not panic even if panels
        // are cramped.
        let mut app = make_test_app();
        let _buf = render_once(&mut app, 40, 10);
    }

    #[test]
    fn draw_focus_changes_active_panel_border_style() {
        // Active panel change updates border color, not text content.
        // Compare the cell style of the first trace panel cell across
        // states to confirm the render path reads `active_panel`.
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let mut app = make_test_app();
        let render = |app: &mut App| {
            let backend = TestBackend::new(120, 40);
            let mut terminal = Terminal::new(backend).unwrap();
            app.detail_tree_text();
            terminal.draw(|f| draw(f, app)).unwrap();
            // Row 0 is the view tab bar; cell (0, 1) is the top-left corner
            // of the Traces panel border below it.
            terminal.backend().buffer()[(0, 1)].style()
        };
        let before = render(&mut app);
        app.next_panel();
        let after = render(&mut app);
        // The border style must differ (color change on focus).
        assert_ne!(
            before, after,
            "border style must differ when active panel changes"
        );
    }

    fn make_correlation(src_svc: &str, tgt_svc: &str) -> CrossTraceCorrelation {
        use sentinel_core::detect::correlate_cross::CorrelationEndpoint;
        CrossTraceCorrelation {
            source: CorrelationEndpoint {
                finding_type: FindingType::NPlusOneSql,
                service: src_svc.to_string(),
                template: "SELECT * FROM t WHERE id = ?".to_string(),
            },
            target: CorrelationEndpoint {
                finding_type: FindingType::SlowHttp,
                service: tgt_svc.to_string(),
                template: "GET /api/x".to_string(),
            },
            co_occurrence_count: 47,
            source_total_occurrences: 50,
            confidence: 0.92,
            median_lag_ms: 214.0,
            first_seen: "2026-04-25T10:00:00.000Z".to_string(),
            last_seen: "2026-04-25T10:30:00.000Z".to_string(),
            sample_trace_id: Some("trace-sample".to_string()),
        }
    }

    fn buffer_contains(buf: &ratatui::buffer::Buffer, needle: &str) -> bool {
        let area = buf.area;
        for y in 0..area.height {
            let mut line = String::new();
            for x in 0..area.width {
                line.push_str(buf[(x, y)].symbol());
            }
            if line.contains(needle) {
                return true;
            }
        }
        false
    }

    /// Flatten a `TestBackend` buffer into a newline-separated string so
    /// `assert!(rendered.contains(...))` can search the whole frame.
    /// Used by the modal/indicator render tests.
    #[cfg(feature = "daemon")]
    fn render_buffer_to_string(buf: &ratatui::buffer::Buffer) -> String {
        let area = buf.area;
        (0..area.height)
            .map(|y| {
                (0..area.width)
                    .map(|x| {
                        buf.cell((x, y))
                            .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
                    })
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn with_correlations_populates_field() {
        let app = make_test_app()
            .with_correlations(vec![make_correlation("a", "b"), make_correlation("c", "d")]);
        assert_eq!(app.correlation_count(), 2);
    }

    #[test]
    fn next_panel_cycles_through_four_panels() {
        let mut app = make_test_app();
        assert_eq!(app.active_panel, Panel::Traces);
        app.next_panel();
        assert_eq!(app.active_panel, Panel::Findings);
        app.next_panel();
        assert_eq!(app.active_panel, Panel::Detail);
        app.next_panel();
        assert_eq!(app.active_panel, Panel::Correlations);
        app.next_panel();
        assert_eq!(app.active_panel, Panel::Traces);
    }

    #[test]
    fn correlations_panel_shows_empty_hint_when_zero() {
        let mut app = make_test_app();
        app.active_panel = Panel::Correlations;
        let buf = render_once(&mut app, 120, 40);
        assert!(
            buffer_contains(&buf, "No correlations available"),
            "missing empty-state hint, dump:\n{buf:?}"
        );
    }

    #[test]
    fn correlations_panel_renders_each_pair() {
        let mut app = make_test_app().with_correlations(vec![
            make_correlation("svc-alpha", "svc-beta"),
            make_correlation("svc-gamma", "svc-delta"),
        ]);
        app.active_panel = Panel::Correlations;
        // Test exercises the full layout: the 25% Correlations column at
        // typical terminal widths (80 to 160) truncates the metrics tail.
        // Use a very wide TestBackend so the entire row fits and every
        // field is asserted. Narrow-width rendering is covered by
        // `correlations_panel_renders_at_typical_width`.
        let buf = render_once(&mut app, 320, 40);
        assert!(
            buffer_contains(&buf, "svc-alpha"),
            "first correlation source missing"
        );
        assert!(
            buffer_contains(&buf, "svc-delta"),
            "second correlation target missing"
        );
        assert!(
            buffer_contains(&buf, "92%"),
            "confidence percentage missing"
        );
    }

    #[test]
    fn detail_panel_shows_hint_when_spans_unavailable() {
        // make_test_app() builds traces with `spans: vec![]`, mirroring
        // a Report-mode input or a query-inspect trace whose explain
        // tree did not come back from the daemon. The Detail panel
        // must surface the two paths that produce a real tree.
        let mut app = make_test_app();
        app.active_panel = Panel::Findings;
        app.enter(); // drill into Detail
        let buf = render_once(&mut app, 160, 40);
        assert!(
            buffer_contains(&buf, "Not available"),
            "Detail panel must surface a span-tree-unavailable hint"
        );
        assert!(
            buffer_contains(&buf, "inspect --input"),
            "hint must mention `inspect --input <events>.json`"
        );
        assert!(
            buffer_contains(&buf, "query inspect"),
            "hint must mention `query inspect`"
        );
    }

    #[test]
    fn correlations_panel_renders_at_typical_width() {
        let mut app = make_test_app().with_correlations(vec![
            make_correlation("svc-alpha", "svc-beta"),
            make_correlation("svc-gamma", "svc-delta"),
        ]);
        app.active_panel = Panel::Correlations;
        let buf = render_once(&mut app, 160, 40);
        assert!(
            buffer_contains(&buf, "svc-alpha"),
            "source service prefix must remain visible at typical width"
        );
        assert!(
            buffer_contains(&buf, "svc-gamma"),
            "second source service prefix must remain visible"
        );
    }

    #[test]
    fn correlations_panel_strips_ansi_from_service_name() {
        use sentinel_core::detect::correlate_cross::CorrelationEndpoint;
        let mut hostile = make_correlation("a", "b");
        hostile.source.service = "evil\x1b[2J\x1b[H wipe".to_string();
        hostile.target = CorrelationEndpoint {
            finding_type: FindingType::SlowHttp,
            service: "click\x1b]8;;https://attacker/\x07tag\x1b]8;;\x07".to_string(),
            template: "GET /x".to_string(),
        };
        let mut app = make_test_app().with_correlations(vec![hostile]);
        app.active_panel = Panel::Correlations;
        let buf = render_once(&mut app, 320, 40);
        let mut full = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                full.push_str(buf[(x, y)].symbol());
            }
        }
        assert!(
            !full.as_bytes().contains(&0x1b),
            "ESC byte from service leaked into terminal buffer"
        );
        assert!(
            !full.as_bytes().contains(&0x07),
            "BEL byte from OSC 8 leaked into terminal buffer"
        );
    }

    #[test]
    fn move_down_in_correlations_panel_advances_selection() {
        let mut app = make_test_app().with_correlations(vec![
            make_correlation("a", "b"),
            make_correlation("c", "d"),
            make_correlation("e", "f"),
        ]);
        app.active_panel = Panel::Correlations;
        assert_eq!(app.selected_correlation, 0);
        app.move_down();
        app.move_down();
        assert_eq!(app.selected_correlation, 2);
        app.move_down();
        assert_eq!(
            app.selected_correlation, 2,
            "selection must clamp at last index"
        );
    }

    // ── Ack modal tests (gated behind the daemon feature) ───────────

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_default_is_hidden() {
        let modal = AckModalState::default();
        assert!(!modal.is_visible());
        assert_eq!(modal.mode, AckModalMode::Hidden);
        assert_eq!(modal.focus, AckFormField::Reason);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_open_ack_focuses_reason_and_clears_buffers() {
        let mut modal = AckModalState {
            reason_buf: "old".to_string(),
            expires_buf: "old".to_string(),
            error_message: Some("stale".to_string()),
            ..AckModalState::default()
        };
        modal.open_ack("sig-123".to_string());
        assert!(modal.is_visible());
        assert_eq!(
            modal.mode,
            AckModalMode::Ack {
                signature: "sig-123".to_string()
            }
        );
        assert_eq!(modal.focus, AckFormField::Reason);
        assert!(modal.reason_buf.is_empty());
        assert!(modal.expires_buf.is_empty());
        assert!(modal.error_message.is_none());
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_open_unack_focuses_submit_directly() {
        let mut modal = AckModalState::default();
        modal.open_unack("sig-456".to_string());
        assert_eq!(
            modal.mode,
            AckModalMode::Unack {
                signature: "sig-456".to_string()
            }
        );
        assert_eq!(modal.focus, AckFormField::Submit);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_close_resets_state() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        modal.error_message = Some("err".to_string());
        modal.submitting = true;
        modal.close();
        assert!(!modal.is_visible());
        assert!(modal.error_message.is_none());
        assert!(!modal.submitting);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_next_field_cycles_5_steps_then_loops() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        assert_eq!(modal.focus, AckFormField::Reason);
        modal.next_field();
        assert_eq!(modal.focus, AckFormField::Expires);
        modal.next_field();
        assert_eq!(modal.focus, AckFormField::By);
        modal.next_field();
        assert_eq!(modal.focus, AckFormField::Submit);
        modal.next_field();
        assert_eq!(modal.focus, AckFormField::Cancel);
        modal.next_field();
        assert_eq!(modal.focus, AckFormField::Reason);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_prev_field_cycles_backwards() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        modal.prev_field();
        assert_eq!(modal.focus, AckFormField::Cancel);
        modal.prev_field();
        assert_eq!(modal.focus, AckFormField::Submit);
        modal.prev_field();
        assert_eq!(modal.focus, AckFormField::By);
        modal.prev_field();
        assert_eq!(modal.focus, AckFormField::Expires);
        modal.prev_field();
        assert_eq!(modal.focus, AckFormField::Reason);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn step_focus_wraps_at_both_ends() {
        let cycle = ACK_FOCUS_CYCLE;
        assert_eq!(
            step_focus(&cycle, AckFormField::Cancel, 1),
            AckFormField::Reason,
            "forward from last wraps to first"
        );
        assert_eq!(
            step_focus(&cycle, AckFormField::Reason, -1),
            AckFormField::Cancel,
            "backward from first wraps to last"
        );
        let unack = UNACK_FOCUS_CYCLE;
        assert_eq!(
            step_focus(&unack, AckFormField::Reason, 1),
            AckFormField::Cancel,
            "unknown current is treated as index 0, +1 lands on Cancel"
        );
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_unack_field_cycle_skips_text_inputs() {
        let mut modal = AckModalState::default();
        modal.open_unack("sig".to_string());
        assert_eq!(modal.focus, AckFormField::Submit);
        modal.next_field();
        assert_eq!(modal.focus, AckFormField::Cancel);
        modal.next_field();
        assert_eq!(modal.focus, AckFormField::Submit);
        modal.prev_field();
        assert_eq!(modal.focus, AckFormField::Cancel);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn handle_modal_key_typing_appends_to_focused_buffer() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        modal.reason_buf.clear();
        let _ = handle_modal_key(&mut modal, KeyCode::Char('h'));
        let _ = handle_modal_key(&mut modal, KeyCode::Char('i'));
        assert_eq!(modal.reason_buf, "hi");

        modal.focus = AckFormField::Expires;
        let _ = handle_modal_key(&mut modal, KeyCode::Char('2'));
        let _ = handle_modal_key(&mut modal, KeyCode::Char('4'));
        let _ = handle_modal_key(&mut modal, KeyCode::Char('h'));
        assert_eq!(modal.expires_buf, "24h");

        modal.focus = AckFormField::By;
        modal.by_buf.clear(); // open_ack pre-filled it from $USER
        let _ = handle_modal_key(&mut modal, KeyCode::Char('a'));
        let _ = handle_modal_key(&mut modal, KeyCode::Char('b'));
        assert_eq!(modal.by_buf, "ab");
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn handle_modal_key_backspace_pops_focused_buffer() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        modal.reason_buf = "hello".to_string();
        let _ = handle_modal_key(&mut modal, KeyCode::Backspace);
        assert_eq!(modal.reason_buf, "hell");
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn handle_modal_key_tab_advances_focus() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        let action = handle_modal_key(&mut modal, KeyCode::Tab);
        assert_eq!(action, ModalAction::None);
        assert_eq!(modal.focus, AckFormField::Expires);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn handle_modal_key_esc_returns_cancel() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        let action = handle_modal_key(&mut modal, KeyCode::Esc);
        assert_eq!(action, ModalAction::Cancel);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn handle_modal_key_enter_on_submit_returns_submit() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        modal.focus = AckFormField::Submit;
        let action = handle_modal_key(&mut modal, KeyCode::Enter);
        assert_eq!(action, ModalAction::Submit);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn handle_modal_key_enter_on_cancel_returns_cancel() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        modal.focus = AckFormField::Cancel;
        let action = handle_modal_key(&mut modal, KeyCode::Enter);
        assert_eq!(action, ModalAction::Cancel);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn handle_modal_key_enter_on_text_field_advances_focus() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        let action = handle_modal_key(&mut modal, KeyCode::Enter);
        assert_eq!(action, ModalAction::None);
        assert_eq!(modal.focus, AckFormField::Expires);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn handle_modal_key_enforces_max_lengths() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        modal.focus = AckFormField::Reason;
        for _ in 0..(REASON_MAX + 5) {
            let _ = handle_modal_key(&mut modal, KeyCode::Char('x'));
        }
        assert_eq!(modal.reason_buf.chars().count(), REASON_MAX);

        modal.focus = AckFormField::Expires;
        for _ in 0..(EXPIRES_MAX + 5) {
            let _ = handle_modal_key(&mut modal, KeyCode::Char('y'));
        }
        assert_eq!(modal.expires_buf.chars().count(), EXPIRES_MAX);

        modal.focus = AckFormField::By;
        modal.by_buf.clear();
        for _ in 0..(BY_MAX + 5) {
            let _ = handle_modal_key(&mut modal, KeyCode::Char('z'));
        }
        assert_eq!(modal.by_buf.chars().count(), BY_MAX);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn app_default_has_no_daemon_handle() {
        let app = make_test_app();
        assert!(app.daemon_url.is_none());
        assert!(app.api_key.is_none());
        assert!(app.acks_by_signature.is_empty());
        assert!(!app.ack_modal.is_visible());
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn app_with_daemon_handle_populates_acks_by_signature() {
        let mut acks = HashMap::new();
        acks.insert(
            "sig-1".to_string(),
            AckSource::Daemon {
                by: "alice".to_string(),
                at: Utc::now(),
                reason: Some("investigating".to_string()),
                expires_at: None,
            },
        );
        let app = make_test_app().with_daemon_handle(
            "http://localhost:14318".to_string(),
            Some("secret".to_string()),
            acks,
        );
        assert_eq!(app.daemon_url.as_deref(), Some("http://localhost:14318"));
        assert_eq!(app.api_key.as_deref(), Some("secret"));
        assert!(app.acks_by_signature.contains_key("sig-1"));
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn findings_panel_renders_acked_indicator_when_signature_in_map() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut app = make_test_app();
        app.all_findings[0].signature = "sig-acked".to_string();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.acks_by_signature.insert(
            "sig-acked".to_string(),
            AckSource::Daemon {
                by: "alice".to_string(),
                at: Utc::now(),
                reason: Some("test".to_string()),
                expires_at: None,
            },
        );
        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| draw(f, &app)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        let rendered = render_buffer_to_string(&buffer);
        assert!(
            rendered.contains("acked by alice"),
            "expected ack indicator in rendered TUI buffer, got:\n{rendered}"
        );
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_renders_centered_overlay() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.ack_modal.open_ack("sig-123".to_string());
        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| draw(f, &app)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        let rendered = render_buffer_to_string(&buffer);
        assert!(
            rendered.contains("Acknowledge finding"),
            "expected modal title, got:\n{rendered}"
        );
        assert!(rendered.contains("Reason"), "expected reason field label");
        assert!(rendered.contains("[Submit]"), "expected submit button");
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_submit_payload_validation_error_uses_validation_variant() {
        // Drive AckSubmitPayload::from_modal with an unparseable expires
        // input. It must return AckSubmitError::Validation (not Transport)
        // so apply_ack_outcome does not clobber the message with a
        // "network error:" prefix when it Displays it.
        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.ack_modal.open_ack("sig".to_string());
        app.ack_modal.expires_buf = "not a date".to_string();
        let err =
            AckSubmitPayload::from_modal(&app).expect_err("invalid expires must surface an error");
        match err {
            crate::ack::AckSubmitError::Validation(msg) => {
                assert!(
                    msg.starts_with("expires:"),
                    "expected `expires:` prefix, got: {msg}"
                );
                assert!(
                    !msg.contains("network error"),
                    "validation must not be wrapped as network error: {msg}"
                );
            }
            other => panic!("expected Validation, got {other:?}"),
        }
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn apply_ack_outcome_success_closes_modal_and_updates_map() {
        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.ack_modal.open_ack("sig".to_string());
        app.ack_modal.submitting = true;
        let mut refreshed = HashMap::new();
        refreshed.insert(
            "sig".to_string(),
            AckSource::Daemon {
                by: "alice".to_string(),
                at: Utc::now(),
                reason: Some("test".to_string()),
                expires_at: None,
            },
        );
        refreshed.insert(
            "sig2".to_string(),
            AckSource::Daemon {
                by: "bob".to_string(),
                at: Utc::now(),
                reason: None,
                expires_at: None,
            },
        );
        apply_ack_outcome(
            &mut app,
            AckOutcome::Success {
                refreshed_acks: Some(refreshed),
            },
        );
        assert!(!app.ack_modal.is_visible(), "modal must close on success");
        assert_eq!(app.acks_by_signature.len(), 2);
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn apply_ack_outcome_success_with_none_keeps_existing_map() {
        // Refetch failed but write succeeded: the previous snapshot must
        // stay intact so the indicator reflects the most recent known
        // truth instead of dropping to empty.
        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.acks_by_signature.insert(
            "sig-prior".to_string(),
            AckSource::Daemon {
                by: "alice".to_string(),
                at: Utc::now(),
                reason: None,
                expires_at: None,
            },
        );
        app.ack_modal.open_ack("sig-prior".to_string());
        app.ack_modal.submitting = true;
        apply_ack_outcome(
            &mut app,
            AckOutcome::Success {
                refreshed_acks: None,
            },
        );
        assert!(!app.ack_modal.is_visible(), "modal must close on success");
        assert_eq!(
            app.acks_by_signature.len(),
            1,
            "previous snapshot preserved"
        );
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn apply_ack_outcome_success_with_some_empty_clears_map() {
        // Legitimate "all acks expired" refetch: an empty Some(map)
        // overrides a prior non-empty snapshot.
        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.acks_by_signature.insert(
            "sig-prior".to_string(),
            AckSource::Daemon {
                by: "alice".to_string(),
                at: Utc::now(),
                reason: None,
                expires_at: None,
            },
        );
        apply_ack_outcome(
            &mut app,
            AckOutcome::Success {
                refreshed_acks: Some(HashMap::new()),
            },
        );
        assert!(app.acks_by_signature.is_empty());
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn apply_ack_outcome_failure_keeps_modal_with_error_message() {
        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.ack_modal.open_ack("sig".to_string());
        app.ack_modal.submitting = true;
        apply_ack_outcome(
            &mut app,
            AckOutcome::Failure {
                message: "HTTP 503 daemon ack store disabled".to_string(),
            },
        );
        assert!(app.ack_modal.is_visible(), "modal stays open on failure");
        assert_eq!(
            app.ack_modal.error_message.as_deref(),
            Some("HTTP 503 daemon ack store disabled"),
        );
        assert!(
            !app.ack_modal.submitting,
            "submitting flag clears on failure"
        );
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn apply_ack_outcome_after_user_cancel_drops_failure_silently() {
        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        // Open then close to simulate Esc-while-submitting.
        app.ack_modal.open_ack("sig".to_string());
        app.ack_modal.close();
        apply_ack_outcome(
            &mut app,
            AckOutcome::Failure {
                message: "transport error".to_string(),
            },
        );
        assert!(!app.ack_modal.is_visible());
        assert!(app.ack_modal.error_message.is_none());
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn submit_ack_modal_is_no_op_when_already_submitting() {
        // Held Enter or double tap: the second submit must not spawn a
        // duplicate roundtrip. The submitting flag stays true and no
        // outcome is sent through the channel.
        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.ack_modal.open_ack("sig".to_string());
        app.ack_modal.submitting = true;
        let (tx, mut rx) = mpsc::unbounded_channel::<AckOutcome>();
        submit_ack_modal(&mut app, &tx);
        assert!(app.ack_modal.submitting, "submitting flag stays true");
        assert!(
            matches!(rx.try_recv(), Err(mpsc::error::TryRecvError::Empty)),
            "no spawn happened, channel must be empty"
        );
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_submit_payload_debug_redacts_api_key() {
        let payload = AckSubmitPayload {
            daemon_url: "http://localhost:14318".to_string(),
            signature: "sig".to_string(),
            api_key: Some("topsecret".to_string()),
            op: AckSubmitOp::Revoke,
        };
        let dbg = format!("{payload:?}");
        assert!(dbg.contains("<redacted>"), "expected redaction marker");
        assert!(
            !dbg.contains("topsecret"),
            "api key must not appear in Debug"
        );
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn opening_ack_modal_with_no_finding_is_silent() {
        // Build an app with no findings: pressing `a` would call
        // `current_finding()` which returns None, the modal stays
        // hidden. Mirror that path here by reading current_finding and
        // confirming we cannot dispatch an open with an empty signature.
        let app = App::new(
            Vec::new(),
            Vec::new(),
            DetectConfig {
                n_plus_one_threshold: 5,
                window_ms: 500,
                slow_threshold_ms: 500,
                slow_min_occurrences: 3,
                max_fanout: 20,
                chatty_service_min_calls: 15,
                pool_saturation_concurrent_threshold: 10,
                serialized_min_sequential: 3,
                sanitizer_aware_classification:
                    sentinel_core::detect::sanitizer_aware::SanitizerAwareMode::default(),
            },
        );
        assert!(app.current_finding().is_none());
        // The dispatch in run_loop is `if let Some(finding) = ...`, so
        // no current_finding means no `open_ack` call.
        assert!(!app.ack_modal.is_visible());
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn modal_input_rejects_control_and_bidi_chars() {
        let mut modal = AckModalState::default();
        modal.open_ack("sig".to_string());
        modal.reason_buf.clear();
        // C0 controls (Tab/Esc/etc are KeyCode variants in real input,
        // but a paste stream could land them via Char). Bidi overrides
        // U+202A..U+202E and isolates U+2066..U+2069.
        for c in ['\u{0007}', '\u{001B}', '\u{202E}', '\u{2068}', '\u{007F}'] {
            let _ = handle_modal_key(&mut modal, KeyCode::Char(c));
        }
        assert!(
            modal.reason_buf.is_empty(),
            "control/bidi chars should not be appended, got: {:?}",
            modal.reason_buf
        );
        // Plain ASCII still works.
        let _ = handle_modal_key(&mut modal, KeyCode::Char('a'));
        assert_eq!(modal.reason_buf, "a");
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn ack_modal_error_message_is_rendered() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut app = make_test_app();
        app.daemon_url = Some("http://localhost:14318".to_string());
        app.ack_modal.open_ack("sig".to_string());
        app.ack_modal.error_message = Some("HTTP 503 daemon ack store disabled".to_string());
        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| draw(f, &app)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        let rendered = render_buffer_to_string(&buffer);
        assert!(
            rendered.contains("daemon ack store disabled"),
            "expected error message in modal footer, got:\n{rendered}"
        );
    }

    #[test]
    fn enter_in_correlations_jumps_to_sample_trace_detail() {
        let mut app = make_test_app().with_correlations(vec![{
            let mut c = make_correlation("a", "b");
            c.sample_trace_id = Some("trace-2".to_string());
            c
        }]);
        app.active_panel = Panel::Correlations;
        app.selected_correlation = 0;

        app.enter();

        assert_eq!(app.active_panel, Panel::Detail);
        assert_eq!(
            app.traces[app.selected_trace].trace_id, "trace-2",
            "selected_trace must point to trace-2"
        );
        assert_eq!(app.selected_finding, 0);
        assert_eq!(app.scroll_offset, 0);
    }

    #[test]
    fn enter_in_correlations_with_no_sample_trace_id_is_silent() {
        let mut app = make_test_app().with_correlations(vec![{
            let mut c = make_correlation("a", "b");
            c.sample_trace_id = None;
            c
        }]);
        app.active_panel = Panel::Correlations;
        let panel_before = app.active_panel;
        let trace_before = app.selected_trace;

        app.enter();

        assert_eq!(
            app.active_panel, panel_before,
            "no jump must happen when sample_trace_id is None"
        );
        assert_eq!(app.selected_trace, trace_before);
    }

    #[test]
    fn enter_in_correlations_with_unknown_trace_id_is_silent() {
        let mut app = make_test_app().with_correlations(vec![{
            let mut c = make_correlation("a", "b");
            c.sample_trace_id = Some("trace-from-yesterday".to_string());
            c
        }]);
        app.active_panel = Panel::Correlations;
        let panel_before = app.active_panel;
        let trace_before = app.selected_trace;

        app.enter();

        assert_eq!(
            app.active_panel, panel_before,
            "no jump when sample_trace_id is not in trace_index"
        );
        assert_eq!(app.selected_trace, trace_before);
    }

    #[test]
    fn enter_in_correlations_resets_finding_and_scroll() {
        let mut app = make_test_app().with_correlations(vec![{
            let mut c = make_correlation("a", "b");
            c.sample_trace_id = Some("trace-2".to_string());
            c
        }]);
        app.active_panel = Panel::Correlations;
        app.selected_correlation = 0;
        app.selected_finding = 3;
        app.scroll_offset = 5;
        app.cached_detail = Some((0, "stale tree from trace-1".to_string()));

        app.enter();

        assert_eq!(app.selected_finding, 0, "selected_finding must reset to 0");
        assert_eq!(app.scroll_offset, 0, "scroll_offset must reset to 0");
        assert!(
            app.cached_detail.is_none(),
            "cached_detail must invalidate so the new trace's tree is recomputed"
        );
    }

    #[test]
    fn enter_in_correlations_with_empty_correlations_is_silent() {
        let mut app = make_test_app();
        app.active_panel = Panel::Correlations;

        app.enter();

        assert_eq!(app.active_panel, Panel::Correlations);
    }

    #[test]
    fn enter_in_correlations_with_out_of_bounds_cursor_is_silent() {
        let mut app = make_test_app().with_correlations(vec![{
            let mut c = make_correlation("a", "b");
            c.sample_trace_id = Some("trace-2".to_string());
            c
        }]);
        app.active_panel = Panel::Correlations;
        app.selected_correlation = 99;

        app.enter();

        assert_eq!(app.active_panel, Panel::Correlations);
        assert_eq!(app.selected_trace, 0);
    }

    #[test]
    fn escape_from_correlations_drilled_detail_returns_to_correlations() {
        let mut app = make_test_app().with_correlations(vec![{
            let mut c = make_correlation("a", "b");
            c.sample_trace_id = Some("trace-2".to_string());
            c
        }]);
        app.active_panel = Panel::Correlations;
        app.selected_correlation = 0;
        app.enter();
        assert_eq!(app.active_panel, Panel::Detail);

        app.escape();

        assert_eq!(
            app.active_panel,
            Panel::Correlations,
            "Detail entered from Correlations must escape back to Correlations"
        );
    }

    #[test]
    fn escape_from_findings_drilled_detail_still_returns_to_findings() {
        let mut app = make_test_app();
        app.active_panel = Panel::Findings;
        app.enter();
        assert_eq!(app.active_panel, Panel::Detail);

        app.escape();

        assert_eq!(
            app.active_panel,
            Panel::Findings,
            "Detail entered from Findings must keep escaping back to Findings"
        );
    }

    #[test]
    fn jump_to_same_trace_preserves_cached_detail() {
        let mut app = make_test_app().with_correlations(vec![{
            let mut c = make_correlation("a", "b");
            c.sample_trace_id = Some("trace-1".to_string());
            c
        }]);
        app.active_panel = Panel::Correlations;
        app.selected_correlation = 0;
        app.cached_detail = Some((0, "rendered tree for trace-1".to_string()));

        app.enter();

        assert_eq!(app.active_panel, Panel::Detail);
        assert!(
            app.cached_detail.is_some(),
            "cached_detail must be preserved when jumping to the already-selected trace"
        );
    }
}