alphai-tui 0.14.0

Terminal stock dashboard: live quotes and charts plus AI-scored financial news and SEC Form 4 insider activity from AlphaAI
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
use std::sync::{Arc, RwLock};
use std::time::Instant;

use crossterm::event::{KeyCode, KeyEvent};
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use tokio::sync::Notify;

use crate::alphai::{self, Article, FeedPayload, InsiderTrades, SentimentSummary, TRENDING_KEY};
use crate::app::{
    App, AppInit, ChartStyle, FeedBundle, NewsLayout, NewsScope, PRICE_FLASH, SettingsRow,
    settings_rows,
};
use crate::config::{ChartDefaults, Config, UiDefaults};
use crate::domain::{Candle, Interval, Quote, Range, TickerData};
use crate::poller::SourceEvent;
use crate::source::make_source;
use crate::theme::Theme;
use crate::ui;

fn empty_app(symbols: Vec<String>) -> App {
    let (app, _rx) = empty_app_with_cmds(symbols);
    app
}

/// Like `empty_app`, but keeps the AlphaAI command receiver alive so tests
/// can assert which fetches the app requested.
fn empty_app_with_cmds(
    symbols: Vec<String>,
) -> (App, tokio::sync::mpsc::UnboundedReceiver<alphai::Cmd>) {
    let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
    let (alphai_tx, alphai_rx) = tokio::sync::mpsc::unbounded_channel();
    let source = make_source("yahoo", &Config::default()).unwrap();
    let app = App::new(AppInit {
        symbols,
        source: Arc::new(RwLock::new(source)),
        source_name: "yahoo",
        range: Range::D1,
        interval: Interval::M5,
        params: Arc::new(RwLock::new((Range::D1, Interval::M5))),
        every: Arc::new(RwLock::new(std::time::Duration::from_secs(15))),
        rx,
        refresh: Arc::new(Notify::new()),
        alphai_tx,
        config: Config::default(),
        config_path: None,
        theme: Theme::default(),
        theme_name: crate::theme::DEFAULT_PRESET,
        chart: ChartDefaults::default(),
        ui: UiDefaults::default(),
        keymap: crate::keymap::Keymap::default(),
        alphai_enabled: true,
        first_run: false,
    });
    (app, alphai_rx)
}

fn press(app: &mut App, code: KeyCode) {
    app.handle_key(KeyEvent::from(code));
}

/// A cell only candlesticks produce: the upper half block is not part of the
/// table sparkline glyph ramp, and the line chart is pure Braille.
fn has_candles(screen: &str) -> bool {
    screen.contains('▀') || screen.contains('▄') || screen.contains('█')
}

fn fake_app() -> App {
    let mut app = empty_app(vec!["AAPL".into(), "MSFT".into()]);
    for (symbol, base) in [("AAPL", 200.0), ("MSFT", 400.0)] {
        let candles: Vec<Candle> = (0..30)
            .map(|i| {
                let close = base + i as f64 * 0.5;
                Candle {
                    ts: 1_700_000_000 + i * 300,
                    open: close - 0.2,
                    high: close + 0.3,
                    low: close - 0.4,
                    close,
                    // Uneven on purpose: equal volumes render as one solid
                    // block and would hide bar-height bugs.
                    volume: Some(1000.0 + (i % 5) as f64 * 400.0),
                }
            })
            .collect();
        let price = candles.last().unwrap().close;
        app.data.insert(
            symbol.into(),
            TickerData {
                quote: Quote {
                    symbol: symbol.into(),
                    price,
                    prev_close: Some(base),
                    currency: Some("USD".into()),
                },
                candles,
            },
        );
    }
    app
}

fn article(title: &str, ticker: &str, score: i64, sentiment: &str) -> Article {
    serde_json::from_str(&format!(
        r#"{{
          "original": {{
            "title": "{title}",
            "url": "https://example.com/a",
            "time_published": "2026-07-10T12:00:00Z",
            "summary": "Summary of {title}.",
            "source_domain": "example.com"
          }},
          "enrichment": {{
            "category": "earnings",
            "tickers": ["{ticker}"],
            "relevance_score": {score},
            "ai_trading_insights": {{
              "ticker_analysis": [
                {{"ticker": "{ticker}", "impact_analysis": {{
                  "sentiment": "{sentiment}",
                  "confidence": "high",
                  "price_impact_prediction": "+2-4% near term",
                  "summary": "Impact summary for {title}."
                }}}}
              ],
              "news_trading_value": {{
                "actionability_score": "high",
                "information_novelty": 7,
                "timing_relevance": "pre-market"
              }},
              "alternative_perspectives": {{
                "contrarian_view": "Priced in already.",
                "overlooked_factors": "Margins are thinning."
              }}
            }},
            "news_context_enhancement": {{
              "background_context": "Follows last quarter's beat.",
              "key_entities": [
                {{"name": "Acme", "type": "company", "description": "widget maker"}}
              ],
              "market_relevance_summary": "Read-through for the sector."
            }}
          }}
        }}"#
    ))
    .unwrap()
}

/// A story-collapsed row as the market and trending feeds return them: two
/// tickers and an outlet count.
fn market_article(title: &str, sources: i64) -> Article {
    let mut a = article(title, "AAPL", 8, "positive");
    a.enrichment.tickers.push("MSFT".into());
    a.sources_count = Some(sources);
    a
}

/// A Form 4 row: templated title, ownership form, no AI enrichment (the
/// sentiment glyph must come from the title fallback).
fn filing(title: &str, form: &str) -> Article {
    serde_json::from_str(&format!(
        r#"{{
          "original": {{
            "title": "{title}",
            "url": "https://example.com/f",
            "time_published": "2026-07-10T12:00:00Z",
            "summary": "Summary of {title}.",
            "source_domain": "sec.gov",
            "ownership_form": "{form}"
          }},
          "enrichment": {{"category": "insider", "tickers": ["AAPL"], "relevance_score": 7}}
        }}"#
    ))
    .unwrap()
}

fn render(app: &mut App) -> String {
    render_sized(app, 100, 30)
}

fn render_sized(app: &mut App, width: u16, height: u16) -> String {
    let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
    terminal.draw(|f| ui::draw(f, app)).unwrap();
    let buffer = terminal.backend().buffer().clone();
    let area = buffer.area;
    let mut out = String::new();
    for y in area.top()..area.bottom() {
        for x in area.left()..area.right() {
            out.push_str(buffer.cell((x, y)).unwrap().symbol());
        }
        out.push('\n');
    }
    out
}

#[test]
fn table_view_shows_quotes() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Table);
    let screen = render(&mut app);
    assert!(screen.contains("Watchlist"), "screen:\n{screen}");
    assert!(screen.contains("AAPL"), "screen:\n{screen}");
    assert!(screen.contains("214.50"), "screen:\n{screen}"); // 200 + 29*0.5
    assert!(screen.contains("+14.50"), "screen:\n{screen}");
    assert!(screen.contains("+7.25%"), "screen:\n{screen}");
    assert!(screen.contains("▶"), "selection marker missing:\n{screen}");
}

#[test]
fn chart_view_shows_selected_symbol() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    app.selected = 1;
    let screen = render(&mut app);
    assert!(screen.contains("MSFT"), "screen:\n{screen}");
    assert!(screen.contains("414.50"), "screen:\n{screen}");
    assert!(has_candles(&screen), "no candle cells rendered:\n{screen}");
}

#[test]
fn chart_toggles_to_line_mode() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    press(&mut app, KeyCode::Char('c'));
    assert_eq!(app.chart_style, ChartStyle::Line);
    let screen = render(&mut app);
    assert!(
        screen.chars().any(|c| ('\u{2800}'..='\u{28FF}').contains(&c)),
        "no Braille line in line mode:\n{screen}"
    );
    press(&mut app, KeyCode::Char('c'));
    assert_eq!(app.chart_style, ChartStyle::Candles);
}

/// The default 20% right margin keeps candles off the right edge and hosts
/// the last-price tag; `right_margin_pct = 0` restores the old flush layout.
#[test]
fn right_margin_frees_columns_and_hosts_the_price_tag() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    app.show_rsi = false;
    // Volume bars share the candles' glyphs; this is about the price plot.
    app.show_volume = false;
    let max_body_x = |screen: &str| {
        screen
            .lines()
            .flat_map(|l| {
                l.chars()
                    .enumerate()
                    .filter(|(_, c)| matches!(c, '█' | '▀' | '▄'))
                    .map(|(i, _)| i)
            })
            .max()
            .unwrap()
    };

    let screen = render(&mut app);
    let with_margin = max_body_x(&screen);
    // The price appears in the title and again as the tag in the margin.
    assert!(screen.matches("214.50").count() >= 2, "price tag missing:\n{screen}");

    app.chart.right_margin_pct = 0;
    let screen = render(&mut app);
    let flush = max_body_x(&screen);
    assert_eq!(screen.matches("214.50").count(), 1, "margin off, tag still drawn:\n{screen}");
    assert!(
        with_margin + 10 <= flush,
        "margin freed no columns: {with_margin} vs {flush}\n{screen}"
    );
}

/// Line mode renders with the margin (marker line into it) and without.
#[test]
fn line_mode_renders_with_and_without_margin() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    press(&mut app, KeyCode::Char('c'));
    let braille = |s: &str| s.chars().any(|c| ('\u{2800}'..='\u{28FF}').contains(&c));
    assert!(braille(&render(&mut app)), "no line with the margin on");
    app.chart.right_margin_pct = 0;
    assert!(braille(&render(&mut app)), "no line with the margin off");
}

#[test]
fn price_flash_tracks_update_direction() {
    let mut app = empty_app(vec!["AAPL".into()]);
    let data = |price: f64| SourceEvent::Data {
        symbol: "AAPL".into(),
        data: TickerData {
            quote: Quote {
                symbol: "AAPL".into(),
                price,
                prev_close: Some(price),
                currency: None,
            },
            candles: vec![],
        },
    };
    app.apply(data(100.0));
    assert_eq!(app.price_flash_dir("AAPL"), None, "first data must not flash");
    app.apply(data(101.0));
    assert_eq!(app.price_flash_dir("AAPL"), Some(true));
    app.apply(data(100.5));
    assert_eq!(app.price_flash_dir("AAPL"), Some(false));
    app.price_flash.clear();
    app.apply(data(100.5));
    assert_eq!(app.price_flash_dir("AAPL"), None, "unchanged price must not flash");
}

/// The live quote is folded into the in-progress last candle on apply, so
/// the candle redraws with every price tick instead of waiting for the
/// source's bar series to catch up.
#[test]
fn live_quote_updates_the_last_candle() {
    let mut app = empty_app(vec!["AAPL".into()]);
    let data = |price: f64| SourceEvent::Data {
        symbol: "AAPL".into(),
        data: TickerData {
            quote: Quote {
                symbol: "AAPL".into(),
                price,
                prev_close: Some(100.0),
                currency: None,
            },
            candles: vec![
                Candle {
                    ts: 0,
                    open: 99.0,
                    high: 100.0,
                    low: 98.0,
                    close: 99.5,
                    volume: None,
                },
                Candle {
                    ts: 300,
                    open: 100.0,
                    high: 101.0,
                    low: 99.5,
                    close: 100.5,
                    volume: None,
                },
            ],
        },
    };
    // Price below the stale bar close: close follows, low extends down.
    app.apply(data(99.0));
    let last = *app.data["AAPL"].candles.last().unwrap();
    assert_eq!(last.close, 99.0);
    assert_eq!(last.low, 99.0);
    assert_eq!(last.high, 101.0);
    // Price above the bar high: close follows, high extends up.
    app.apply(data(101.5));
    let last = *app.data["AAPL"].candles.last().unwrap();
    assert_eq!(last.close, 101.5);
    assert_eq!(last.high, 101.5);
    assert_eq!(last.low, 99.5);
    // Earlier bars stay untouched.
    assert_eq!(app.data["AAPL"].candles[0].close, 99.5);
}

fn reversed_cells(app: &mut App) -> Vec<ratatui::style::Color> {
    use ratatui::style::Modifier;
    let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
    terminal.draw(|f| ui::draw(f, app)).unwrap();
    let buffer = terminal.backend().buffer().clone();
    let mut out = Vec::new();
    for y in 0..30 {
        for x in 0..100 {
            let cell = buffer.cell((x, y)).unwrap();
            if cell.modifier.contains(Modifier::REVERSED) {
                out.push(cell.fg);
            }
        }
    }
    out
}

/// An active pulse inverts the price (title and margin tag) in the tick's
/// color; an expired one reverts on the next frame. Nothing else in the
/// Chart view uses REVERSED, so the cell scan is unambiguous.
#[test]
fn price_flash_inverts_the_price_on_the_chart() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    assert!(reversed_cells(&mut app).is_empty(), "inverted cells without a flash");

    app.price_flash.insert("AAPL".into(), (Instant::now(), true));
    let cells = reversed_cells(&mut app);
    assert!(!cells.is_empty(), "flash did not invert the price");
    assert!(cells.iter().all(|&fg| fg == app.theme.up), "up tick must use the up color");

    app.price_flash.insert("AAPL".into(), (Instant::now() - PRICE_FLASH, true));
    assert!(reversed_cells(&mut app).is_empty(), "expired flash still inverted");
}

/// The candle-mode SMA overlay draws connected braille lines, not the old
/// per-column dots. RSI is off so the price panel is the only braille source.
#[test]
fn candle_sma_overlay_is_a_braille_line() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    app.show_rsi = false;
    let braille = |s: &str| s.chars().any(|c| ('\u{2800}'..='\u{28FF}').contains(&c));
    let screen = render(&mut app);
    assert!(has_candles(&screen), "not in candle mode:\n{screen}");
    assert!(braille(&screen), "no braille SMA overlay:\n{screen}");
    // The header and footer use "·" as a separator; only the plot matters.
    let plot: String = screen.lines().skip(2).take(25).collect();
    assert!(!plot.contains('·'), "old per-column SMA dots still drawn:\n{screen}");
    press(&mut app, KeyCode::Char('m'));
    let screen = render(&mut app);
    assert!(!braille(&screen), "SMA hidden but braille remains:\n{screen}");
}

#[test]
fn sma_toggle_hides_legend() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    let screen = render(&mut app);
    assert!(screen.contains("SMA20"), "screen:\n{screen}");
    // The 30-candle fixture cannot produce an SMA100 line, so its legend
    // label must not appear either.
    assert!(!screen.contains("SMA100"), "screen:\n{screen}");
    press(&mut app, KeyCode::Char('m'));
    let screen = render(&mut app);
    assert!(!screen.contains("SMA20"), "screen:\n{screen}");
}

/// With warm-up history behind the visible window (fetch_range over-fetches
/// for exactly this) the SMA100 legend appears; rendering also exercises the
/// candle renderer and RSI panel with a non-zero visible-window offset.
#[test]
fn sma_slow_appears_with_warmup_history() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    let candles: Vec<Candle> = (0..600)
        .map(|i| {
            let close = 200.0 + (i % 40) as f64 * 0.5;
            Candle {
                ts: 1_700_000_000 + i * 300,
                open: close - 0.2,
                high: close + 0.3,
                low: close - 0.4,
                close,
                volume: Some(1000.0),
            }
        })
        .collect();
    app.data.get_mut("AAPL").unwrap().candles = candles;
    let screen = render(&mut app);
    assert!(screen.contains("SMA100"), "screen:\n{screen}");
    press(&mut app, KeyCode::Char('c'));
    let screen = render(&mut app);
    assert!(screen.contains("SMA100"), "screen:\n{screen}");
}

#[test]
fn rsi_toggle_hides_panel() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    let screen = render(&mut app);
    assert!(screen.contains("RSI(14)"), "screen:\n{screen}");
    press(&mut app, KeyCode::Char('i'));
    let screen = render(&mut app);
    assert!(!screen.contains("RSI(14)"), "screen:\n{screen}");
}

#[test]
fn rsi_panel_hidden_on_short_terminal() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    // Body height 16 is below the RSI threshold: price chart keeps it all.
    let screen = render_sized(&mut app, 100, 18);
    assert!(!screen.contains("RSI(14)"), "screen:\n{screen}");
    assert!(has_candles(&screen), "screen:\n{screen}");
}

/// `e` reweights the same two overlays: same periods, same colors, only the
/// legend and the math change.
#[test]
fn ma_type_key_switches_the_overlays_to_ema() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    let braille = |s: &str| s.chars().any(|c| ('\u{2800}'..='\u{28FF}').contains(&c));
    let screen = render(&mut app);
    assert!(screen.contains("SMA20"), "screen:\n{screen}");
    press(&mut app, KeyCode::Char('e'));
    let screen = render(&mut app);
    assert!(screen.contains("EMA20"), "screen:\n{screen}");
    assert!(!screen.contains("SMA20"), "screen:\n{screen}");
    assert!(braille(&screen), "no overlay line left:\n{screen}");
    // Line mode reads the same switch.
    press(&mut app, KeyCode::Char('c'));
    assert!(render(&mut app).contains("EMA20"), "line mode kept SMA");
    press(&mut app, KeyCode::Char('e'));
    assert!(render(&mut app).contains("SMA20"), "the toggle does not go back");
}

/// The volume panel ships on and rides the `b` toggle.
#[test]
fn volume_toggle_hides_panel() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    let screen = render(&mut app);
    assert!(screen.contains("Vol"), "screen:\n{screen}");
    press(&mut app, KeyCode::Char('b'));
    let screen = render(&mut app);
    assert!(!screen.contains("Vol"), "screen:\n{screen}");
}

/// Space goes to the price chart first: RSI keeps the height at which it has
/// always appeared, and volume waits for a taller terminal.
#[test]
fn volume_panel_yields_to_the_price_chart() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    let screen = render_sized(&mut app, 100, 24);
    assert!(screen.contains("RSI(14)"), "screen:\n{screen}");
    assert!(!screen.contains("Vol"), "screen:\n{screen}");
    assert!(has_candles(&screen), "screen:\n{screen}");
    // With RSI out of the way the same terminal has room for volume.
    press(&mut app, KeyCode::Char('i'));
    let screen = render_sized(&mut app, 100, 24);
    assert!(screen.contains("Vol"), "screen:\n{screen}");
}

/// Finnhub synthesizes candles from ticks and carries no volume; an empty
/// panel would cost the price chart rows for nothing.
#[test]
fn volume_panel_absent_without_data() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    for data in app.data.values_mut() {
        for candle in &mut data.candles {
            candle.volume = None;
        }
    }
    let screen = render(&mut app);
    assert!(!screen.contains("Vol"), "screen:\n{screen}");
    assert!(has_candles(&screen), "screen:\n{screen}");
}

/// Every bar sits under its candle: both panels end in the same column, and
/// the right margin stays clear in both.
#[test]
fn volume_bars_share_the_candle_columns() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    let screen = render_sized(&mut app, 100, 40);
    let lines: Vec<&str> = screen.lines().collect();
    let vol_top = lines.iter().position(|l| l.contains("Vol")).expect("volume panel");
    let rsi_top = lines.iter().position(|l| l.contains("RSI(")).expect("rsi panel");
    let max_body_x = |rows: &[&str]| {
        rows.iter()
            .flat_map(|l| {
                l.chars()
                    .enumerate()
                    .filter(|(_, c)| matches!(c, '█' | '▀' | '▄'))
                    .map(|(i, _)| i)
            })
            .max()
    };
    let candles = max_body_x(&lines[..vol_top]).expect("candles");
    let bars = max_body_x(&lines[vol_top + 1..rsi_top]).expect("bars");
    assert_eq!(candles, bars, "bars and candles end in different columns:\n{screen}");
    // Both stop well short of the right border: that is the price margin.
    assert!(bars < 90, "the margin is not clear: {bars}\n{screen}");
}

/// Every view's footer must fit the 110-column terminal the README promises.
/// The chart hints were at 107 of them before the volume key arrived.
#[test]
fn footer_hints_fit_110_columns() {
    let mut app = fake_app();
    for (i, view) in ui::VIEWS.iter().enumerate() {
        app.view_idx = i;
        let width = crate::ui::hints_text(&app).chars().count();
        assert!(width <= 110, "{:?}: footer is {width} columns wide", view.id());
    }
}

#[test]
fn range_keys_cycle_presets_and_update_header() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    press(&mut app, KeyCode::Char('t'));
    assert_eq!((app.range, app.interval), (Range::D5, Interval::M15));
    let screen = render(&mut app);
    assert!(screen.contains("· 15m"), "screen:\n{screen}");
    // Wrap backwards past the first preset.
    press(&mut app, KeyCode::Char('T'));
    press(&mut app, KeyCode::Char('T'));
    assert_eq!((app.range, app.interval), (Range::Y1, Interval::D1));
    assert!(render(&mut app).contains("· 1d"));
    // Old data stays on screen until the poller answers.
    assert!(app.data.contains_key("AAPL"));
}

/// Budget invariant: a range switch must wake only the price poller. The
/// visible AlphaAI bundle stays cached (manual_refresh would drop it and
/// trigger a refetch on the next draw).
#[test]
fn range_switch_keeps_news_bundle() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    press(&mut app, KeyCode::Char('t'));
    assert!(app.feeds.contains_key("AAPL"), "range switch dropped the news bundle");
}

#[test]
fn split_view_combines_table_chart_and_news() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Split);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    let screen = render(&mut app);
    assert!(screen.contains("Watchlist"), "screen:\n{screen}");
    assert!(
        screen.contains('▀'),
        "no candle chart in split view:\n{screen}"
    );
    assert!(screen.contains("News · AAPL"), "screen:\n{screen}");
    assert!(screen.contains("Apple beats expectations"), "screen:\n{screen}");
}

#[test]
fn split_view_news_panel_without_key_shows_one_line_hint() {
    let mut app = fake_app();
    app.alphai_enabled = false;
    app.view_idx = ui::view_index(ui::ViewId::Split);
    let screen = render(&mut app);
    assert!(screen.contains("alphai.io"), "screen:\n{screen}");
    assert!(screen.contains("press s"), "screen:\n{screen}");
}

#[test]
fn split_view_drops_news_panel_on_tiny_terminal() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Split);
    let mut terminal = Terminal::new(TestBackend::new(100, 12)).unwrap();
    terminal.draw(|f| ui::draw(f, &mut app)).unwrap();
    let buffer = terminal.backend().buffer().clone();
    let mut screen = String::new();
    for y in 0..12 {
        for x in 0..100 {
            screen.push_str(buffer.cell((x, y)).unwrap().symbol());
        }
        screen.push('\n');
    }
    assert!(screen.contains("Watchlist"), "screen:\n{screen}");
    assert!(!screen.contains("News ·"), "news strip should be hidden:\n{screen}");
}

/// Every view registers a distinct ViewId (a duplicate would make
/// `view_index` land on the wrong tab) and carries footer hints.
#[test]
fn view_ids_are_unique_and_indexable() {
    for (i, view) in ui::VIEWS.iter().enumerate() {
        assert_eq!(ui::view_index(view.id()), i, "duplicate ViewId {:?}", view.id());
        assert!(!view.hints().is_empty(), "{:?}: empty footer hints", view.id());
    }
}

/// The footer renders the keys actually bound in the keymap, in the
/// traditional shapes ("↑↓ select", "c/m/i/b/e chart").
#[test]
fn footer_shows_bound_keys() {
    let mut app = fake_app();
    let screen = render(&mut app);
    assert!(screen.contains("q quit"), "screen:\n{screen}");
    assert!(screen.contains("tab/1-9 view"), "screen:\n{screen}");
    assert!(screen.contains("↑↓ select"), "screen:\n{screen}");
    assert!(screen.contains("c/m/i/b/e chart"), "screen:\n{screen}");
    app.view_idx = ui::view_index(ui::ViewId::News);
    let screen = render(&mut app);
    assert!(screen.contains("⏎ open"), "screen:\n{screen}");
    assert!(screen.contains("x layout"), "screen:\n{screen}");
}

/// A `[keybindings]` remap flows through to the footer and to dispatch:
/// the hint shows the new key and pressing it fires the action.
#[test]
fn footer_and_dispatch_follow_a_remap() {
    let mut app = fake_app();
    let mut warnings = Vec::new();
    app.keymap = crate::keymap::Keymap::from_config(
        [("open", vec!["z"]), ("card", vec!["n"])],
        &mut warnings,
    );
    assert!(warnings.is_empty(), "{warnings:?}");
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    let screen = render(&mut app);
    assert!(screen.contains("z open"), "screen:\n{screen}");
    assert!(!screen.contains("⏎ open"), "screen:\n{screen}");
    // The new key drives the action, the old one is gone.
    press(&mut app, KeyCode::Char('v'));
    assert!(!app.article_overlay.open, "the replaced default still fired");
    press(&mut app, KeyCode::Char('n'));
    assert!(app.article_overlay.open, "the remapped key did not fire");
}

/// ? opens the help overlay listing every action with its live keys and
/// its [keybindings] name; esc closes it, q still quits. The coverage walk
/// over ACTIONS keeps the table exhaustive: a new action cannot ship
/// without a help row.
#[test]
fn help_overlay_lists_every_action() {
    let mut app = fake_app();
    press(&mut app, KeyCode::Char('?'));
    assert!(app.help.open);
    let screen = render_sized(&mut app, 90, 45);
    for (_, name) in crate::keymap::ACTIONS.iter() {
        assert!(screen.contains(name), "action {name} missing:\n{screen}");
    }
    assert!(screen.contains("ctrl-c"), "screen:\n{screen}");
    assert!(screen.contains("[keybindings]"), "screen:\n{screen}");
    // Esc closes the overlay without quitting the app.
    assert!(!app.handle_key(KeyEvent::from(KeyCode::Esc)));
    assert!(!app.help.open);
    // A remap shows up in the table: the overlay reads the live keymap.
    app.keymap =
        crate::keymap::Keymap::from_config([("refresh", vec!["f5"])], &mut Vec::new());
    press(&mut app, KeyCode::Char('?'));
    let screen = render_sized(&mut app, 90, 45);
    assert!(screen.contains("f5"), "screen:\n{screen}");
    // q inside the overlay still quits.
    assert!(app.handle_key(KeyEvent::from(KeyCode::Char('q'))));
}

/// Split embeds the news strip, but j/k must keep driving the watchlist
/// selection and must never page the feed (budget guard).
#[test]
fn split_j_moves_watchlist_not_articles() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into(), "MSFT".into()]);
    app.view_idx = ui::view_index(ui::ViewId::Split);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            Some("cur1".into()),
        ),
    );
    press(&mut app, KeyCode::Char('j'));
    assert_eq!(app.selected, 1, "j did not move the watchlist selection");
    assert_eq!(app.news_selected, 0, "j leaked into the article list");
    assert!(cmds.try_recv().is_err(), "split view paged the feed");
}

#[test]
fn missing_data_renders_placeholders() {
    let mut app = empty_app(vec!["AAPL".into()]);
    app.errors.insert("AAPL".into(), "boom".into());
    for view_idx in 0..ui::VIEWS.len() {
        app.view_idx = view_idx;
        let screen = render(&mut app); // must not panic
        assert!(!screen.is_empty(), "view {view_idx} rendered nothing");
    }
}

#[test]
fn news_view_lists_articles_and_sentiment() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![
                article("Apple beats expectations", "AAPL", 9, "positive"),
                article("Supplier note weighs on outlook", "AAPL", 6, "negative"),
            ],
            Some(FeedPayload::Sentiment(SentimentSummary {
                days: 7,
                total: 20,
                bullish: 12,
                neutral: 5,
                bearish: 3,
            })),
            None,
        ),
    );
    let screen = render(&mut app);
    assert!(screen.contains("News · AAPL"), "screen:\n{screen}");
    assert!(screen.contains("Apple beats expectations"), "screen:\n{screen}");
    assert!(screen.contains("12 bullish"), "screen:\n{screen}");
    assert!(screen.contains("▲"), "sentiment glyph missing:\n{screen}");
    // detail pane shows the selected article's summary and the AI meta calls
    assert!(
        screen.contains("Summary of Apple beats expectations"),
        "screen:\n{screen}"
    );
    assert!(screen.contains("nov 7"), "novelty missing from meta:\n{screen}");
    assert!(screen.contains("positive/high"), "sentiment/confidence missing:\n{screen}");
    assert!(screen.contains("act high"), "actionability missing:\n{screen}");
}

#[test]
fn news_view_without_key_shows_hint() {
    let mut app = fake_app();
    app.alphai_enabled = false;
    app.view_idx = ui::view_index(ui::ViewId::News);
    let screen = render(&mut app);
    assert!(screen.contains("alphai.io"), "screen:\n{screen}");
    assert!(screen.contains("free API key"), "screen:\n{screen}");
}

#[test]
fn news_view_shows_error_state() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.alphai_errors
        .insert("AAPL".into(), "invalid AlphaAI API key".into());
    let screen = render(&mut app);
    assert!(screen.contains("invalid AlphaAI API key"), "screen:\n{screen}");
    assert!(screen.contains("press r to retry"), "screen:\n{screen}");
}

#[test]
fn insider_view_shows_summary_and_filings() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Insider);
    let trades: InsiderTrades = serde_json::from_str(
        r#"{
          "ticker": "AAPL",
          "summary": {
            "last_12m": { "buy_count": 2, "sell_count": 12,
                          "buy_value_usd": "1240000.00", "sell_value_usd": "224580213.05",
                          "unique_insiders": 6, "pct_10b5_1": 85 },
            "top_insiders": [{"name": "COOK TIMOTHY", "title": "CEO", "event_count": 3, "net_value_usd": "-50300000.00"}]
          }
        }"#,
    )
    .unwrap();
    app.feeds.insert(
        alphai::insider_key("AAPL"),
        FeedBundle::new(
            vec![filing("Apple insider sold $12.5M of stock", "direct")],
            Some(FeedPayload::Insider(Box::new(trades))),
            None,
        ),
    );
    let screen = render(&mut app);
    assert!(screen.contains("Insider · AAPL"), "screen:\n{screen}");
    assert!(screen.contains("14 events"), "screen:\n{screen}");
    assert!(screen.contains("$224.6M"), "screen:\n{screen}");
    assert!(screen.contains("85% under 10b5-1"), "screen:\n{screen}");
    assert!(screen.contains("6 insiders"), "screen:\n{screen}");
    assert!(screen.contains("COOK TIMOTHY"), "screen:\n{screen}");
    assert!(screen.contains("×3"), "event count missing:\n{screen}");
    // No AI enrichment and no structured block on this legacy filing: the
    // sell glyph comes from the title fallback, the ownership marker follows,
    // and the plan/value columns stay blank.
    assert!(screen.contains("▼  D"), "screen:\n{screen}");
    assert!(screen.contains("Apple insider sold"), "screen:\n{screen}");
    assert!(screen.contains("score 4+"), "size filter missing from the title:\n{screen}");
}

/// A filing with the structured `insider` block: side/value/plan render from
/// it, and the block beats the title wording (a code D "sold to issuer" row
/// must stay neutral even though the title says "sold").
#[test]
fn insider_structured_block_drives_row_and_card() {
    fn with_block(title: &str, side: &str, value: Option<&str>, plan: bool) -> Article {
        let value_json = value.map_or("null".to_string(), |v| format!("\"{v}\""));
        serde_json::from_str(&format!(
            r#"{{
              "original": {{"title": "{title}", "time_published": "2026-07-10T12:00:00Z",
                            "ownership_form": "direct"}},
              "enrichment": {{"category": "insider", "tickers": ["AAPL"], "relevance_score": 7}},
              "insider": {{
                "side": "{side}", "transaction_code": "S",
                "shares": "25000.0000", "avg_price_usd": "187.3200",
                "total_value_usd": {value_json}, "is_10b5_1": {plan},
                "insider_name": "STEVENS MARK A", "insider_title": "Director",
                "is_officer": false, "is_director": true,
                "is_ten_percent_owner": false, "transaction_date": "2026-07-09"
              }}
            }}"#
        ))
        .unwrap()
    }
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Insider);
    app.feeds.insert(
        alphai::insider_key("AAPL"),
        FeedBundle::new(
            vec![
                with_block("X sold $4.7M of stock", "sell", Some("4683000.00"), true),
                // Code D: shares sold BACK TO THE ISSUER; side "other" must
                // not fall back to the "sold" keyword in the title.
                with_block("Y sold $1.0M of stock to the issuer", "other", Some("1000000.00"), false),
            ],
            None,
            None,
        ),
    );
    let screen = render(&mut app);
    assert!(screen.contains("$4.7M"), "value column missing:\n{screen}");
    assert!(screen.contains("▼  D p"), "sell glyph + plan flag missing:\n{screen}");
    assert!(screen.contains("·  D"), "structured \"other\" not neutral:\n{screen}");
    // The detail meta carries the structured trade.
    assert!(screen.contains("SELL $4.7M"), "meta trade missing:\n{screen}");
    assert!(screen.contains("10b5-1 plan"), "meta plan flag missing:\n{screen}");
    // The fullscreen card shows the full structured trade.
    press(&mut app, KeyCode::Char('v'));
    let card = render(&mut app);
    assert!(card.contains("SELL 25,000 sh @ $187.32 = $4.7M (code S)"), "card:\n{card}");
    assert!(card.contains("STEVENS MARK A (Director)"), "card:\n{card}");
    assert!(card.contains("2026-07-09"), "card:\n{card}");
}

/// An Insider bundle with the trades chart payload, its events placed
/// relative to today so the trailing windows always cover them.
fn insider_app_with_chart() -> App {
    use chrono::{Datelike, Days, Utc};

    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Insider);
    let today = Utc::now().date_naive();
    let day = |ago: u64| (today - Days::new(ago)).format("%Y-%m-%d").to_string();
    let monday = |ago: u64| {
        let d = today - Days::new(ago);
        (d - Days::new(u64::from(d.weekday().num_days_from_monday())))
            .format("%Y-%m-%d")
            .to_string()
    };
    let trades: InsiderTrades = serde_json::from_str(&format!(
        r#"{{
          "summary": {{ "last_12m": {{ "buy_count": 1, "sell_count": 2,
                        "buy_value_usd": "500000", "sell_value_usd": "10886021",
                        "unique_insiders": 2, "pct_10b5_1": 33 }} }},
          "series_weekly": [
            {{ "week_start": "{w1}", "buy_count": 0, "sell_count": 1,
               "buy_value_usd": "0", "sell_value_usd": "9886021" }},
            {{ "week_start": "{w2}", "buy_count": 1, "sell_count": 1,
               "buy_value_usd": "500000", "sell_value_usd": "1000000" }}
          ],
          "chart_events": [
            {{ "side": "sell", "transaction_code": "S", "total_value_usd": "9886021.65",
               "tranche_count": 8, "stake_change_pct": "-100.0", "is_10b5_1": true,
               "insider_name": "A", "transaction_date": "{e1}", "news_uid": "uid-1" }},
            {{ "side": "sell", "transaction_code": "D", "total_value_usd": "1000000",
               "insider_name": "B", "transaction_date": "{e2}" }},
            {{ "side": "buy", "transaction_code": "P", "total_value_usd": "500000",
               "insider_name": "C", "transaction_date": "{e2}" }}
          ]
        }}"#,
        w1 = monday(5),
        w2 = monday(12),
        e1 = day(5),
        e2 = day(12),
    ))
    .unwrap();
    let mut sold = filing("Apple insider sold $9.9M of stock", "direct");
    sold.original.uid = "uid-1".into();
    app.feeds.insert(
        alphai::insider_key("AAPL"),
        FeedBundle::new(vec![sold], Some(FeedPayload::Insider(Box::new(trades))), None),
    );
    app
}

/// The chart panel: log scatter of the window's events over the weekly
/// bars, joined to the list by uid, cycled off and back by g.
#[test]
fn insider_chart_panel_draws_and_cycles() {
    let mut app = insider_app_with_chart();
    let screen = render(&mut app);
    assert!(screen.contains("Form 4 · 3m"), "panel title missing:\n{screen}");
    // Window totals in the title: both sides priced.
    assert!(screen.contains("▼ $10.9M"), "sell total missing:\n{screen}");
    assert!(screen.contains("▲ $500.0K"), "buy total missing:\n{screen}");
    assert!(screen.contains("3 events"), "event count missing:\n{screen}");
    // The three mark shapes: filled sell, hollow sale-to-issuer, filled buy.
    assert!(screen.contains("▽"), "sale-to-issuer mark missing:\n{screen}");
    // Log decade labels from $100K up to $10M.
    assert!(screen.contains("$10M"), "decade label missing:\n{screen}");
    assert!(screen.contains("$100K"), "decade label missing:\n{screen}");
    assert!(screen.contains("▲ buy · ▼ sell · ▽ to issuer"), "legend missing:\n{screen}");
    // Weekly bars: two-sided window renders block glyphs under the scatter.
    assert!(has_candles(&screen), "weekly bars missing:\n{screen}");
    // The selected filing's extras join the detail pane by uid.
    assert!(screen.contains("stake -100.0%"), "stake extra missing:\n{screen}");
    assert!(screen.contains("8 tranches"), "tranche extra missing:\n{screen}");

    // g cycles 3m -> 12m -> off -> 3m; the panel yields its rows when off.
    press(&mut app, KeyCode::Char('g'));
    assert!(render(&mut app).contains("Form 4 · 12m"));
    press(&mut app, KeyCode::Char('g'));
    let screen = render(&mut app);
    assert!(!screen.contains("Form 4 ·"), "panel must hide when off:\n{screen}");
    press(&mut app, KeyCode::Char('g'));
    assert!(render(&mut app).contains("Form 4 · 3m"));
}

/// Rows are scarce before they are gone: the weekly bars drop first, the
/// whole panel only when the list would starve.
#[test]
fn insider_chart_degrades_bars_then_panel() {
    let mut app = insider_app_with_chart();
    // 24-row terminal: the panel fits only without its bars.
    let screen = render_sized(&mut app, 100, 24);
    assert!(screen.contains("Form 4 · 3m"), "short panel missing:\n{screen}");
    assert!(!has_candles(&screen), "bars must drop on short terminals:\n{screen}");
    // 20 rows: the panel is gone, the list and detail stay.
    let screen = render_sized(&mut app, 100, 20);
    assert!(!screen.contains("Form 4 ·"), "panel must yield:\n{screen}");
    assert!(screen.contains("Apple insider sold"), "list lost:\n{screen}");
}

/// +/- on the Insider view adjust the insider filter only, and the refetch
/// carries the new min_relevance (the news filter stays untouched).
#[test]
fn insider_score_keys_adjust_own_filter() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::Insider);
    let mut bundle = FeedBundle::new(
        vec![filing("Apple insider sold $12.5M of stock", "direct")],
        None,
        None,
    );
    bundle.min_score = Some(app.insider_min_score);
    app.feeds.insert(alphai::insider_key("AAPL"), bundle);
    app.ensure_alphai_data();
    assert!(cmds.try_recv().is_err(), "matching filter refetched");

    let news_before = app.news_min_score;
    press(&mut app, KeyCode::Char('+'));
    assert_eq!(app.insider_min_score, 5);
    assert_eq!(app.news_min_score, news_before, "+ leaked into the news filter");
    app.ensure_alphai_data();
    match cmds.try_recv() {
        Ok(alphai::Cmd::FetchInsider { symbol, cursor, min_relevance, .. }) => {
            assert_eq!(symbol, "AAPL");
            assert_eq!(cursor, None);
            assert_eq!(min_relevance, Some(5));
        }
        other => panic!("expected a filtered insider fetch, got {:?}", other.is_ok()),
    }
}

#[test]
fn news_scope_cycles_and_relabels() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    assert_eq!(app.news_cache_key(), "AAPL");
    press(&mut app, KeyCode::Char('f'));
    assert_eq!(app.news_scope, NewsScope::Market);
    assert_eq!(app.news_cache_key(), "*");
    assert!(render(&mut app).contains("News · market"));
    press(&mut app, KeyCode::Char('f'));
    assert_eq!(app.news_scope, NewsScope::Trending);
    assert_eq!(app.news_cache_key(), TRENDING_KEY);
    assert!(render(&mut app).contains("News · trending"));
    press(&mut app, KeyCode::Char('f'));
    assert_eq!(app.news_cache_key(), "AAPL");
}

#[test]
fn market_scope_shows_tickers_and_sources_count() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.news_scope = NewsScope::Market;
    app.feeds.insert(
        "*".into(),
        FeedBundle::new(
            vec![market_article("Fed minutes move futures", 7)],
            None,
            None,
        ),
    );
    let screen = render(&mut app);
    assert!(screen.contains("AAPL,MSFT"), "ticker cell missing:\n{screen}");
    assert!(screen.contains("×7"), "outlet count missing:\n{screen}");
    assert!(screen.contains("reprints collapsed"), "head line missing:\n{screen}");
}

#[test]
fn trending_view_lists_articles() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.news_scope = NewsScope::Trending;
    app.feeds.insert(
        TRENDING_KEY.into(),
        FeedBundle::new(
            vec![market_article("Chip stocks rally on export news", 5)],
            None,
            None,
        ),
    );
    let screen = render(&mut app);
    assert!(screen.contains("News · trending"), "screen:\n{screen}");
    assert!(screen.contains("top 10 of the last 48h"), "screen:\n{screen}");
    assert!(screen.contains("Chip stocks rally"), "screen:\n{screen}");
    assert!(screen.contains("×5"), "outlet count missing:\n{screen}");
}

#[test]
fn article_overlay_opens_scrolls_and_closes() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    press(&mut app, KeyCode::Char('v'));
    assert!(app.article_overlay.open);
    let screen = render(&mut app);
    assert!(screen.contains("Article"), "overlay missing:\n{screen}");
    assert!(screen.contains("price: +2-4% near term"), "impact missing:\n{screen}");
    assert!(screen.contains("Trading value"), "screen:\n{screen}");
    assert!(screen.contains("contrarian: Priced in already."), "screen:\n{screen}");
    assert!(screen.contains("entities: Acme (company)"), "screen:\n{screen}");
    press(&mut app, KeyCode::Char('j'));
    assert_eq!(app.article_overlay.scroll, 1);
    render(&mut app); // must not panic; the render pass clamps the scroll
    press(&mut app, KeyCode::Esc);
    assert!(!app.article_overlay.open);
    // The card pane still shows the article; only the modal frame must go.
    assert!(!render(&mut app).contains(" Article "), "overlay did not close");
}

#[test]
fn overlay_steals_nav_keys() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![
                article("First", "AAPL", 9, "positive"),
                article("Second", "AAPL", 8, "positive"),
            ],
            None,
            None,
        ),
    );
    press(&mut app, KeyCode::Char('v'));
    press(&mut app, KeyCode::Char('j'));
    press(&mut app, KeyCode::Char('l'));
    assert_eq!(app.news_selected, 0, "overlay leaked j to the article list");
    assert_eq!(app.selected, 0, "overlay leaked l to the ticker list");
}

#[test]
fn overlay_works_from_insider_view() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Insider);
    app.feeds.insert(
        alphai::insider_key("AAPL"),
        FeedBundle::new(
            vec![filing("Officer bought 10,000 shares", "indirect")],
            None,
            None,
        ),
    );
    press(&mut app, KeyCode::Char('v'));
    assert!(app.article_overlay.open);
    let screen = render(&mut app);
    assert!(screen.contains("Officer bought 10,000 shares"), "screen:\n{screen}");
    assert!(screen.contains("Summary of Officer bought"), "screen:\n{screen}");
}

#[test]
fn overlay_noop_when_no_articles() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    press(&mut app, KeyCode::Char('v'));
    assert!(!app.article_overlay.open, "overlay opened with nothing to show");
}

#[test]
fn news_card_pane_shown_by_default() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    let screen = render(&mut app);
    // The full AI card sits next to the list without opening the overlay.
    assert!(screen.contains(" card ·"), "card pane missing:\n{screen}");
    assert!(screen.contains("Trading value"), "card content missing:\n{screen}");
    assert!(screen.contains("contrarian: Priced in already."), "screen:\n{screen}");
}

#[test]
fn x_cycles_news_layout() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    assert_eq!(app.news_layout, NewsLayout::Side);
    press(&mut app, KeyCode::Char('x'));
    assert_eq!(app.news_layout, NewsLayout::Stacked);
    let screen = render(&mut app);
    assert!(screen.contains(" card ·"), "card pane missing in stacked:\n{screen}");
    press(&mut app, KeyCode::Char('x'));
    assert_eq!(app.news_layout, NewsLayout::Side);
}

/// +/- move the score filter; the cached bundle's recorded filter stops
/// matching, so the next ensure pass refetches page 1 with the new value,
/// without waiting for the top row (a filter change is an explicit ask).
#[test]
fn score_keys_adjust_filter_and_refetch() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    let mut bundle = FeedBundle::new(
        vec![
            article("Apple beats expectations", "AAPL", 9, "positive"),
            article("Supplier note", "AAPL", 8, "negative"),
        ],
        None,
        None,
    );
    bundle.min_score = Some(app.news_min_score);
    app.feeds.insert("AAPL".into(), bundle);
    app.news_selected = 1;
    app.ensure_alphai_data();
    assert!(cmds.try_recv().is_err(), "matching filter refetched");

    // The title advertises the active filter before and after the change.
    assert!(render(&mut app).contains("score 7+"), "filter missing from the title");
    press(&mut app, KeyCode::Char('+'));
    assert_eq!(app.news_min_score, 8);
    assert_eq!(app.news_selected, 0, "selection not reset on a filter change");
    assert!(render(&mut app).contains("score 8+"));

    app.ensure_alphai_data();
    match cmds.try_recv() {
        Ok(alphai::Cmd::FetchNews { symbol, cursor, min_relevance, .. }) => {
            assert_eq!(symbol.as_deref(), Some("AAPL"));
            assert_eq!(cursor, None, "filter change must restart from page 1");
            assert_eq!(min_relevance, Some(8));
        }
        other => panic!("expected a filtered head fetch, got {:?}", other.is_ok()),
    }
    // The second ensure pass is absorbed by the inflight guard.
    app.ensure_alphai_data();
    assert!(cmds.try_recv().is_err(), "duplicate refetch for one filter change");
}

#[test]
fn score_filter_clamps_at_bounds() {
    let mut app = empty_app(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.news_min_score = 10;
    press(&mut app, KeyCode::Char('+'));
    assert_eq!(app.news_min_score, 10);
    app.news_min_score = 1;
    press(&mut app, KeyCode::Char('-'));
    assert_eq!(app.news_min_score, 1);
    // Outside a news-feed view the keys are inert.
    app.view_idx = ui::view_index(ui::ViewId::Chart);
    press(&mut app, KeyCode::Char('+'));
    assert_eq!(app.news_min_score, 1);
}

/// Below the width floor the side layout hands the whole width to the list;
/// the embedded card pane disappears but v still opens the fullscreen card.
#[test]
fn narrow_news_view_hides_side_card() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    // The pane title carries "pgup/pgdn scroll"; the footer's "v card" hint
    // stays in both sizes, so it cannot be the needle.
    let wide = render_sized(&mut app, 100, 30);
    assert!(wide.contains("pgup/pgdn scroll"), "card pane missing at 100 cols:\n{wide}");
    let narrow = render_sized(&mut app, 80, 30);
    assert!(!narrow.contains("pgup/pgdn scroll"), "card pane still there at 80 cols:\n{narrow}");
    assert!(narrow.contains("Apple beats expectations"), "list missing:\n{narrow}");
    press(&mut app, KeyCode::Char('v'));
    let overlay = render_sized(&mut app, 80, 30);
    assert!(overlay.contains(" Article "), "v overlay unavailable when narrow:\n{overlay}");
}

/// Ages under 15 minutes count as breaking (they render in the accent
/// color); unparsable timestamps never do.
#[test]
fn article_freshness_window() {
    use chrono::{Duration, Utc};
    let mut a = article("Fresh", "AAPL", 9, "positive");
    let now = Utc::now();
    a.original.time_published = (now - Duration::minutes(5)).to_rfc3339();
    assert!(ui::news::is_fresh(&a, now));
    a.original.time_published = (now - Duration::minutes(30)).to_rfc3339();
    assert!(!ui::news::is_fresh(&a, now));
    a.original.time_published = "not-a-date".into();
    assert!(!ui::news::is_fresh(&a, now));
}

#[test]
fn j_at_last_row_requests_next_page() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            Some("cur1".into()),
        ),
    );
    assert!(
        render(&mut app).contains("↓ load older articles"),
        "load-more hint missing"
    );
    press(&mut app, KeyCode::Char('j'));
    match cmds.try_recv() {
        Ok(alphai::Cmd::FetchNews { symbol, cursor, min_relevance, .. }) => {
            assert_eq!(symbol.as_deref(), Some("AAPL"));
            assert_eq!(cursor.as_deref(), Some("cur1"));
            assert_eq!(min_relevance, Some(app.news_min_score));
        }
        other => panic!("expected a page fetch, got {:?}", other.is_ok()),
    }
    // While the page is in flight the hint reports progress and a second j
    // must not spend another request.
    assert!(render(&mut app).contains("loading…"), "no in-flight feedback");
    press(&mut app, KeyCode::Char('j'));
    assert!(cmds.try_recv().is_err(), "duplicate page fetch sent");
}

#[test]
fn insider_j_at_last_row_requests_next_page() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::Insider);
    app.feeds.insert(
        alphai::insider_key("AAPL"),
        FeedBundle::new(
            vec![filing("Apple insider sold $12.5M of stock", "direct")],
            None,
            Some("cur9".into()),
        ),
    );
    press(&mut app, KeyCode::Char('j'));
    match cmds.try_recv() {
        Ok(alphai::Cmd::FetchInsider { symbol, cursor, min_relevance, .. }) => {
            assert_eq!(symbol, "AAPL");
            assert_eq!(cursor.as_deref(), Some("cur9"));
            assert_eq!(min_relevance, Some(app.insider_min_score));
        }
        other => panic!("expected an insider page fetch, got {:?}", other.is_ok()),
    }
}

/// A minimal row with a uid, as every real API article carries one (the
/// richer `article` fixture leaves it empty, staying invisible to the
/// unseen-marker tracking).
fn uid_article(uid: &str, title: &str) -> Article {
    serde_json::from_str(&format!(
        r#"{{"original": {{"uid": "{uid}", "title": "{title}"}}}}"#
    ))
    .unwrap()
}

/// A head (non-append) news fetch for `key`, as the AlphaAI task delivers it.
fn head_fetch(app: &mut App, key: &str, articles: Vec<Article>, min_relevance: Option<u8>) {
    app.apply_alphai(alphai::Event::Feed {
        key: key.into(),
        articles,
        side: None,
        next_cursor: None,
        mode: alphai::FeedMode::Replace,
        min_relevance,
    });
}

#[test]
fn page_append_extends_list_and_dedupes() {
    let mut app = empty_app(vec!["AAPL".into()]);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(vec![uid_article("aaa", "First")], None, Some("c1".into())),
    );
    app.apply_alphai(alphai::Event::Feed {
        key: "AAPL".into(),
        articles: vec![uid_article("aaa", "First reprint"), uid_article("bbb", "Second")],
        side: None,
        next_cursor: Some("c2".into()),
        mode: alphai::FeedMode::Append,
        min_relevance: Some(7),
    });
    let b = &app.feeds["AAPL"];
    assert_eq!(b.articles.len(), 2, "page boundary duplicate not dropped");
    assert_eq!(b.articles[1].original.title, "Second");
    assert_eq!(b.next_cursor.as_deref(), Some("c2"));
}

/// Rows brought in by a refetch carry the unseen marker until the cursor
/// rests on them; the first fetch of a feed is a baseline and marks nothing.
#[test]
fn refetch_marks_new_rows_until_hovered() {
    let mut app = empty_app(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    head_fetch(
        &mut app,
        "AAPL",
        vec![uid_article("aaa", "First"), uid_article("bbb", "Second")],
        Some(7),
    );
    assert!(
        !app.is_unseen("AAPL", &app.feeds["AAPL"].articles[0]),
        "first fetch marked its own baseline"
    );

    head_fetch(
        &mut app,
        "AAPL",
        vec![
            uid_article("ccc", "Breaking story"),
            uid_article("aaa", "First"),
            uid_article("bbb", "Second"),
        ],
        Some(7),
    );
    assert!(app.is_unseen("AAPL", &app.feeds["AAPL"].articles[0]), "new row unmarked");
    assert!(!app.is_unseen("AAPL", &app.feeds["AAPL"].articles[1]), "old row marked");

    // The marker renders while the cursor is parked elsewhere...
    app.news_selected = 1;
    let screen = render(&mut app);
    assert!(screen.contains("● Breaking story"), "marker missing:\n{screen}");
    // ...and hovering the row retires it.
    app.news_selected = 0;
    let screen = render(&mut app);
    assert!(!screen.contains("●"), "marker survived the hover:\n{screen}");

    // Manual r drops the bundle but not the seen set: the refetch after it
    // still marks only what is genuinely new.
    press(&mut app, KeyCode::Char('r'));
    head_fetch(
        &mut app,
        "AAPL",
        vec![uid_article("ddd", "Newer still"), uid_article("ccc", "Breaking story")],
        Some(7),
    );
    assert!(app.is_unseen("AAPL", &app.feeds["AAPL"].articles[0]), "post-r new row unmarked");
    assert!(!app.is_unseen("AAPL", &app.feeds["AAPL"].articles[1]), "post-r hovered row marked");
}

/// Paged-in older rows and a refetch after moving the score filter are the
/// reader asking for more, not news arriving: neither marks.
#[test]
fn pagination_and_filter_moves_never_mark() {
    let mut app = empty_app(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    head_fetch(&mut app, "AAPL", vec![uid_article("aaa", "First")], Some(7));
    app.apply_alphai(alphai::Event::Feed {
        key: "AAPL".into(),
        articles: vec![uid_article("old1", "Older story")],
        side: None,
        next_cursor: None,
        mode: alphai::FeedMode::Append,
        min_relevance: Some(7),
    });
    assert!(
        !app.is_unseen("AAPL", &app.feeds["AAPL"].articles[1]),
        "paged-in row marked as new"
    );

    // Loosening the filter reveals lower-scored rows: old news, no markers.
    head_fetch(
        &mut app,
        "AAPL",
        vec![uid_article("aaa", "First"), uid_article("low", "Low score story")],
        Some(6),
    );
    assert!(
        !app.is_unseen("AAPL", &app.feeds["AAPL"].articles[1]),
        "filter-revealed row marked as new"
    );
}

/// The Split strip shows the markers but has no cursor, so rendering it
/// never retires them.
#[test]
fn split_strip_shows_markers_without_clearing() {
    let mut app = empty_app(vec!["AAPL".into()]);
    head_fetch(&mut app, "AAPL", vec![uid_article("aaa", "First")], Some(7));
    head_fetch(
        &mut app,
        "AAPL",
        vec![uid_article("ccc", "Breaking story"), uid_article("aaa", "First")],
        Some(7),
    );
    app.view_idx = ui::view_index(ui::ViewId::Split);
    let screen = render(&mut app);
    assert!(screen.contains("● Breaking story"), "marker missing:\n{screen}");
    let screen = render(&mut app);
    assert!(screen.contains("● Breaking story"), "the strip retired a marker:\n{screen}");
}

#[test]
fn archive_gate_shows_upsell_and_stops_paging() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            Some("cur1".into()),
        ),
    );
    app.apply_alphai(alphai::Event::PageError {
        key: "AAPL".into(),
        error: alphai::ARCHIVE_GATE_MSG.into(),
        gated: true,
    });
    let b = &app.feeds["AAPL"];
    assert!(b.gated);
    assert_eq!(b.next_cursor, None, "gated feed still offers a cursor");
    // The list survives and the hint sells the upgrade instead of an error.
    let screen = render(&mut app);
    assert!(screen.contains("Apple beats expectations"), "list dropped:\n{screen}");
    assert!(screen.contains("archive limit"), "upsell missing:\n{screen}");
    press(&mut app, KeyCode::Char('j'));
    assert!(cmds.try_recv().is_err(), "gated feed still paged");
}

/// A uid row with an explicit publication time, for the merge ordering.
fn timed_article(uid: &str, title: &str, published: &str) -> Article {
    serde_json::from_str(&format!(
        r#"{{"original": {{"uid": "{uid}", "title": "{title}", "time_published": "{published}"}}}}"#
    ))
    .unwrap()
}

/// A delta poll's page, as the AlphaAI task delivers it.
fn delta_page(app: &mut App, key: &str, articles: Vec<Article>, cursor: &str) {
    app.apply_alphai(alphai::Event::Feed {
        key: key.into(),
        articles,
        side: None,
        next_cursor: Some(cursor.into()),
        mode: alphai::FeedMode::Merge,
        min_relevance: Some(7),
    });
}

/// Arrivals land above the shown feed, newest publication first, and a row
/// the feed already carries is dropped. The paging cursor is untouched: the
/// two cursor families are mutually unreadable and crossing them is a 400.
#[test]
fn delta_merge_prepends_arrivals_and_dedupes() {
    let mut app = empty_app(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![timed_article("aaa", "Shown", "2026-07-10T12:00:00Z")],
            None,
            Some("page1".into()),
        ),
    );
    delta_page(&mut app, "AAPL", vec![], "d1");
    delta_page(
        &mut app,
        "AAPL",
        vec![
            timed_article("aaa", "Shown, reported again", "2026-07-10T12:00:00Z"),
            timed_article("bbb", "Arrived, published earlier", "2026-07-10T11:00:00Z"),
            timed_article("ccc", "Arrived, published later", "2026-07-10T11:30:00Z"),
        ],
        "d2",
    );
    let b = &app.feeds["AAPL"];
    let titles: Vec<&str> = b.articles.iter().map(|a| a.original.title.as_str()).collect();
    assert_eq!(
        titles,
        ["Arrived, published later", "Arrived, published earlier", "Shown"],
        "arrivals must sit on top, newest publication first"
    );
    assert_eq!(b.delta_cursor.as_deref(), Some("d2"));
    assert_eq!(b.next_cursor.as_deref(), Some("page1"), "merge moved the paging cursor");
}

/// The priming poll back-fills what the published head page could not show,
/// so it is a baseline. Every later poll carries genuine arrivals and marks.
#[test]
fn delta_prime_is_a_baseline_and_later_polls_mark() {
    let mut app = empty_app(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    head_fetch(&mut app, "AAPL", vec![uid_article("aaa", "First")], Some(7));
    delta_page(&mut app, "AAPL", vec![uid_article("bbb", "Late arrival")], "d1");
    assert!(
        !app.is_unseen("AAPL", &app.feeds["AAPL"].articles[0]),
        "the priming page marked a row as new"
    );
    delta_page(&mut app, "AAPL", vec![uid_article("ccc", "Just in")], "d2");
    assert!(
        app.is_unseen("AAPL", &app.feeds["AAPL"].articles[0]),
        "an arrival is not marked as new"
    );
}

/// A background merge never changes the row under the cursor: without the
/// shift, `mark_selected_seen` would retire the marker of a row the reader
/// never opened. A merge into a feed that is not on screen moves nothing.
#[test]
fn merge_keeps_the_row_under_the_cursor() {
    let mut app = empty_app(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    head_fetch(
        &mut app,
        "AAPL",
        vec![uid_article("aaa", "First"), uid_article("bbb", "Second")],
        Some(7),
    );
    app.news_selected = 1;
    delta_page(&mut app, "AAPL", vec![], "d1");
    delta_page(
        &mut app,
        "AAPL",
        vec![uid_article("ccc", "Arrived"), uid_article("ddd", "Also arrived")],
        "d2",
    );
    assert_eq!(app.news_selected, 3, "the cursor did not move with the rows");
    assert_eq!(
        app.feeds["AAPL"].articles[app.news_selected].original.title,
        "Second",
        "the cursor changed rows under the reader"
    );

    let insider = alphai::insider_key("AAPL");
    app.feeds.insert(
        insider.clone(),
        FeedBundle::new(vec![uid_article("i1", "Filing")], None, None),
    );
    delta_page(&mut app, &insider, vec![uid_article("i2", "New filing")], "d3");
    assert_eq!(app.news_selected, 3, "a merge off screen moved the cursor");
}

/// A failed poll is not a failed view: the feed stays, the reason goes under
/// the list, and polling stops until the reader retries, because nothing here
/// ever retries by itself.
#[test]
fn poll_error_keeps_the_feed_and_stops_polling() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    app.apply_alphai(alphai::Event::PollError {
        key: "AAPL".into(),
        error: "AlphaAI API 429: slow down".into(),
    });
    let screen = render(&mut app);
    assert!(screen.contains("Apple beats expectations"), "poll error blanked the feed:\n{screen}");
    assert!(screen.contains("429"), "poll error not reported:\n{screen}");
    app.feeds.get_mut("AAPL").unwrap().polled =
        Instant::now() - std::time::Duration::from_secs(600);
    app.ensure_alphai_data();
    assert!(cmds.try_recv().is_err(), "a failed poll retried by itself");
}

/// A rejected poll position (400) or one past the archive horizon (403) is
/// not worth showing: drop it and prime a fresh one on the next tick.
#[test]
fn poll_reprime_drops_the_position_and_primes_again() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(vec![article("First", "AAPL", 9, "positive")], None, None),
    );
    app.feeds.get_mut("AAPL").unwrap().delta_cursor = Some("stale".into());
    app.apply_alphai(alphai::Event::PollReprime { key: "AAPL".into() });
    let b = &app.feeds["AAPL"];
    assert_eq!(b.delta_cursor, None, "the rejected position survived");
    assert!(!b.poll_stopped, "a reprime must not stop polling");
    assert!(app.alphai_errors.is_empty(), "a reprime surfaced as an error");
    app.feeds.get_mut("AAPL").unwrap().polled =
        Instant::now() - std::time::Duration::from_secs(600);
    app.ensure_alphai_data();
    assert!(
        matches!(
            cmds.try_recv(),
            Ok(alphai::Cmd::FetchNews { cursor: None, sort: alphai::Sort::Ingested, .. })
        ),
        "the next tick did not prime a fresh position"
    );
}

/// Every fetch pauses while an overlay is open, the poll included: merging
/// rows under a reader who is inside the article would move the list out
/// from under them.
#[test]
fn an_open_overlay_pauses_the_poll() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(vec![article("First", "AAPL", 9, "positive")], None, None),
    );
    app.feeds.get_mut("AAPL").unwrap().polled =
        Instant::now() - std::time::Duration::from_secs(600);
    app.article_overlay.open = true;
    app.ensure_alphai_data();
    assert!(cmds.try_recv().is_err(), "polled with the article overlay open");
    app.article_overlay.open = false;
    app.ensure_alphai_data();
    assert!(
        matches!(
            cmds.try_recv(),
            Ok(alphai::Cmd::FetchNews { sort: alphai::Sort::Ingested, .. })
        ),
        "the poll did not resume once the overlay closed"
    );
}

/// Trending is a fixed top-10 endpoint with no cursor and no `sort`, so its
/// tick stays the head refetch every feed used to do.
#[test]
fn trending_tick_stays_a_head_refetch() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.news_scope = NewsScope::Trending;
    app.feeds.insert(
        alphai::TRENDING_KEY.into(),
        FeedBundle::new(vec![article("Trending story", "AAPL", 9, "positive")], None, None),
    );
    let stale = Instant::now() - std::time::Duration::from_secs(600);
    let b = app.feeds.get_mut(alphai::TRENDING_KEY).unwrap();
    b.fetched = stale;
    b.polled = stale;
    app.ensure_alphai_data();
    assert!(
        matches!(cmds.try_recv(), Ok(alphai::Cmd::FetchTrending)),
        "trending stopped refetching its head"
    );
}

/// The TTL tick is a delta poll now, and a merge keeps the reader's place,
/// so it goes out wherever the cursor sits. It used to do nothing at all
/// below the top row, which left a scrolled reader with no updates.
#[test]
fn ttl_tick_polls_wherever_the_reader_is() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![
                article("First", "AAPL", 9, "positive"),
                article("Second", "AAPL", 8, "positive"),
            ],
            None,
            None,
        ),
    );
    app.feeds.get_mut("AAPL").unwrap().polled =
        Instant::now() - std::time::Duration::from_secs(600);
    app.news_selected = 1;
    app.ensure_alphai_data();
    match cmds.try_recv() {
        Ok(alphai::Cmd::FetchNews { cursor, sort, .. }) => {
            assert_eq!(cursor, None, "the first poll primes a position");
            assert_eq!(sort, alphai::Sort::Ingested, "the tick must be a delta poll");
        }
        other => panic!("expected a delta poll, got {:?}", other.is_ok()),
    }
    assert!(cmds.try_recv().is_err(), "one tick, one request");
}

/// The head fetch replaces the bundle, so it still waits for the top row —
/// but it is now the rarer side-payload refresh, several TTLs apart, and the
/// tick under a scrolled reader is a poll instead of nothing.
#[test]
fn head_refresh_still_waits_for_top_row() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(vec![article("First", "AAPL", 9, "positive")], None, None),
    );
    let stale = Instant::now() - std::time::Duration::from_secs(1_500);
    let b = app.feeds.get_mut("AAPL").unwrap();
    b.fetched = stale;
    b.polled = stale;
    app.news_selected = 1;
    app.ensure_alphai_data();
    assert!(
        matches!(
            cmds.try_recv(),
            Ok(alphai::Cmd::FetchNews { sort: alphai::Sort::Ingested, .. })
        ),
        "a head fetch cannot run under the reader"
    );
    // The poll comes back caught up, which also clears the in-flight guard.
    app.apply_alphai(alphai::Event::Feed {
        key: "AAPL".into(),
        articles: vec![],
        side: None,
        next_cursor: Some("delta1".into()),
        mode: alphai::FeedMode::Merge,
        min_relevance: None,
    });
    app.news_selected = 0;
    app.ensure_alphai_data();
    assert!(
        matches!(
            cmds.try_recv(),
            Ok(alphai::Cmd::FetchNews { cursor: None, sort: alphai::Sort::Published, .. })
        ),
        "no head refresh at the top row"
    );
}

/// Resolved [chart] and [ui] values seed the startup state (the session
/// keys keep toggling everything afterwards) and the t cycle walks the
/// configured presets.
#[test]
fn config_defaults_seed_startup_state() {
    let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
    let (alphai_tx, _alphai_rx) = tokio::sync::mpsc::unbounded_channel();
    let source = make_source("yahoo", &Config::default()).unwrap();
    let mut app = App::new(AppInit {
        symbols: vec!["AAPL".into()],
        source: Arc::new(RwLock::new(source)),
        source_name: "yahoo",
        range: Range::D1,
        interval: Interval::M5,
        params: Arc::new(RwLock::new((Range::D1, Interval::M5))),
        every: Arc::new(RwLock::new(std::time::Duration::from_secs(15))),
        rx,
        refresh: Arc::new(Notify::new()),
        alphai_tx,
        config: Config::default(),
        config_path: None,
        theme: Theme::default(),
        theme_name: crate::theme::DEFAULT_PRESET,
        chart: ChartDefaults {
            style: ChartStyle::Line,
            sma: false,
            ma_type: crate::indicators::MaType::Ema,
            rsi: false,
            volume: false,
            presets: vec![(Range::D5, Interval::M15), (Range::Y1, Interval::D1)],
            ..Default::default()
        },
        ui: UiDefaults {
            view_idx: ui::view_index(ui::ViewId::News),
            news_layout: NewsLayout::Stacked,
            news_scope: NewsScope::Market,
            news_min_score: 6,
            insider_min_score: 5,
            ..Default::default()
        },
        keymap: crate::keymap::Keymap::default(),
        alphai_enabled: false,
        first_run: false,
    });
    assert_eq!(app.view_idx, ui::view_index(ui::ViewId::News));
    assert_eq!(app.chart_style, ChartStyle::Line);
    assert!(!app.show_sma && !app.show_rsi && !app.show_volume);
    assert_eq!(app.ma_type, crate::indicators::MaType::Ema);
    assert_eq!(app.news_layout, NewsLayout::Stacked);
    assert_eq!(app.news_scope, NewsScope::Market);
    assert_eq!(app.news_min_score, 6);
    assert_eq!(app.insider_min_score, 5);
    // t cycles the configured presets, not the built-in table.
    press(&mut app, KeyCode::Char('t'));
    assert_eq!((app.range, app.interval), (Range::D5, Interval::M15));
    press(&mut app, KeyCode::Char('t'));
    assert_eq!((app.range, app.interval), (Range::Y1, Interval::D1));
    press(&mut app, KeyCode::Char('t'));
    assert_eq!((app.range, app.interval), (Range::D5, Interval::M15));
}

/// Empty config = the default look; a remapped accent slot recolors the
/// brand cell in the header.
#[test]
fn theme_accent_recolors_the_header() {
    use ratatui::style::Color;
    let mut app = fake_app();
    let fg_of_brand = |app: &mut App| {
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
        terminal.draw(|f| ui::draw(f, app)).unwrap();
        terminal.backend().buffer().cell((1, 0)).unwrap().fg
    };
    assert_eq!(fg_of_brand(&mut app), Color::Cyan);
    app.theme.accent = Color::Magenta;
    assert_eq!(fg_of_brand(&mut app), Color::Magenta);
}

/// A pane too narrow for every column drops whole columns instead of
/// letting ratatui squeeze all of them (which turned prices into "206."
/// and ranges into "319.54–3" in the split view).
#[test]
fn narrow_watchlist_drops_columns_instead_of_truncating() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::Table);
    let wide = render_sized(&mut app, 100, 12);
    assert!(wide.contains("Lo–Hi"), "screen:\n{wide}");
    assert!(wide.contains("214.50"), "screen:\n{wide}");

    // Room for everything but the range column.
    let mid = render_sized(&mut app, 60, 12);
    assert!(!mid.contains("Lo–Hi"), "range column should be gone:\n{mid}");
    assert!(mid.contains("214.50"), "price truncated:\n{mid}");
    assert!(mid.contains("+7.25%"), "percent truncated:\n{mid}");

    // Narrower still: the absolute change goes too, the price stays whole.
    let narrow = render_sized(&mut app, 46, 12);
    assert!(!narrow.contains("+14.50"), "change should be gone:\n{narrow}");
    assert!(narrow.contains("214.50"), "price truncated:\n{narrow}");
    assert!(narrow.contains("+7.25%"), "percent truncated:\n{narrow}");
}

/// Headlines wider than their column end in an ellipsis instead of being
/// chopped mid-word at the border.
#[test]
fn long_headlines_are_ellipsized() {
    let mut app = fake_app();
    app.view_idx = ui::view_index(ui::ViewId::News);
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article(
                "Apple reports the single longest headline any newsroom has ever \
                 published about a quarterly earnings call",
                "AAPL",
                9,
                "positive",
            )],
            None,
            None,
        ),
    );
    let screen = render(&mut app);
    // The list row is cut with an ellipsis (the card pane still has it all).
    let row = screen
        .lines()
        .find(|l| l.contains('▶'))
        .unwrap_or_else(|| panic!("no selected row:\n{screen}"));
    assert!(row.contains('…'), "no ellipsis in the row:\n{screen}");
    assert!(!row.contains("newsroom"), "row not cut:\n{screen}");
}

#[test]
fn ellipsize_counts_characters_not_bytes() {
    assert_eq!(ui::ellipsize("abcdef", 4), "abc…");
    // Multi-byte input must not split a character (byte truncation panics).
    assert_eq!(ui::ellipsize("привет", 3), "пр…");
    assert_eq!(ui::ellipsize("short", 20), "short");
    // Width 0 means the caller does not know the column: pass it through.
    assert_eq!(ui::ellipsize("short", 0), "short");
}

/// The cycle key rebuilds the theme the same way a restart would: the
/// preset lands, the slots written out in `[theme]` still win, and the
/// frame style from `[ui] borders` survives.
#[test]
fn theme_key_cycles_presets_over_explicit_slots() {
    use ratatui::style::Color;
    use ratatui::widgets::BorderType;

    let mut app = fake_app();
    app.config.theme = Some(std::collections::BTreeMap::from([(
        "up".to_string(),
        "#00c853".to_string(),
    )]));
    app.theme.border_type = BorderType::Plain;
    app.set_theme("catppuccin-mocha");
    assert_eq!(app.theme.accent, Color::Rgb(0xcb, 0xa6, 0xf7));
    assert_eq!(app.theme.up, Color::Rgb(0x00, 0xc8, 0x53), "explicit slot lost");
    assert_eq!(app.theme.border_type, BorderType::Plain, "[ui] borders lost");

    press(&mut app, KeyCode::Char('p'));
    assert_eq!(app.theme_name, "catppuccin-macchiato");
    assert_eq!(app.theme.accent, Color::Rgb(0xc6, 0xa0, 0xf6));

    // P walks back, so overshooting is one keypress to undo.
    press(&mut app, KeyCode::Char('P'));
    assert_eq!(app.theme_name, "catppuccin-mocha");
    press(&mut app, KeyCode::Char('p'));

    // Every preset is reachable from the keyboard, and the cycle wraps
    // back to where it started after a full lap.
    for _ in 0..crate::theme::PRESETS.len() {
        press(&mut app, KeyCode::Char('p'));
    }
    assert_eq!(app.theme_name, "catppuccin-macchiato");
    assert_eq!(app.theme.up, Color::Rgb(0x00, 0xc8, 0x53));
}

/// Save persists the picked preset into `[theme] preset`; picking the
/// built-in theme takes the line back out rather than writing a no-op.
#[test]
fn settings_theme_row_persists_the_preset() {
    let mut app = empty_app(vec!["AAPL".into()]);
    press(&mut app, KeyCode::Char('s'));
    while !matches!(settings_rows()[app.settings.cursor], SettingsRow::ThemeChoice) {
        press(&mut app, KeyCode::Down);
    }
    let screen = render(&mut app);
    assert!(screen.contains("Theme"), "screen:\n{screen}");

    // Cycling previews live, like the p key does, and the arrows really
    // point somewhere: left walks back through the list, right forward.
    press(&mut app, KeyCode::Left);
    assert_eq!(
        app.settings.theme_choice,
        crate::theme::PRESETS[crate::theme::PRESETS.len() - 1].0,
        "left arrow must step back, not forward"
    );
    press(&mut app, KeyCode::Right);
    assert_eq!(app.settings.theme_choice, crate::theme::DEFAULT_PRESET);
    press(&mut app, KeyCode::Right);
    assert_eq!(app.settings.theme_choice, "catppuccin-mocha");
    assert_eq!(app.theme_name, "catppuccin-mocha");
    let cfg = app.settings_merged_config();
    assert_eq!(
        cfg.theme.as_ref().and_then(|t| t.get("preset")).map(String::as_str),
        Some("catppuccin-mocha")
    );

    // All the way back around to the built-in theme: no key, and no empty
    // [theme] table left behind either.
    for _ in 1..crate::theme::PRESETS.len() {
        press(&mut app, KeyCode::Right);
    }
    assert_eq!(app.settings.theme_choice, crate::theme::DEFAULT_PRESET);
    assert_eq!(app.settings_merged_config().theme, None);
}

/// Every framed panel must come from `Theme::panel`, so a theme really
/// recolors the whole frame. Corners are the tell: nothing but a block
/// border draws them, and a panel built with a bare `Block::bordered()`
/// would keep the default color and the square corner set.
#[test]
fn borders_are_themed() {
    use ratatui::style::Color;
    const ROUNDED: [&str; 4] = ["╭", "╮", "╰", "╯"];
    const SQUARE: [&str; 4] = ["┌", "┐", "└", "┘"];

    let mut app = fake_app();
    app.feeds.insert(
        "AAPL".into(),
        FeedBundle::new(
            vec![article("Apple beats expectations", "AAPL", 9, "positive")],
            None,
            None,
        ),
    );
    app.feeds.insert(
        alphai::insider_key("AAPL"),
        FeedBundle::new(
            vec![filing("Apple insider sold $12.5M of stock", "direct")],
            None,
            None,
        ),
    );
    app.theme.border = Color::Rgb(1, 2, 3);

    for view in ui::VIEWS {
        app.view_idx = ui::view_index(view.id());
        let mut terminal = Terminal::new(TestBackend::new(120, 40)).unwrap();
        terminal.draw(|f| ui::draw(f, &mut app)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        let mut corners = 0;
        for y in buffer.area.top()..buffer.area.bottom() {
            for x in buffer.area.left()..buffer.area.right() {
                let cell = buffer.cell((x, y)).unwrap();
                assert!(
                    !SQUARE.contains(&cell.symbol()),
                    "{:?}: a panel bypassed Theme::panel (square corner at {x},{y})",
                    view.id()
                );
                if ROUNDED.contains(&cell.symbol()) {
                    corners += 1;
                    assert_eq!(
                        cell.fg,
                        Color::Rgb(1, 2, 3),
                        "{:?}: unthemed border at {x},{y}",
                        view.id()
                    );
                }
            }
        }
        assert!(corners >= 4, "{:?}: no framed panel rendered", view.id());
    }
}

/// Save must start from the loaded config and replace only the settings
/// screen's own fields, so file-only sections like [theme] survive it.
#[test]
fn settings_save_merge_preserves_file_only_sections() {
    let mut app = fake_app();
    app.config.theme = Some(std::collections::BTreeMap::from([(
        "accent".to_string(),
        "magenta".to_string(),
    )]));
    app.open_settings();
    app.settings.key_values.insert("alphai", "ak_live_new".into());
    let merged = app.settings_merged_config();
    assert_eq!(
        merged.theme.as_ref().and_then(|t| t.get("accent")).map(String::as_str),
        Some("magenta")
    );
    assert_eq!(merged.keys.get("alphai").map(String::as_str), Some("ak_live_new"));
    assert_eq!(merged.watchlist, vec!["AAPL".to_string(), "MSFT".to_string()]);
}

/// The single-copy guards must hold for every feed kind: the insider tick
/// polls too, and its head refresh still waits for the top row. Delta mode
/// matters most here, since a Form 4 is filed days after its trade and
/// lands below the head of the published page.
#[test]
fn insider_tick_polls_and_head_refresh_waits_for_top_row() {
    let (mut app, mut cmds) = empty_app_with_cmds(vec!["AAPL".into()]);
    app.view_idx = ui::view_index(ui::ViewId::Insider);
    let key = alphai::insider_key("AAPL");
    app.feeds.insert(
        key.clone(),
        FeedBundle::new(
            vec![
                filing("Apple insider sold $12.5M of stock", "direct"),
                filing("Officer bought 10,000 shares", "indirect"),
            ],
            None,
            None,
        ),
    );
    let stale = Instant::now() - std::time::Duration::from_secs(1_500);
    let b = app.feeds.get_mut(&key).unwrap();
    b.fetched = stale;
    b.polled = stale;
    app.news_selected = 1;
    app.ensure_alphai_data();
    assert!(
        matches!(
            cmds.try_recv(),
            Ok(alphai::Cmd::FetchInsider { sort: alphai::Sort::Ingested, .. })
        ),
        "insider head fetch ran under the reader"
    );
    app.apply_alphai(alphai::Event::Feed {
        key: key.clone(),
        articles: vec![],
        side: None,
        next_cursor: Some("delta1".into()),
        mode: alphai::FeedMode::Merge,
        min_relevance: None,
    });
    app.news_selected = 0;
    app.ensure_alphai_data();
    assert!(
        matches!(
            cmds.try_recv(),
            Ok(alphai::Cmd::FetchInsider { cursor: None, sort: alphai::Sort::Published, .. })
        ),
        "no insider head refresh at the top row"
    );
}

#[test]
fn settings_alphai_key_hint_when_missing() {
    if std::env::var("ALPHAI_API_KEY").is_ok() {
        return; // the env-override hint takes precedence; nothing to assert
    }
    let mut app = fake_app();
    app.open_settings();
    let screen = render(&mut app);
    assert!(
        screen.contains("get free on alphai.io/developers"),
        "missing-key hint absent:\n{screen}"
    );
    // Once a key is stored the hint disappears.
    app.config.keys.insert("alphai".into(), "ak_live_abcdefgh1234".into());
    app.open_settings();
    let screen = render(&mut app);
    assert!(
        !screen.contains("get free on alphai.io/developers"),
        "hint shown next to a configured key:\n{screen}"
    );
}

#[test]
fn settings_overlay_masks_keys() {
    let mut app = fake_app();
    app.config.keys.insert("alphai".into(), "ak_live_abcdefgh1234".into());
    app.config.keys.insert("alpaca_secret".into(), "alpaca-secret-abcd9876".into());
    app.open_settings();
    let screen = render(&mut app);
    assert!(screen.contains("Settings"), "screen:\n{screen}");
    assert!(screen.contains("Price source"), "screen:\n{screen}");
    assert!(screen.contains("Alpaca secret"), "screen:\n{screen}");
    assert!(screen.contains("News opens"), "screen:\n{screen}");
    assert!(screen.contains("‹ alphai ›"), "screen:\n{screen}");
    assert!(screen.contains("ak_liv…1234"), "screen:\n{screen}");
    assert!(
        !screen.contains("ak_live_abcdefgh1234"),
        "raw key leaked to screen:\n{screen}"
    );
    assert!(screen.contains("alpaca…9876"), "screen:\n{screen}");
    assert!(
        !screen.contains("alpaca-secret-abcd9876"),
        "raw alpaca secret leaked to screen:\n{screen}"
    );
}

#[test]
fn first_run_opens_settings_with_welcome() {
    let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
    let (alphai_tx, _alphai_rx) = tokio::sync::mpsc::unbounded_channel();
    let source = make_source("yahoo", &Config::default()).unwrap();
    let mut app = App::new(AppInit {
        symbols: vec!["AAPL".into()],
        source: Arc::new(RwLock::new(source)),
        source_name: "yahoo",
        range: Range::D1,
        interval: Interval::M5,
        params: Arc::new(RwLock::new((Range::D1, Interval::M5))),
        every: Arc::new(RwLock::new(std::time::Duration::from_secs(15))),
        rx,
        refresh: Arc::new(Notify::new()),
        alphai_tx,
        config: Config::default(),
        config_path: None,
        theme: Theme::default(),
        theme_name: crate::theme::DEFAULT_PRESET,
        chart: ChartDefaults::default(),
        ui: UiDefaults::default(),
        keymap: crate::keymap::Keymap::default(),
        alphai_enabled: false,
        first_run: true,
    });
    assert!(app.settings.open);
    let screen = render(&mut app);
    assert!(screen.contains("Welcome to alphai-tui"), "screen:\n{screen}");
    assert!(screen.contains("https://alphai.io"), "screen:\n{screen}");
}

/// The Poll every settings row: seeded from the live interval, edited like a
/// key field, validated and applied on Save. config_path is None here so the
/// file write fails, but the live interval and in-memory config still apply.
#[test]
fn settings_poll_every_saves_and_applies_live() {
    let mut app = empty_app(vec!["AAPL".into()]);
    press(&mut app, KeyCode::Char('s'));
    assert!(app.settings.open);
    assert_eq!(app.settings.every_input, "15");
    let screen = render(&mut app);
    assert!(screen.contains("Poll every"), "screen:\n{screen}");
    assert!(screen.contains("15s"), "screen:\n{screen}");

    while !matches!(settings_rows()[app.settings.cursor], SettingsRow::PollEvery) {
        press(&mut app, KeyCode::Down);
    }
    press(&mut app, KeyCode::Enter);
    assert!(app.settings.editing);
    press(&mut app, KeyCode::Backspace);
    press(&mut app, KeyCode::Backspace);
    press(&mut app, KeyCode::Char('5'));
    press(&mut app, KeyCode::Enter);
    assert_eq!(app.settings.every_input, "5");

    while !matches!(settings_rows()[app.settings.cursor], SettingsRow::Save) {
        press(&mut app, KeyCode::Down);
    }
    press(&mut app, KeyCode::Enter);
    assert_eq!(app.config.every, Some(5));
    // Reopening reseeds from the shared interval the poller reads: the live
    // value really changed.
    app.open_settings();
    assert_eq!(app.settings.every_input, "5");
}

/// A bad interval blocks Save with a message instead of half-applying.
#[test]
fn settings_poll_every_rejects_bad_input() {
    for bad in ["abc", "1", "0", ""] {
        let mut app = empty_app(vec!["AAPL".into()]);
        press(&mut app, KeyCode::Char('s'));
        app.settings.every_input = bad.to_string();
        while !matches!(settings_rows()[app.settings.cursor], SettingsRow::Save) {
            press(&mut app, KeyCode::Down);
        }
        press(&mut app, KeyCode::Enter);
        assert!(app.settings.open, "at {bad:?}: settings closed on bad input");
        assert!(
            app.settings.message.as_deref().is_some_and(|m| m.contains("poll interval")),
            "at {bad:?}: no validation message"
        );
        assert_eq!(app.config.every, None, "at {bad:?}: bad value persisted");
        app.open_settings();
        assert_eq!(app.settings.every_input, "15", "at {bad:?}: live interval changed");
    }
}