aboutsummaryrefslogtreecommitdiffstats
path: root/src/features/messages.js
blob: b28b899ca364cd6f56058a4cd0b5876ed512ed89 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
// Messages — Concord community chat (CORD-01..05) + NIP-17 private DMs.
//
// Communities are end-to-end private: there is no global discovery in
// Concord, membership travels by invite. coinos ships with one built-in
// community (below) so every user starts somewhere; beyond it users join by
// invite link, by direct invite (giftwrapped to their npub), or by founding
// their own community in-app.
//
// Identity: the session's nostr login when a signer is live, else the
// wallet's NIP-06 key. Community traffic encrypts under stream keys the app
// holds (signers only sign seals); DMs seal to the peer, which is what the
// widened signer adapters (encryptTo/decryptFrom) exist for. The DM inbox
// listens for both identities and decrypts with whichever keys are present.

import {
  subscribeOn, publishOn, queryOn, fetchInboxRelays,
  npubOf, neventOf, parseNostrPubkey, parseNostrRef, generateSecretKey, getPublicKey, finalizeEvent, nip44,
  PROFILE_RELAYS, openWrapsOffthread, unwrapDMsOffthread,
} from '../nostr.js';
import {
  channelKey, controlKey, guestbookKey, openWrap, wrapRumor, rumorWithId,
  foldControl, foldGuestbook, observeAuthor, eventMs, msTags, makeEdition,
  communityId, parseInviteLink, makeInviteLink, makeInviteBundleEvent, openInviteBundle,
} from '../concord.js';
import { makeDMRumor, makeDMReaction, unwrapDM, wrapDM } from '../dm.js';
import { saveInbox } from '../dm-inbox.js';
import { makeSearcher, resultRows, fallbackAvatar, warmSearch } from '../recipient-search.js';
import { getNetwork } from '../api.js';
import { decodeBolt11 } from '../ark/lightning.js';
import { hexToBytes, bytesToHex } from '@noble/hashes/utils';
import { t } from '../i18n.js';

// The coinos community's join material lives in ../community.js — shared
// with the public read-only chat page so the two can never drift.
import { COMMUNITY, EPOCH } from '../community.js';
const DM_RELAYS = ['wss://relay.coinos.io', 'wss://nos.lol'];
const NOTIFIER = 'https://nwcpush.coinos.io';
const APP_BASE = 'https://v3.coinos.io';
const CACHE_MAX = 50; // messages kept per channel / per DM thread in feature state
// NIP-89 client attribution on PUBLIC notes (posts + thread replies) — other
// clients render it as "via coinos". Name-only: the fuller form appends a
// kind-31990 handler coordinate, which we haven't published. Deliberately
// absent from anything encrypted (DMs, community wraps) — those are private
// and need no billboard.
const CLIENT_TAG = ['client', 'coinos'];

export function messagesFeature(ctx) {
  const { h, ui, render, wallet, toast, hook } = ctx;

  // ---- persisted state ----------------------------------------------------

  const st = () => {
    const s = wallet.loadFeatureState('messages', {});
    s.joined ||= {}; // { [cid]: { [pubkey]: true } }
    s.cache ||= {}; // { [channelId]: [msgs] }
    s.communities ||= []; // join material beyond the built-in
    s.invites ||= {}; // { [cid]: { sk, token, url } } — minted links
    s.dms ||= {}; // { [peerPk]: [{ id, from, text, t }] }
    s.declined ||= {}; // direct-invite rumor ids dismissed
    s.tombstones ||= {}; // { [cid]: removed_at ms } — left communities (CORD-02 §8)
    s.read ||= {}; // { ['dm:'+pk | 'ch:'+id]: created_at } — last message we've seen
    s.notify ||= {}; // { [cid]: true } — communities that may buzz your phone (opt-in)
    s.drafts ||= {}; // { ['dm:'+pk | 'ch:'+id]: text } — half-typed messages
    s.zaps ||= {}; // { [eventId]: { s: sats, m: 1 } } — last known zap tallies
    for (const c of s.communities) c.added_at ||= Date.now();
    // pre-multi-community shape: joined was { [pubkey]: true } for coinos
    for (const k of Object.keys(s.joined))
      if (s.joined[k] === true) { (s.joined[COMMUNITY.community_id] ||= {})[k] = true; delete s.joined[k]; }
    return s;
  };
  const save = (s) => wallet.saveFeatureState('messages', s);

  const communities = () => [COMMUNITY, ...st().communities];

  // ---- unread -------------------------------------------------------------
  // A conversation is unread when its newest message from someone else is
  // newer than the last one we looked at. The watermark is the rumor's own
  // created_at, not a local clock, so it means the same thing on every device
  // the state syncs to. Our own messages never count — sending isn't reading,
  // but you've obviously seen what you wrote.

  const dmRead = (pk) => 'dm:' + pk;
  const chRead = (id) => 'ch:' + id;
  // The list screen has a watermark of its own: standing on it answers the
  // header dot ("someone's waiting" — you've now been shown who), while each
  // row keeps its own dot until that conversation is actually opened.
  const HOME_READ = 'home';

  const newestFrom = (entries, theirs) => {
    let ts = 0;
    for (const m of entries) if (theirs(m)) ts = Math.max(ts, m.rumor.created_at || 0);
    return ts;
  };

  function markRead(key, ts) {
    const s = st();
    if (!ts || (s.read[key] || 0) >= ts) return;
    s.read[key] = ts;
    bumpMsgRev();
    save(s);
    // read markers ride their own sync domain (registered below) — nudging
    // the cache is what gets the watermark onto the relays for other devices
    try { wallet.saveCache(); } catch {}
  }

  // One tap, every dot: advance each conversation's watermark to its newest
  // foreign message — DMs and community channels alike.
  function markAllRead() {
    const s = st();
    const my = myPubkeys();
    let changed = false;
    const bump = (key, ts) => { if (ts && (s.read[key] || 0) < ts) { s.read[key] = ts; changed = true; } };
    for (const [pk, msgs] of threads) bump(dmRead(pk), newestFrom(msgs.values(), (m) => !m.mine));
    for (const room of rooms.values())
      for (const [id, msgs] of room.byChannel)
        bump(chRead(id), newestFrom(msgs.values(), (m) => !my.includes(m.author)));
    if (changed) { bumpMsgRev(); save(s); try { wallet.saveCache(); } catch {} }
    render();
  }

  const anyUnread = () => {
    for (const [pk, msgs] of threads) if (dmUnread(pk, msgs)) return true;
    for (const room of rooms.values()) if (roomUnread(room)) return true;
    return false;
  };

  // Read state syncs across devices: each watermark only ever grows, so a
  // per-key max is a clean commutative merge — a thread read anywhere is
  // read everywhere.
  if (wallet.registerCacheExtension && !wallet._msgReadSync) {
    wallet._msgReadSync = true;
    wallet.registerCacheExtension({
      domain: 'msgread',
      mergeAlways: true,
      save: () => {
        const read = wallet.loadFeatureState('messages', {}).read || {};
        return Object.keys(read).length ? { msgRead: read } : {};
      },
      load: (d) => {
        if (!d.msgRead) return;
        const s = wallet.loadFeatureState('messages', {});
        s.read ||= {};
        let changed = false;
        for (const [k, v] of Object.entries(d.msgRead)) {
          if (typeof v === 'number' && (s.read[k] || 0) < v) { s.read[k] = v; changed = true; }
        }
        if (changed) { bumpMsgRev(); wallet.saveFeatureState('messages', s); }
      },
    });
  }

  // Per-conversation dots for the list screen: newer than when we last had
  // that thread (or any channel of that room) open.
  const dmUnread = (pk, msgs) =>
    newestFrom(msgs.values(), (m) => !m.mine) > (st().read[dmRead(pk)] || 0);
  function roomUnread(room) {
    const s = st();
    const my = myPubkeys();
    for (const [id, msgs] of room.byChannel)
      if (newestFrom(msgs.values(), (m) => !my.includes(m.author)) > (s.read[chRead(id)] || 0)) return true;
    return false;
  }

  // How many conversations are waiting on us — the header only draws a dot, but
  // a count keeps the door open for a number later. Floored by the list-screen
  // watermark: once you've seen the list, the header stops repeating it.
  //
  // Memoized on a revision counter: the header asks on EVERY render, and the
  // walk touches every cached message in every thread and room — a phone
  // paid that for each toast and repaint. Message arrivals and read-marks
  // bump the revision; everything else reuses the answer.
  let msgRev = 0;
  const bumpMsgRev = () => { msgRev++; };
  let _unreadMemo = { rev: -1, val: 0 };
  function unreadCount() {
    if (_unreadMemo.rev === msgRev) return _unreadMemo.val;
    _unreadMemo = { rev: msgRev, val: unreadCountNow() };
    return _unreadMemo.val;
  }
  function unreadCountNow() {
    const s = st();
    const my = myPubkeys();
    const seen = s.read[HOME_READ] || 0;
    let n = 0;
    for (const [pk, msgs] of threads)
      if (newestFrom(msgs.values(), (m) => !m.mine) > Math.max(seen, s.read[dmRead(pk)] || 0)) n++;
    for (const room of rooms.values())
      for (const [id, msgs] of room.byChannel)
        if (newestFrom(msgs.values(), (m) => !my.includes(m.author)) > Math.max(seen, s.read[chRead(id)] || 0)) n++;
    return n;
  }
  const communityById = (cid) => communities().find((c) => c.community_id === cid);

  // ---- identity -----------------------------------------------------------

  // Who we speak as. If the user logged in with a nostr account we speak as
  // that account or not at all — falling back to the wallet's own key would
  // sign under a pubkey that isn't the one their avatar and profile show,
  // which reads to everyone else as a different person entirely.
  async function identity() {
    const id = hook('nostrLoginIdentity');
    if (id) {
      const signer = id.signer || (await hook('nostrLoginResume'));
      return signer ? { pubkey: id.pubkey, signer } : null;
    }
    if (wallet.nostr && wallet.nostr.sk) return { pubkey: wallet.nostr.pk, signer: wallet.nostr.sk };
    return null;
  }
  const myPubkeys = () => {
    const pks = [];
    const id = hook('nostrLoginIdentity');
    if (id) pks.push(id.pubkey);
    if (wallet.nostr && wallet.nostr.pk && !pks.includes(wallet.nostr.pk)) pks.push(wallet.nostr.pk);
    return pks;
  };
  const isMe = (pk) => myPubkeys().includes(pk);
  // The ONE nostr identity this wallet uses for DMs: the login identity when
  // signed in (extension/bunker/passkey/Google), else the seed-derived key. A
  // wallet has two keys (seed + login), but only this one should receive and
  // advertise DMs — advertising/polling the seed key as a SECOND inbox is what
  // produced duplicate welcome DMs and split a person's messages across two
  // identities. isMe/dmDecryptors stay tolerant of both so already-received
  // messages still thread and align; we just stop treating the seed key as a
  // live second inbox. (One key here, but kept as a list for the '#p' filters.)
  const dmSubKeys = () => {
    const id = hook('nostrLoginIdentity');
    const pk = (id && id.pubkey) || (wallet.nostr && wallet.nostr.pk) || null;
    return pk ? [pk] : [];
  };
  // "No identity" while soft-locked means the keys left with the lock — say
  // that, not "signer disconnected" (which reads as a nostr-login problem).
  const noIdToast = () => {
    // A missing signer gets the reconnect screen, not a dead-end toast —
    // logging out and back in was the workaround nobody should need.
    if (!wallet.watchOnly && hook('nostrReconnectPrompt')) return;
    toast(t(wallet.watchOnly ? 'msgLockedChat' : 'msgNoIdentity'));
  };
  // Thrown by the publish paths after noIdToast already did the talking
  // (opened the reconnect screen, or toasted): callers must not toast it
  // again — a pasted-nsec login that lost its signer on reload used to get
  // the toast INSTEAD of the screen with the nsec field this way.
  class NoIdentity extends Error { constructor() { super(t('msgNoIdentity')); this.silent = true; } }
  const requireIdentity = async () => {
    const id = await identity();
    if (!id) { noIdToast(); throw new NoIdentity(); }
    return id;
  };

  // ---- shared runtime -----------------------------------------------------

  const rooms = new Map(); // cid -> room runtime
  const threads = new Map(); // peerPk -> Map(rumorId -> { rumor, mine })
  // DM reactions, keyed by the reacted message's id — no thread needed, so a
  // reaction that arrives before its message still lands. Ephemeral like the
  // community ones: the wrap backlog rebuilds them on reload.
  const dmReacts = new Map(); // rumorId -> Map(authorPk -> emoji)
  const pendingDirect = new Map(); // rumor id -> { bundle, from }
  const profiles = new Map(); // pubkey -> profile | null while loading
  const seenWraps = new Set();
  // Wraps this device already opened (or gave up on), remembered ACROSS
  // boots: relays re-serve their last ~400 wraps on every subscribe, and a
  // remote-signer wallet paid two NIP-46 round trips (sign + verify each)
  // per wrap to rediscover DMs it already had — ~4s of a phone's boot.
  // Keyed by an id prefix (64 bits is plenty for "skip this one").
  const WRAPS_MAX = 1500;
  const wrapKey = (id) => String(id).slice(0, 16);
  let wrapLog = null, wrapsTimer = 0;
  function loadSeenWraps() {
    if (wrapLog) return;
    wrapLog = (st().wraps || []).slice(-WRAPS_MAX);
    for (const k of wrapLog) seenWraps.add(k);
  }
  function rememberWrap(id) {
    const k = wrapKey(id);
    if (!wrapLog) wrapLog = [];
    if (!seenWraps.has(k)) wrapLog.push(k);
    seenWraps.add(k);
    clearTimeout(wrapsTimer);
    wrapsTimer = setTimeout(() => {
      try { const s = st(); s.wraps = wrapLog.slice(-WRAPS_MAX); wrapLog = s.wraps; save(s); } catch {}
    }, 1500);
  }
  let dmStarted = false;
  let allUnsubs = [];

  let repaintTimer = null;
  const scheduleRepaint = () => {
    if (repaintTimer) return;
    repaintTimer = setTimeout(() => {
      repaintTimer = null;
      if (ui.screen === 'wallet') render();
    }, 80);
  };

  // Profiles persist across sessions (capped) so known faces paint right
  // away instead of flashing the punk fallback; entries refresh in the
  // background once a day.
  const PROFILE_TTL = 24 * 3600_000;
  let profilesWarmed = false;
  function warmProfiles() {
    if (profilesWarmed) return;
    profilesWarmed = true;
    const cached = wallet.loadFeatureState('profiles', {});
    for (const [pk, p] of Object.entries(cached)) if (!profiles.has(pk)) profiles.set(pk, p);
  }
  function persistProfile(pk, p) {
    // A faceless answer is not a fact worth writing down — persisting
    // {name:null, picture:null} rows only evicts real faces from the cap and
    // spreads a cold-relay miss across sessions.
    if (!p || (!p.name && !p.picture)) return;
    const s = wallet.loadFeatureState('profiles', {});
    s[pk] = { name: p.name || null, picture: p.picture || null, nip05: p.nip05 || null, lud16: p.lud16 || null,
      about: p.about || null, banner: p.banner || null, t: Date.now(),
      ...(p.thumbFor === p.picture && p.thumb
        ? { thumb: p.thumb, thumbFor: p.thumbFor, thumbPx: p.thumbPx || 0 } : {}),
      ...(p.thumbFail ? { thumbFail: p.thumbFail, thumbFailAt: p.thumbFailAt || 0, thumbFails: p.thumbFails || 1,
        thumbFailVersion: p.thumbFailVersion || 0 } : {}) };
    // Thumbnails are the bulk of this blob, so they live on a budget: the
    // least recently seen faces give theirs up first. The row itself stays —
    // that face just paints the way it used to.
    if (JSON.stringify(s).length > THUMB_BUDGET) {
      const oldestFirst = Object.keys(s).filter((k) => s[k].thumb).sort((a, b) => (s[a].t || 0) - (s[b].t || 0));
      for (const k of oldestFirst) {
        delete s[k].thumb; delete s[k].thumbFor;
        if (JSON.stringify(s).length <= THUMB_BUDGET) break;
      }
    }
    const keys = Object.keys(s);
    if (keys.length > 150) {
      // the user's own faces never churn out — their avatar going punk over
      // a busy community room is the one eviction people actually notice
      const keep = new Set([(hook('nostrLoginIdentity') || {}).pubkey,
        wallet.nostrPubkey && wallet.nostrPubkey()].filter(Boolean));
      const evictable = keys.filter((k) => !keep.has(k));
      for (const k of evictable.sort((a, b) => (s[a].t || 0) - (s[b].t || 0)).slice(0, keys.length - 150)) delete s[k];
    }
    wallet.saveFeatureState('profiles', s);
  }
  // A punk picture is OUR OWN art. Every coinos user who keeps the default
  // publishes https://v3.coinos.io/punks/N.webp as their nostr picture, and
  // the legacy coinos.io copies 502 for a third of the set — so painting
  // those from the local files means no network, no broken faces, and the
  // right size for the circle being drawn.
  // Absolute (what the wizard publishes) or the bare relative path an older
  // build wrote into a few profiles.
  const PUNK_PIC_RE = /^(?:https?:\/\/(?:[a-z0-9-]+\.)*coinos\.io\/)?punks\/(\d{1,2})\.webp$/i;
  const localPunk = (url, big) => {
    const m = PUNK_PIC_RE.exec(url || '');
    return m ? (big ? `punks/${m[1]}.webp` : `punks-sm/${m[1]}.webp`) : null;
  };

  // A refreshed profile whose picture hasn't changed keeps the thumbnail we
  // already made of it — otherwise every relay refresh throws the local copy
  // away and the original gets downloaded all over again.
  const keepThumb = (pk, entry) => {
    const prev = profiles.get(pk);
    if (!prev || !entry || !entry.picture) return entry;
    if (prev.thumb && prev.thumbFor === entry.picture) {
      // thumbPx rides along: without it a refreshed profile looks like a
      // thumbnail of unknown size and gets remade on every relay refresh
      entry.thumb = prev.thumb; entry.thumbFor = prev.thumbFor; entry.thumbPx = prev.thumbPx || 0;
    }
    if (prev.thumbFail === entry.picture) {
      entry.thumbFail = prev.thumbFail;
      entry.thumbFailAt = prev.thumbFailAt || 0;
      entry.thumbFails = prev.thumbFails || 1;
      entry.thumbFailVersion = prev.thumbFailVersion || 0;
    }
    return entry;
  };

  // Pull the picture bytes into the HTTP cache the moment we learn the URL —
  // an avatar div then paints instantly instead of holding its quiet circle
  // while the image downloads.
  const preloadPicture = (p) => { try { if (p && p.picture) new Image().src = p.picture; } catch {} };

  // A profile picture is whatever its owner uploaded, and that is very often
  // the full-size original: among the faces this wallet had cached, one was a
  // 5MB JPEG and another 3.9MB — megabytes fetched and decoded to paint a
  // 30px circle, which is the second of blank circles you see after a
  // refresh. So the first time we see a picture we downscale it ONCE and keep
  // the thumbnail beside the profile. Every later boot paints the face from
  // localStorage in the first frame, with no network at all.
  //
  // Reading the pixels needs CORS (a tainted canvas can't be exported). Most
  // avatar hosts allow it; the ones that don't are remembered as failures and
  // keep today's behaviour rather than being retried every boot.
  const THUMB_PX = 144;      // the 44px feed circle at 3x, with room to spare;
                             // the 64px profile avatar layers the original
                             // over it anyway
  // Chars of data URL for one face. Scaled with THUMB_PX: the busiest
  // picture on hand fit 9000 at 96px and needs 12827 at 144px — measured in
  // the browser, not estimated, because its own webp encoder is nothing
  // like as kind to noise as an offline one. A face over the cap keeps
  // painting from its original, which is the old behaviour, so the cap only
  // decides who gets the fast path.
  const THUMB_MAX = 16_000;
  // ...and for all of them together. Raised with THUMB_PX: a 144px face
  // costs about 5.4KB against 96px's 3.2KB, and the budget is what decides
  // how many faces paint instantly rather than fetching their original —
  // this holds about fifty, which covers a feed and an inbox at once. The
  // blob carries each profile's bio and banner as well now — a couple of
  // hundred bytes each, and the reason a profile page paints on the first
  // tap — so the ceiling is raised to keep the same number of faces.
  const THUMB_BUDGET = 320_000;
  const THUMB_SLOW = 20_000; // a host that won't answer must not hold a slot
  const THUMB_RETRY = 6 * 3600_000; // ...and must not be written off for good
  const THUMB_RETRY_MAX = 14 * 24 * 3600_000; // a host that never works, backed off
  // Older crossOrigin <img> attempts could fail on a cached no-CORS response.
  // Those failures must not suppress the corrected fetch/blob path.
  const THUMB_VERSION = 1;
  const thumbing = new Set();
  function makeThumb(pk, p) {
    if (!p || !p.picture || typeof document === 'undefined') return;
    // thumbPx: a thumbnail made when the circles were smaller is too soft for
    // today's, so it's remade once. The old one keeps painting until then.
    if (p.thumbFor === p.picture && p.thumbPx === THUMB_PX) return;
    if (localPunk(p.picture)) return; // our own art, already the right size on disk
    // A failed attempt is usually the network, not the host: these images sit
    // on CDNs that answer in 700ms one minute and time out the next. So every
    // failure is tried again — backing off each time, so a host that truly
    // won't have us is asked about twice a month rather than every boot.
    if (p.thumbFailVersion === THUMB_VERSION && p.thumbFail === p.picture
      && Date.now() - (p.thumbFailAt || 0) < Math.min(THUMB_RETRY * 2 ** ((p.thumbFails || 1) - 1), THUMB_RETRY_MAX)) return;
    if (thumbing.has(pk) || thumbing.size >= 3) return; // a few at a time
    // Making the thumbnail costs one more fetch of the original today to
    // save every fetch after it — but not on a connection someone is
    // nursing. Data Saver keeps today's behaviour.
    try { if (navigator.connection && navigator.connection.saveData) return; } catch {}
    thumbing.add(pk);
    const url = p.picture;
    const done = (patch) => {
      thumbing.delete(pk);
      const entry = { ...(profiles.get(pk) || p), ...patch };
      if (patch.thumb) {
        delete entry.thumbFail; delete entry.thumbFailAt;
        delete entry.thumbFails; delete entry.thumbFailVersion;
      }
      profiles.set(pk, entry);
      persistProfile(pk, entry);
      if (patch.thumb) scheduleRepaint();
    };
    const failed = () => done({ thumbFail: url, thumbFailAt: Date.now(), thumbFailVersion: THUMB_VERSION,
      thumbFails: (p.thumbFailVersion === THUMB_VERSION && p.thumbFail === url ? p.thumbFails || 0 : 0) + 1 });
    // Fetch the bytes rather than pointing a crossOrigin <img> at the URL.
    // The avatar itself is painted as a plain background-image, so the
    // picture is already in the HTTP cache as a no-CORS entry — and a
    // crossOrigin <img> for the same URL reuses that entry and fails the CORS
    // check, which is how a host that allows us perfectly well (verified: the
    // same fetch succeeds) came to be written off. Drawing from a blob also
    // keeps the canvas untainted, so nothing here depends on the element's
    // CORS bookkeeping at all.
    (async () => {
      let bmp = null;
      try {
        const res = await fetch(url, { mode: 'cors', cache: 'reload', signal: AbortSignal.timeout(THUMB_SLOW) });
        if (!res.ok) throw new Error('http ' + res.status);
        bmp = await createImageBitmap(await res.blob());
        // centre-crop to a square, the way background-size:cover paints it
        const side = Math.min(bmp.width, bmp.height);
        if (!side) throw new Error('empty');
        const c = document.createElement('canvas');
        c.width = c.height = THUMB_PX;
        c.getContext('2d').drawImage(bmp, (bmp.width - side) / 2, (bmp.height - side) / 2,
          side, side, 0, 0, THUMB_PX, THUMB_PX);
        let data = c.toDataURL('image/webp', 0.75);
        if (!data.startsWith('data:image/webp')) data = c.toDataURL('image/jpeg', 0.7);
        if (data.length > THUMB_MAX) data = c.toDataURL('image/webp', 0.5); // a busy picture, leaned on harder
        if (data.length > THUMB_MAX) throw new Error('too big');
        done({ thumb: data, thumbFor: url, thumbPx: THUMB_PX });
      } catch { failed(); } finally { try { bmp && bmp.close(); } catch {} }
    })();
  }

  // A profile that came back EMPTY is usually not proof there's no kind 0.
  // A feed holds a couple of dozen relay subscriptions open, relays cap what
  // one connection may ask at once, and a batch of a dozen pubkeys routinely
  // comes back with seven — the rest aren't missing, they're crowded out.
  // Trusting that silence for ten minutes is what left real accounts wearing
  // a punk and an npub. So a miss is retried soon and backs off only if it
  // keeps missing: fifteen seconds, then half a minute, then a minute, up to
  // the ten minutes that's right for someone who genuinely has no profile.
  const EMPTY_RETRY = 10 * 60_000;
  const emptyRetry = (p) => Math.min(15_000 * Math.pow(2, Math.max(0, (p && p.miss) || 1) - 1), EMPTY_RETRY);
  function profileOf(pk) {
    warmProfiles();
    const cur = profiles.get(pk);
    if (cur !== undefined && (cur === null
      || Date.now() - (cur.t || 0) < (!cur.name && !cur.picture ? emptyRetry(cur) : PROFILE_TTL))) return cur;
    profiles.set(pk, cur || null); // null = loading, no fallback art yet
    wantProfile(pk);
    return cur || null;
  }

  // Profiles are asked for in BATCHES.
  //
  // One REQ per pubkey was the old shape, and it looked fine until a feed
  // painted eighty rows at once: eighty REQs in the same breath, against
  // relays that cap how many a connection may have open. Most were refused,
  // the five-second timeout expired, and an empty answer was remembered for
  // ten minutes — which is the punk-and-a-shortened-npub row. Measured
  // against this wallet's own feed, 131 of the 133 people on screen had a
  // kind 0 sitting on relays we were already connected to.
  const PROF_BATCH = 200;
  // Relays that exist to index profiles rather than to carry conversation.
  // We don't read notes from these, so they never appear in the batch above —
  // but they are the ones most likely to hold the kind 0 of someone whose
  // own relays we can't reach.
  const PROFILE_INDEX_RELAYS = ['wss://purplepag.es', 'wss://user.kindpag.es', 'wss://relay.nostr.band'];
  let profQueue = new Set(), profTimer = null, profInFlight = new Set();
  function wantProfile(pk) {
    if (!pk || profQueue.has(pk) || profInFlight.has(pk)) return;
    profQueue.add(pk);
    if (profTimer) return;
    // a short beat, so one paint's worth of rows becomes one request
    profTimer = setTimeout(() => { profTimer = null; const b = [...profQueue]; profQueue = new Set(); fetchProfiles(b).catch(() => {}); }, 250);
  }

  function applyProfile(pk, ev) {
    let m = null;
    try { m = JSON.parse(ev.content); } catch { m = null; }
    const p = m ? {
      name: m.display_name || m.name || null,
      picture: m.picture || null,
      nip05: m.nip05 || null,
      lud16: typeof m.lud16 === 'string' ? m.lud16.trim() : null,
      // The batch downloaded this person's WHOLE kind 0 to get their name.
      // Keeping the bio and the banner costs one more field each and is the
      // difference between a profile page that paints and one that jumps
      // when the fetch lands a second later. 1000 chars is what the page
      // renders anyway.
      about: typeof m.about === 'string' ? m.about.slice(0, 1000) : null,
      banner: typeof m.banner === 'string' ? m.banner.slice(0, 400) : null,
    } : null;
    // An empty answer must never clobber a remembered face with a punk: keep
    // what we had and just refresh the clock.
    const prev = profiles.get(pk);
    const entry = keepThumb(pk, p ? { ...p, t: Date.now(), miss: 0 } : { ...(prev || {}), t: Date.now() });
    profiles.set(pk, entry);
    persistProfile(pk, entry);
    preloadPicture(entry);
  }

  async function fetchProfiles(pks) {
    for (const pk of pks) profInFlight.add(pk);
    try {
      const found = new Set();
      for (let i = 0; i < pks.length; i += PROF_BATCH) {
        const slice = pks.slice(i, i + PROF_BATCH);
        const evs = await queryOn(zapRelays(), { kinds: [0], authors: slice }, 5000).catch(() => []);
        const newest = new Map();
        for (const ev of evs || []) {
          const c = newest.get(ev.pubkey);
          if (!c || ev.created_at > c.created_at) newest.set(ev.pubkey, ev);
        }
        for (const [pk, ev] of newest) { applyProfile(pk, ev); found.add(pk); }
        // paint what this batch found before going after the stragglers —
        // the outbox fallback below can take seconds, and there's no reason
        // for a face we already have to wait behind one we don't
        if (newest.size) scheduleRepaint();
      }
      // Whoever our relays have never heard of: ask the relays they publish
      // to. Same outbox plan the feed uses, so it costs the lists we already
      // have rather than a round trip each — plus the relays whose whole job
      // is holding kind 0s, which we deliberately don't read notes from and
      // so never ask in the batch above.
      const left = pks.filter((pk) => !found.has(pk));
      if (left.length) {
        const idx = await queryOn(PROFILE_INDEX_RELAYS, { kinds: [0], authors: left }, 5000).catch(() => []);
        const idxNewest = new Map();
        for (const ev of idx || []) {
          const c = idxNewest.get(ev.pubkey);
          if (!c || ev.created_at > c.created_at) idxNewest.set(ev.pubkey, ev);
        }
        for (const [pk, ev] of idxNewest) { applyProfile(pk, ev); found.add(pk); }
        if (idxNewest.size) scheduleRepaint();
      }
      const stillLeft = pks.filter((pk) => !found.has(pk));
      if (stillLeft.length) {
        const left = stillLeft;
        await fetchRelayLists(left);
        await Promise.all(outboxPlan(left).map(async ({ relays, authors }) => {
          const evs = await queryOn(relays, { kinds: [0], authors }, 5000).catch(() => []);
          const newest = new Map();
          for (const ev of evs || []) {
            const c = newest.get(ev.pubkey);
            if (!c || ev.created_at > c.created_at) newest.set(ev.pubkey, ev);
          }
          for (const [pk, ev] of newest) { applyProfile(pk, ev); found.add(pk); }
        }));
      }
      // nobody has one: mark the clock so it's retried in minutes, not asked
      // again on every paint
      for (const pk of pks) {
        if (found.has(pk)) continue;
        const prev = profiles.get(pk);
        profiles.set(pk, { ...(prev || {}), t: Date.now(), miss: ((prev && prev.miss) || 0) + 1 });
      }
      scheduleRepaint();
    } finally {
      for (const pk of pks) profInFlight.delete(pk);
    }
  }
  const displayName = (pk) => {
    const p = profileOf(pk);
    if (p && p.name) return p.name;
    const npub = npubOf(pk);
    return npub ? npub.slice(0, 12) : pk.slice(0, 12);
  };

  // Community wraps decrypt with real secp256k1 work (NIP-44), and a relay
  // backlog delivers hundreds at once. Decrypting them inline in the
  // subscription callbacks blocked the main thread in one burst on boot — the
  // stutter felt when dragging the balance carousel right after a refresh.
  // Queue the decrypt work and run it time-sliced: ~8ms of work, then yield so
  // input and paint get a turn. Chat catches up a few frames later; the wallet
  // stays responsive. (Same pattern the DM inbox drain already uses.)
  // Open one community wrap off the main thread when the crypto worker is
  // up (the decrypt + seal verify per wrap is the remaining boot secp256k1
  // the profiler pinned); the time-sliced queue below stays as the fallback,
  // so a dead worker only changes where the crypto runs, never whether chat
  // catches up. The stream conversation key is group material every member
  // derives — no secret crosses the thread boundary.
  function openWrapBg(wrap, stream, cb) {
    const job = openWrapsOffthread([wrap], stream.convKey);
    if (!job) { enqueueRoomWork(() => cb(openWrap(wrap, stream))); return; }
    job.then((r) => {
      if (r) cb(r[0]);
      else enqueueRoomWork(() => cb(openWrap(wrap, stream))); // worker died mid-job
    });
  }

  const roomWork = [];
  let roomWorking = false;
  function enqueueRoomWork(fn) {
    roomWork.push(fn);
    if (roomWorking) return;
    roomWorking = true;
    (async () => {
      try {
        let t0 = performance.now();
        while (roomWork.length) {
          try { roomWork.shift()(); } catch {}
          if (performance.now() - t0 > 8) { await new Promise((r) => setTimeout(r)); t0 = performance.now(); }
        }
      } finally { roomWorking = false; }
    })();
  }

  // ---- community rooms ----------------------------------------------------

  // subscribe:false builds the room from LOCAL CACHE only — no relay
  // subscription, so none of the gift-wrap verify/decrypt (real secp256k1)
  // runs. That's the boot default: the home screen and its unread dot read
  // the last-known cached messages, and the heavy live backfill waits until
  // the user actually opens Chat (homeView/room view pass subscribe:true).
  function ensureRoom(jm, { subscribe = true } = {}) {
    let room = rooms.get(jm.community_id);
    if (room) { if (subscribe) subscribeRoom(room); return room; }
    const root = hexToBytes(jm.community_root);
    room = {
      jm,
      control: controlKey(root, jm.community_id, jm.root_epoch || EPOCH),
      guestbook: guestbookKey(root, jm.community_id, jm.root_epoch || EPOCH),
      chStream: (id) => channelKey(root, id, EPOCH),
      folded: null,
      controlEntries: [],
      guestEntries: [],
      members: new Map(),
      byChannel: new Map(),
      edits: new Map(),
      deletes: new Set(),
      reactions: new Map(),
      presence: new Map(), // pubkey -> ms of their last beat (this session only)
      typing: new Map(), // pubkey -> { ch, t }
      subbed: new Set(),
      subscribed: false,
      relays: jm.relays && jm.relays.length ? jm.relays : DM_RELAYS,
    };
    rooms.set(jm.community_id, room);

    const refold = () => { room.folded = foldControl(room.controlEntries, { ownerHex: jm.owner, cid: jm.community_id }); };
    const refoldGuestbook = () => {
      room.members = foldGuestbook(room.guestEntries, { nowMs: Date.now(), banned: room.folded?.banned });
      for (const [, msgs] of room.byChannel)
        for (const { rumor, author } of msgs.values()) {
          const tms = eventMs(rumor);
          if (tms) observeAuthor(room.members, author, tms);
        }
    };
    // The replay of stored wraps arrives one event at a time, and folding
    // after every wrap paints each intermediate state: a superseded ban-list
    // version blinks members' messages out until the newest version lands,
    // and the member count creeps upward as joins stream in. Fold once per
    // burst instead — a short quiet gap ends the burst — so the page goes
    // from cache straight to the settled state.
    let foldTimer = 0;
    room.scheduleFold = () => {
      clearTimeout(foldTimer);
      foldTimer = setTimeout(() => {
        refold();
        refoldGuestbook();
        // remember the settled count — next session's list paints it
        // immediately instead of "encrypted" flipping to a number
        const s = st();
        (s.memberCounts ||= {})[jm.community_id] =
          [...room.members.values()].filter((m) => m.state === 'join').length;
        save(s);
        scheduleRepaint();
      }, 250);
    };

    // warm from local cache so the page (and the unread dot) paint before —
    // and without needing — any relay subscription
    const cached = st().cache;
    for (const c of jm.channels || [])
      for (const m of cached[c.id] || []) {
        const msgs = room.byChannel.get(c.id) || room.byChannel.set(c.id, new Map()).get(c.id);
        if (!msgs.has(m.rumor.id)) msgs.set(m.rumor.id, m);
      }
    bumpMsgRev();
    if (subscribe) subscribeRoom(room);
    return room;
  }

  // Open the relay subscriptions for a room — the heavy path (gift-wrap
  // verify + decrypt). Deferred until Chat is opened; idempotent.
  function subscribeRoom(room) {
    if (room.subscribed) return;
    room.subscribed = true;
    const scheduleFold = room.scheduleFold;
    allUnsubs.push(
      subscribeOn(room.relays, { kinds: [1059], authors: [room.control.pk], limit: 500 }, (wrap) => {
        if (seenWraps.has(wrap.id)) return;
        seenWraps.add(wrap.id);
        openWrapBg(wrap, room.control, (opened) => {
          if (!opened || opened.rumor.kind !== 3308) return;
          room.controlEntries.push(opened);
          scheduleFold();
        });
      }),
      subscribeOn(room.relays, { kinds: [1059], authors: [room.guestbook.pk], limit: 500 }, (wrap) => {
        if (seenWraps.has(wrap.id)) return;
        seenWraps.add(wrap.id);
        openWrapBg(wrap, room.guestbook, (opened) => {
          if (!opened) return;
          room.guestEntries.push(opened);
          scheduleFold();
        });
      })
    );
    for (const c of room.jm.channels || []) subChannel(room, c.id);
  }

  function subChannel(room, id) {
    if (room.subbed.has(id)) return;
    room.subbed.add(id);
    // derive the stream key once per channel, not once per wrap — groupKey
    // does an hkdf + ECDH each call, real curve work on a 200-wrap backfill
    const stream = room.chStream(id);
    allUnsubs.push(subscribeOn(room.relays, { kinds: [1059, 21059], authors: [stream.pk], limit: 200 }, (wrap) => {
      if (seenWraps.has(wrap.id)) return;
      seenWraps.add(wrap.id);
      openWrapBg(wrap, stream, (opened) => {
        if (!opened) return;
        onChat(room, id, opened);
      });
    }));
  }

  function onChat(room, channelId, { rumor, author }) {
    const tag = (k) => rumor.tags?.find((x) => x[0] === k);
    // CORD-03 §3: the rumor must commit to the channel/epoch that decrypted it
    if (tag('channel')?.[1] !== channelId || tag('epoch')?.[1] !== String(EPOCH)) return;
    if (room.folded && room.folded.banned.has(author)) return;
    if (rumor.kind === PRESENCE || rumor.kind === TYPING) {
      // Dated by the beat itself, never by arrival. Relays hand back stored
      // beats when we subscribe, and treating those as "just now" would light
      // up the whole member list as online. Clamped to now so a fast clock
      // can't hold someone online forever.
      const ts = Math.min(Date.now(), eventMs(rumor) || rumor.created_at * 1000);
      if (ts > (room.presence.get(author) || 0)) room.presence.set(author, ts);
      if (rumor.kind === TYPING && Date.now() - ts < TYPING_MS) {
        room.typing.set(author, { ch: channelId, t: ts });
        setTimeout(scheduleRepaint, TYPING_MS + 100); // clear itself when it lapses
      }
      scheduleRepaint();
      return;
    }
    if (rumor.kind === 9) {
      const msgs = room.byChannel.get(channelId) || room.byChannel.set(channelId, new Map()).get(channelId);
      msgs.set(rumor.id, { rumor, author });
      bumpMsgRev();
      room.typing.delete(author); // the message itself ends the "typing…"
    } else if (rumor.kind === 5) {
      for (const e of rumor.tags.filter((x) => x[0] === 'e')) {
        const m = room.byChannel.get(channelId)?.get(e[1]);
        if (!m || m.author === author) room.deletes.add(e[1]);
      }
    } else if (rumor.kind === 3302) {
      const target = tag('e')?.[1];
      if (target) {
        const cur = room.edits.get(target);
        if (!cur || eventMs(rumor) > eventMs(cur.rumor)) room.edits.set(target, { rumor, author });
      }
    } else if (rumor.kind === 7) {
      const target = tag('e')?.[1];
      if (target) {
        const r = room.reactions.get(target) || room.reactions.set(target, new Map()).get(target);
        r.set(author, rumor.content);
      }
    }
    const tms = eventMs(rumor);
    if (tms) observeAuthor(room.members, author, tms);
    scheduleRepaint();
  }

  const roomChannels = (room) => {
    if (room.folded && room.folded.channels.size)
      return [...room.folded.channels.entries()].map(([id, c]) => ({ id, name: c.name }));
    return room.jm.channels || [];
  };

  function persistCache(room) {
    const s = st();
    for (const [chId, msgs] of room.byChannel) {
      // Pending entries stay out of the cache: unconfirmed means the relay
      // never took it, and a reload would resurrect it dimmed forever.
      s.cache[chId] = [...msgs.values()]
        .filter((m) => !room.deletes.has(m.rumor.id) && !m.pending)
        .sort((a, b) => eventMs(a.rumor) - eventMs(b.rumor))
        .slice(-CACHE_MAX);
    }
    save(s);
  }

  async function ensureJoined(room, id) {
    const s = st();
    const j = (s.joined[room.jm.community_id] ||= {});
    if (j[id.pubkey]) return;
    const { created_at, ms } = msTags(Date.now());
    const tags = [ms];
    if (room.jm.invitedBy) tags.push(['invite', room.jm.invitedBy, room.jm.inviteLabel || '']);
    const wrap = await wrapRumor({ kind: 3306, pubkey: id.pubkey, content: 'join', tags, created_at }, id.signer, room.guestbook);
    publishOn(room.relays, wrap);
    j[id.pubkey] = true;
    save(s);
  }

  // ---- drafts -------------------------------------------------------------
  // Half-typed text survives navigation and reloads: one draft per
  // conversation ('dm:<pk>' / 'ch:<channelId>'), kept in feature state.
  // The session map is authoritative while the app runs; persistence rides a
  // debounce so typing doesn't hammer storage.
  const sessionDrafts = new Map();
  let draftPersist = 0;
  const POST_DRAFT = 'post'; // the profile page's new-post composer
  const draftFor = (key) =>
    (sessionDrafts.has(key) ? sessionDrafts.get(key) : (st().drafts || {})[key] || '');
  function setDraft(key, text) {
    sessionDrafts.set(key, text);
    clearTimeout(draftPersist);
    draftPersist = setTimeout(() => {
      const s = st();
      s.drafts ||= {};
      for (const [k, v] of sessionDrafts) { if (v) s.drafts[k] = v; else delete s.drafts[k]; }
      save(s);
    }, 800);
  }

  // The morph never rewrites a focused field's value (it would fight the user
  // mid-keystroke), and the composer is focused at the moment you send — so
  // clearing the draft alone leaves the sent text sitting in the input.
  // Clear the live element too.
  function clearDraft(key) {
    setDraft(key, '');
    const inp = document.getElementById('msg-draft');
    if (inp) inp.value = '';
  }

  async function sendMessage(room, chId) {
    const text = draftFor('ch:' + chId).trim();
    if (!text) return;
    const id = await identity();
    if (!id) { noIdToast(); return; }
    // The rumor id is a plain hash, so the message can be on screen before
    // any signing, encryption or network runs. The pending flag never shows —
    // it only keeps unconfirmed messages out of the cache and marks what to
    // withdraw if signing fails.
    const { created_at, ms } = msTags(Date.now());
    // an armed reply context e-tags the quoted message (rendered as a quote
    // by replyQuote on every device that has the original)
    const replyTo = ui.msgReplyTo && room.byChannel.get(chId)?.has(ui.msgReplyTo) ? ui.msgReplyTo : null;
    ui.msgReplyTo = null;
    const rumor = rumorWithId({
      kind: 9, pubkey: id.pubkey, content: text,
      tags: [['channel', chId], ['epoch', String(EPOCH)], ...(replyTo ? [['e', replyTo]] : []), ms], created_at,
    });
    const msgs = room.byChannel.get(chId) || room.byChannel.set(chId, new Map()).get(chId);
    const entry = { rumor, author: id.pubkey, pending: true };
    msgs.set(rumor.id, entry);
    clearDraft('ch:' + chId);
    ui.msgStick = true;
    render();
    try {
      const wrap = await wrapRumor(rumor, id.signer, room.chStream(chId));
      seenWraps.add(wrap.id); // our own echo has nothing to add
      const ok = await publishOn(room.relays, wrap);
      if (!ok) { toast(t('msgSendFailed')); return; }
      delete entry.pending;
      ensureJoined(room, id).catch(() => {});
      persistCache(room);
    } catch (e) {
      // Signing or wrapping failed — the message never existed on the wire,
      // so it leaves the screen rather than sit there looking sent.
      msgs.delete(rumor.id);
      toast(e.message || String(e));
      render();
    }
  }

  // A reaction is a kind-7 rumor on the channel stream — same envelope as a
  // message, content = the emoji. One reaction per author per message (the
  // fold keeps the latest), so picking a different emoji replaces yours;
  // tapping an existing chip joins that vote. Optimistic like sendMessage:
  // the chip appears immediately, the wire catches up.
  const REACT_EMOJIS = ['👍', '❤️', '😂', '🔥', '🎉', '🙏'];
  async function sendReaction(room, chId, m, emoji) {
    const id = await identity();
    if (!id) { noIdToast(); return; }
    ui.msgSheet = null;
    const { created_at, ms } = msTags(Date.now());
    const rumor = rumorWithId({
      kind: 7, pubkey: id.pubkey, content: emoji,
      tags: [['channel', chId], ['epoch', String(EPOCH)], ['e', m.rumor.id], ['k', '9'], ms], created_at,
    });
    const r = room.reactions.get(m.rumor.id) || room.reactions.set(m.rumor.id, new Map()).get(m.rumor.id);
    const prev = r.get(id.pubkey);
    r.set(id.pubkey, emoji);
    render();
    try {
      const wrap = await wrapRumor(rumor, id.signer, room.chStream(chId));
      seenWraps.add(wrap.id); // our own echo has nothing to add
      const ok = await publishOn(room.relays, wrap);
      if (!ok) toast(t('msgSendFailed'));
    } catch (e) {
      // never went out — put back whatever stood before
      if (prev) r.set(id.pubkey, prev); else r.delete(id.pubkey);
      toast(e.message || String(e));
      render();
    }
  }

  // The displayed text of a message after its edit fold, trimmed to one line.
  function msgSnippet(room, m, max = 90) {
    const edit = room.edits.get(m.rumor.id);
    const text = edit && edit.author === m.author ? edit.rumor.content : m.rumor.content;
    const one = String(text || '').replace(/\s+/g, ' ').trim();
    return one.length > max ? one.slice(0, max - 1) + '…' : one;
  }

  // A kind-9 that e-tags another message is a REPLY — render the quoted
  // context above its text, Telegram-style. Quotes of deleted (or not-yet-
  // loaded) messages stay silent rather than resurrect them.
  function replyQuote(room, chId, m) {
    const replyId = (m.rumor.tags || []).find((x) => x[0] === 'e')?.[1];
    if (!replyId || room.deletes.has(replyId)) return null;
    const src = room.byChannel.get(chId)?.get(replyId);
    if (!src) return null;
    return h('div', { class: 'chat-quote' },
      h('span', { class: 'chat-quote-name' }, displayName(src.author)),
      h('span', { class: 'chat-quote-text' }, msgSnippet(room, src)));
  }

  // Telegram-style message action sheet: quick reactions on top, then the
  // actions this message supports. Opened by a tap on the bubble.
  function messageSheet(room, chId) {
    const m = room.byChannel.get(chId)?.get(ui.msgSheet);
    if (!m) { ui.msgSheet = null; return null; }
    const my = myPubkeys();
    const mine = my.includes(m.author);
    const reacts = room.reactions.get(m.rumor.id);
    const myReact = reacts && my.map((pk) => reacts.get(pk)).find(Boolean);
    const close = () => { ui.msgSheet = null; render(); };
    const item = (icon, label, onClick) => h('button', { class: 'msg-sheet-item', onClick },
      h('span', { class: 'msg-sheet-ico' }, icon), label);
    return h('div', {
      class: 'confirm-pop-backdrop',
      onClick: (e) => { if (e.target === e.currentTarget) close(); },
    },
      h('div', { class: 'card col msg-sheet' },
        h('div', { class: 'msg-sheet-emojis' },
          REACT_EMOJIS.map((e2) => h('button', {
            class: e2 === myReact ? 'on' : '',
            onClick: () => { close(); sendReaction(room, chId, m, e2); },
          }, e2))),
        item('↩', t('msgReply'), () => {
          ui.msgReplyTo = m.rumor.id;
          close();
          setTimeout(() => document.getElementById('msg-draft')?.focus(), 50);
        }),
        !mine && canZapPk(m.author) ? item('⚡', t('msgZap'), () => { close(); zapMessage(m.author, m.rumor.id); }) : null,
        item('⧉', t('copy'), async () => {
          try { await navigator.clipboard.writeText(msgSnippet(room, m, 100000)); toast(t('copied')); } catch {}
          close();
        }),
        mine ? item('✕', t('msgDelete'), () => { close(); deleteMessage(room, chId, m); }) : null));
  }

  // The composer's "replying to" context bar, with its way out.
  function replyBar(room, chId) {
    const m = ui.msgReplyTo && room.byChannel.get(chId)?.get(ui.msgReplyTo);
    if (!m) { ui.msgReplyTo = null; return null; }
    return h('div', { class: 'reply-bar' },
      h('div', { class: 'col grow', style: 'gap:1px;min-width:0' },
        h('span', { class: 'small', style: 'font-weight:650' }, '↩ ', displayName(m.author)),
        h('span', { class: 'small muted chat-quote-text' }, msgSnippet(room, m))),
      h('button', { class: 'chat-del', style: 'position:static;display:flex;flex-shrink:0', onClick: () => { ui.msgReplyTo = null; render(); } }, '×'));
  }

  async function deleteMessage(room, chId, m) {
    const id = await identity();
    if (!id || id.pubkey !== m.author) return;
    const { created_at, ms } = msTags(Date.now());
    const rumor = {
      kind: 5, pubkey: id.pubkey, content: '',
      tags: [['channel', chId], ['epoch', String(EPOCH)], ['e', m.rumor.id], ['k', '9'], ms], created_at,
    };
    const wrap = await wrapRumor(rumor, id.signer, room.chStream(chId));
    room.deletes.add(m.rumor.id);
    render();
    publishOn(room.relays, wrap);
    persistCache(room);
  }

  // ---- founding a community (CORD-02 genesis) -----------------------------

  async function createCommunity(name) {
    const id = await identity();
    if (!id) { noIdToast(); return; }
    name = name.trim().slice(0, 64);
    if (!name) return;
    const ownerSalt = bytesToHex(crypto.getRandomValues(new Uint8Array(32)));
    const rootBytes = crypto.getRandomValues(new Uint8Array(32));
    const cid = communityId(id.pubkey, ownerSalt);
    const generalId = bytesToHex(crypto.getRandomValues(new Uint8Array(32)));
    const control = controlKey(rootBytes, cid, 0);
    const guestbook = guestbookKey(rootBytes, cid, 0);
    const now = Date.now();
    const relays = DM_RELAYS;
    const meta = { ...makeEdition({ vsk: 0, eid: cid, version: 1, content: JSON.stringify({ name, relays }) }, now), pubkey: id.pubkey };
    const general = { ...makeEdition({ vsk: 2, eid: generalId, version: 1, content: JSON.stringify({ name: 'general', private: false }) }, now + 1), pubkey: id.pubkey };
    const { created_at, ms } = msTags(now + 2);
    const join = { kind: 3306, pubkey: id.pubkey, content: 'join', tags: [ms], created_at };
    const events = [
      await wrapRumor(meta, id.signer, control, { plaintext: true }),
      await wrapRumor(general, id.signer, control, { plaintext: true }),
      await wrapRumor(join, id.signer, guestbook),
    ];
    for (const e of events) await publishOn(relays, e);
    const jm = {
      community_id: cid, owner: id.pubkey, owner_salt: ownerSalt,
      community_root: bytesToHex(rootBytes), root_epoch: 0,
      channels: [{ id: generalId, name: 'general' }], relays, name,
      added_at: Date.now(),
    };
    const s = st();
    s.communities.push(jm);
    (s.joined[cid] ||= {})[id.pubkey] = true;
    save(s);
    publishLists();
    registerPush().catch(() => {});
    ensureRoom(jm);
    ui.msgView = 'room';
    ui.msgCommunity = cid;
    ui.msgChannel = null;
    ui.msgNewName = '';
    ui.msgHomePanel = null;
    render();
  }

  // A new channel is one owner-signed ChannelMetadata edition (CORD-03 §2);
  // the control-plane fold picks it up and every member's switcher grows.
  async function createChannel(room, name) {
    name = (name || '').trim().slice(0, 64);
    if (!name) return;
    const id = await identity();
    if (!id || id.pubkey !== room.jm.owner) { toast(t('msgOwnerOnly')); return; }
    const chId = bytesToHex(crypto.getRandomValues(new Uint8Array(32)));
    const edition = {
      ...makeEdition({ vsk: 2, eid: chId, version: 1, content: JSON.stringify({ name: name.replace(/^#/, ''), private: false }) }, Date.now()),
      pubkey: id.pubkey,
    };
    const wrap = await wrapRumor(edition, id.signer, room.control, { plaintext: true });
    const ok = await publishOn(room.relays, wrap);
    if (!ok) { toast(t('msgSendFailed')); return; }
    ui.msgNewChannel = '';
    ui.msgChannelPanel = false; // the field has done its job — put it away
    toast('#' + name.replace(/^#/, ''));
  }

  // ---- invites ------------------------------------------------------------

  function bundleFor(room, creatorPk) {
    return {
      community_id: room.jm.community_id, owner: room.jm.owner, owner_salt: room.jm.owner_salt,
      community_root: room.jm.community_root, root_epoch: room.jm.root_epoch || 0,
      channels: roomChannels(room).map((c) => ({ id: c.id, name: c.name })),
      relays: room.relays, name: (room.folded?.metadata?.name) || room.jm.name,
      creator_npub: creatorPk,
    };
  }

  async function mintInviteLink(room) {
    const id = await identity();
    if (!id) { noIdToast(); return null; }
    const s = st();
    const existing = s.invites[room.jm.community_id];
    if (existing) return existing.url;
    const linkSk = generateSecretKey();
    const token = crypto.getRandomValues(new Uint8Array(16));
    const evt = makeInviteBundleEvent(linkSk, bundleFor(room, id.pubkey), token);
    const ok = await publishOn(room.relays, evt);
    if (!ok) { toast(t('msgSendFailed')); return null; }
    const url = makeInviteLink(APP_BASE, getPublicKey(linkSk), room.relays, token);
    s.invites[room.jm.community_id] = { sk: bytesToHex(linkSk), token: bytesToHex(token), url, created_at: Math.floor(Date.now() / 1000) };
    save(s);
    publishLists();
    return url;
  }

  async function sendDirectInvite(room, input) {
    const peer = parseNostrPubkey(input);
    if (!peer) { toast(t('msgBadNpub')); return; }
    const id = await identity();
    if (!id) { noIdToast(); return; }
    if (!(id.signer instanceof Uint8Array) && !id.signer.encryptTo) { toast(t('msgSignerNoDm')); return; }
    const rumor = {
      kind: 3313, pubkey: id.pubkey,
      content: JSON.stringify(bundleFor(room, id.pubkey)),
      tags: [], created_at: Math.floor(Date.now() / 1000),
    };
    const wrap = await wrapDM(id.signer, peer, rumor, [['k', '3313']]);
    const inbox = (await fetchInboxRelays(peer)).slice(0, 4);
    const ok = await publishOn([...new Set([...inbox, ...DM_RELAYS])], wrap);
    toast(ok ? t('msgInviteSent') : t('msgSendFailed'));
  }

  function acceptBundle(b, { invitedBy, inviteLabel } = {}) {
    const s = st();
    if (!communityById(b.community_id)) {
      const jm = {
        community_id: b.community_id, owner: b.owner, owner_salt: b.owner_salt,
        community_root: b.community_root, root_epoch: b.root_epoch || 0,
        channels: (b.channels || []).map((c) => ({ id: c.id, name: c.name })),
        relays: (b.relays || []).slice(0, 5), name: b.name || 'community',
        invitedBy, inviteLabel, added_at: Date.now(),
      };
      s.communities.push(jm);
      save(s);
      publishLists();
    }
    const room = ensureRoom(communityById(b.community_id));
    identity().then((id) => id && ensureJoined(room, id)).catch(() => {});
    registerPush().catch(() => {});
    ui.msgView = 'room';
    ui.msgCommunity = b.community_id;
    ui.msgChannel = null;
    ui.msgHomePanel = null;
    pendingLink = null;
    render();
  }

  // A link invite being previewed (pasted or arrived via /invite/<naddr>#…).
  let pendingLink = null; // { parsed, state: 'loading'|'ready'|'error', bundle?, error? }

  async function loadLinkInvite(parsed) {
    pendingLink = { parsed, state: 'loading' };
    scheduleRepaint();
    const relays = [...new Set([...(parsed.relays || []), ...DM_RELAYS])];
    const evts = await queryOn(relays, { kinds: [33301], authors: [parsed.signerPk] }, 4000);
    const newest = evts.sort((a, b) => b.created_at - a.created_at)[0];
    const b = newest && openInviteBundle(newest, parsed.token);
    if (!b) pendingLink = { parsed, state: 'error', error: t('msgInviteNotFound') };
    else if (b.revoked) pendingLink = { parsed, state: 'error', error: t('msgInviteRevoked') };
    else if (b.expired) pendingLink = { parsed, state: 'error', error: t('msgInviteExpired') };
    else pendingLink = { parsed, state: 'ready', bundle: b };
    scheduleRepaint();
  }

  function joinFromText(text) {
    const parsed = parseInviteLink(text);
    if (!parsed) { toast(t('msgBadInvite')); return; }
    ui.msgJoinText = '';
    ui.msgHomePanel = null;
    loadLinkInvite(parsed);
  }

  // An invite link opened in the browser lands here before the wallet exists.
  const urlInvite = typeof location !== 'undefined' ? parseInviteLink(location.href) : null;
  if (urlInvite) { try { history.replaceState(null, '', '/'); } catch {} }

  // coinos.io/<username> parity: a claimed name (or a raw npub / hex key) as
  // the whole URL path deep-links to that profile. Real files never reach the
  // app — the server tries them first — and gift/invite links carry their own
  // multi-segment paths, which this single-segment shape can't match. The
  // path is consumed immediately so a reload lands on the wallet as usual.
  const urlProfile = (() => {
    if (typeof location === 'undefined' || urlInvite) return null;
    const m = location.pathname.match(/^\/([A-Za-z0-9._-]{1,64})\/?$/);
    // reserved app routes are never usernames — /chat is the public
    // community page (app.js routes it), and eating it here rewrote the URL
    // to / before that route ever saw it
    if (m && ['chat'].includes(m[1])) return null;
    return m ? m[1] : null;
  })();
  if (urlProfile) { try { history.replaceState(null, '', '/'); } catch {} }

  // Resolve and open right away — not in init(), which only runs once a
  // wallet opens (and would replay on every wallet born in this tab). For a
  // visitor with no wallet the profile renders as a truly public page over
  // the unlock screen (ui.pubProf gates that surface) — nostr profiles are
  // public data, and Back lands on the app's own front door.
  if (urlProfile) {
    // Claim the first paint synchronously: these are set before the boot
    // render, so the visitor sees a profile shell from the first frame —
    // never a flash of the front door while the registrar lookup runs.
    ui.pubProf = true;
    ui.pubProfPending = urlProfile;
    (async () => {
      await new Promise((r) => setTimeout(r, 0)); // never render mid-boot
      let pk = parseNostrPubkey(urlProfile);
      if (!pk && /^[a-z0-9._-]{1,30}$/i.test(urlProfile)) {
        // same registrar + domain rule the names feature uses
        const domain = getNetwork() === 'mutinynet' ? 'staging.coinos.io' : 'coinos.io';
        const name = urlProfile.toLowerCase();
        try {
          const j = await fetch(`https://names.coinos.io/.well-known/nostr.json?name=${encodeURIComponent(name)}&domain=${domain}`)
            .then((r) => r.json());
          pk = (j.names || {})[name] || null;
        } catch {}
        // The username is real display material: seed the light cache (stale,
        // t:0, so the kind 0 still gets fetched) and the page paints the name
        // immediately instead of an npub prefix. `loading` keeps the avatar a
        // quiet circle meanwhile — punk art must mean "has no picture", never
        // "picture not here yet", or the wrong face flashes before the real
        // one loads.
        if (pk && /^[0-9a-f]{64}$/.test(pk)) {
          warmProfiles();
          if (!profiles.has(pk)) profiles.set(pk, { name, addr: `${name}@${domain}`, t: 0, loading: true });
        }
      }
      if (pk && /^[0-9a-f]{64}$/.test(pk)) {
        // hold the pinned nav key across this render: the profile replaces
        // the shell in place, with no page-slide re-animation
        ui.pubProfHold = true;
        ui.pubProfPending = null;
        if (ui.screen === 'wallet') ui.pubProf = null; // wallet chrome owns it
        openProfile(pk);
        ui.pubProfHold = null;
      } else {
        ui.pubProfPending = null;
        ui.pubProf = null; // unknown name: fall through to the front door
        render();
      }
    })();
  }

  // ---- push notifications -------------------------------------------------
  // The nwcpush notifier watches relays for what it can see without keys:
  // kind-1059 wraps p-tagged at us (DMs, direct invites), zap receipts
  // (payments), and wraps authored by our communities' channel keys (chat).
  // It pushes a typed nudge; the service worker shows a generic notification
  // unless a window is visible. Payment pushes also arrive server-to-server
  // from the names registrar when a lightning-address receive settles.

  const b64ToBytes = (b64) => {
    const pad = '='.repeat((4 - (b64.length % 4)) % 4);
    const raw = atob((b64 + pad).replace(/-/g, '+').replace(/_/g, '/'));
    return Uint8Array.from(raw, (c) => c.charCodeAt(0));
  };

  // What the notifier is allowed to wake us for. Communities are opt-in and
  // off by default: a busy room would otherwise buzz a phone all day for
  // conversations that aren't addressed to anyone in particular.
  function pushWatch() {
    const s = st();
    const on = s.notify;
    const authors = [];
    for (const jm of communities()) {
      if (!on[jm.community_id]) continue;
      const root = hexToBytes(jm.community_root);
      for (const c of (jm.channels || []).slice(0, 8)) authors.push(channelKey(root, c.id, EPOCH).pk);
    }
    // per-category opt-outs travel with the registration so the notifier
    // never sends what the user turned off (a suppressed-but-delivered push
    // would earn Chrome's generic "updated in background" nag instead)
    const reasons = { payment: s.reasons?.payment !== false, dm: s.reasons?.dm !== false };
    // Stamp the network: the same seed makes the same nostr pubkey on mainnet
    // AND staging, so without this the notifier fans a mainnet payment push
    // out to the staging PWA's subscription too — and tapping it opened
    // staging. The notifier now delivers a payment only to registrations on
    // the payment's own network.
    return { ptags: myPubkeys(), authors, reasons, net: getNetwork() };
  }

  const roomNotify = (cid) => !!st().notify[cid];
  async function toggleRoomNotify(cid) {
    const s = st();
    if (s.notify[cid]) delete s.notify[cid]; else s.notify[cid] = true;
    save(s);
    render();
    // The server keeps the watch list, so the change only lands once we
    // re-register. Asking for permission is fair here — they just opted in.
    const ok = await registerPush({ interactive: !!s.notify[cid] });
    if (!ok && s.notify[cid]) {
      const s2 = st();
      delete s2.notify[cid];
      save(s2);
      toast(t('msgPushFailed'));
      render();
    }
  }

  // Settings → Notifications: the master switch for this device plus the
  // per-category choices the registration carries to the notifier.
  function notifyCard() {
    const supported = typeof Notification !== 'undefined'
      && typeof navigator !== 'undefined' && 'serviceWorker' in navigator
      && typeof window !== 'undefined' && 'PushManager' in window;
    const perm = supported ? Notification.permission : 'unsupported';
    const s = st();
    const on = (k) => s.reasons?.[k] !== false;
    const flip = async (k) => {
      const s2 = st();
      s2.reasons = { ...(s2.reasons || {}), [k]: !on(k) };
      save(s2); render();
      const ok = await registerPush({ interactive: true });
      if (!ok) toast(t('msgPushFailed'));
    };
    const rowT = (label, k) => h('div', { class: 'row between' },
      h('span', { class: 'small' }, label),
      h('button', { class: 'btn-sm', onClick: () => flip(k) }, on(k) ? t('nwcOn') : t('nwcOff')));
    return h('div', { class: 'card col', style: 'gap:10px' },
      h('h3', { style: 'margin:0' }, t('notifTitle')),
      !supported
        ? h('div', { class: 'small faint' }, t('nwcNoPush'))
        : perm === 'denied'
          ? h('div', { class: 'notice err' }, t('nwcNotifBlocked'))
          : perm !== 'granted' || !s.push
            ? h('button', { class: 'btn-primary btn-block', onClick: async () => {
                const ok = await registerPush({ interactive: true });
                toast(ok ? t('notifEnabled') : t('msgPushFailed'));
                render();
              } }, t('notifEnable'))
            : h('div', { class: 'small faint' }, t('notifOnDevice')),
      rowT(t('notifPayRecv'), 'payment'),
      rowT(t('notifDm'), 'dm'),
      h('div', { class: 'small faint' }, t('notifChatHint')));
  }

  // Hand the service worker what it needs to tell a friend's DM from a
  // stranger's: our key (only if we actually hold one), who we follow, and the
  // names we already know. See dm-inbox.js for the threat model — a remote
  // signer stores no key here and simply gets unfiltered notifications.
  let inboxAt = 0;
  async function syncInbox({ force = false } = {}) {
    if (!force && Date.now() - inboxAt < 5 * 60_000) return;
    inboxAt = Date.now();
    try {
      const id = await identity();
      if (!id) return;
      const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])],
        { kinds: [3], authors: [id.pubkey] }, 4000);
      const newest = evs.sort((a, b) => b.created_at - a.created_at)[0];
      const follows = newest
        ? [...new Set(newest.tags.filter((x) => x[0] === 'p' && /^[0-9a-f]{64}$/.test(x[1] || '')).map((x) => x[1]))]
        : [];
      const known = [...threads.keys()];
      const names = {};
      for (const pk of [...follows, ...known]) {
        const p = profiles.get(pk);
        if (p && p.name) names[pk] = p.name;
      }
      await saveInbox(wallet._cacheKey(), {
        pubkey: id.pubkey,
        sk: id.signer instanceof Uint8Array ? bytesToHex(id.signer) : null,
        follows, known, names, hasList: !!newest, updated: Date.now(),
      });
    } catch { inboxAt = 0; }
  }

  // The Android wrapper hands us a UnifiedPush endpoint on its launch URL
  // (?up=), because the distributor talks to the app and only the web app
  // knows which pubkeys are worth watching. On a phone without Google Play
  // Services this is the ONLY way to be reached while closed, so it takes
  // precedence over the browser's own push — which there doesn't work at all.
  const UP_KEY = 'coinos-unifiedpush';
  const upEndpoint = () => { try { return localStorage.getItem(UP_KEY) || null; } catch { return null; } };
  (() => {
    try {
      const u = new URLSearchParams(location.search).get('up');
      if (!u) return;
      localStorage.setItem(UP_KEY, u);
      // tidy the URL the way the payment intent does
      history.replaceState(null, '', location.pathname || '/');
    } catch {}
  })();

  // What to tell someone whose phone can't be woken. In a browser that's
  // "your browser has no push service"; inside the UnifiedPush build of the
  // Android app it's about the distributor, because that build IS the push —
  // telling a WebView to go and use Firefox would be nonsense.
  function pushAdvice() {
    const env = hostEnv();
    if (!env || env.app !== 'graphene') return t('nwcNoPushService');
    if (!env.distributors) return t('upNoDistributor');
    if (!env.endpoint) return t('upWaiting', { app: (env.distributor || '').split('.').pop() });
    return t('nwcNoPushService');
  }
  function hostEnv() {
    try {
      const h2 = typeof window !== 'undefined' && window.CoinosHost;
      if (!h2 || typeof h2.env !== 'function') return null;
      return JSON.parse(h2.env());
    } catch { return null; }
  }

  async function registerPush({ interactive = false } = {}) {
    try {
      // A UnifiedPush endpoint needs no permission and no push service: it's
      // a URL the distributor gave the wrapper, and the notifier POSTs to it.
      const up = upEndpoint();
      if (up) {
        const r = await fetch(`${NOTIFIER}/register`, {
          method: 'POST', headers: { 'content-type': 'application/json' },
          body: JSON.stringify({ subscription: { endpoint: up, unifiedpush: true }, notify: pushWatch() }),
        });
        if (!r.ok) return false;
        const s2 = st();
        if (!s2.push || s2.noPushService) { s2.push = true; delete s2.noPushService; save(s2); }
        return true;
      }
      if (typeof Notification === 'undefined' || !('serviceWorker' in navigator) || !('PushManager' in window)) return false;
      if (Notification.permission !== 'granted') {
        if (!interactive) return false;
        if ((await Notification.requestPermission()) !== 'granted') return false;
      }
      const reg = await navigator.serviceWorker.ready;
      const { publicKey } = await (await fetch(`${NOTIFIER}/vapid`)).json();
      const wantKey = b64ToBytes(publicKey);
      let sub = await reg.pushManager.getSubscription();
      // see nwc.js: a Chromium without Google Play Services (GrapheneOS, and
      // any de-Googled Android) has no push service at all, and says so in a
      // way nobody can act on. Remember it so the offer can explain itself.
      const noPushService = (e) => /push service|Registration failed|AbortError|NotSupportedError/i.test((e && (e.message || e.name)) || '');
      // A subscription made against a DIFFERENT VAPID key can never receive a
      // push — the notifier's sends fail with a permanent 403 and it keeps
      // reusing the dead sub, so the device goes silent forever (this is what
      // stranded notifications after the key last rotated). Re-subscribe when
      // the existing sub's server key doesn't match the current one.
      const keyMatches = (s) => {
        try {
          const cur = new Uint8Array(s.options.applicationServerKey || []);
          return cur.length === wantKey.length && cur.every((b, i) => b === wantKey[i]);
        } catch { return false; }
      };
      if (sub && !keyMatches(sub)) { try { await sub.unsubscribe(); } catch {} sub = null; }
      if (!sub) {
        try {
          sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: wantKey });
        } catch (e) {
          if (noPushService(e)) { const s2 = st(); s2.noPushService = true; save(s2); render(); }
          return false;
        }
      }
      { const s2 = st(); if (s2.noPushService) { delete s2.noPushService; save(s2); } }
      const r = await fetch(`${NOTIFIER}/register`, {
        method: 'POST', headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ subscription: sub.toJSON(), notify: pushWatch() }),
      });
      if (!r.ok) return false;
      const s = st();
      if (!s.push) { s.push = true; save(s); }
      return true;
    } catch {
      return false;
    }
  }

  // ---- device sync: Community List (13302) + Invite List (13303) ----------
  // Self-encrypted replaceables (CORD-02 §8 / CORD-05 §4) so memberships and
  // minted link keys follow the user to any device or client. Published under
  // every identity we can encrypt for: the wallet key is the cross-device
  // constant (same seed on every device), the login npub makes the list
  // readable by other Concord clients serving the same identity.

  async function selfCryptors() {
    const out = [];
    if (wallet.nostr && wallet.nostr.sk && wallet.nostr.ck) out.push({
      pk: wallet.nostr.pk,
      sign: async (e) => finalizeEvent(e, wallet.nostr.sk),
      enc: async (txt) => nip44.encrypt(txt, wallet.nostr.ck),
      dec: async (ct) => nip44.decrypt(ct, wallet.nostr.ck),
    });
    const login = hook('nostrLoginIdentity');
    if (login && login.signer && login.signer.encryptSelf) out.push({
      pk: login.pubkey,
      sign: (e) => login.signer.signEvent(e),
      enc: (txt) => login.signer.encryptSelf(txt),
      dec: (ct) => login.signer.decryptSelf(ct),
    });
    return out;
  }

  // Join material subset (never the icon, never link fields). We only run
  // epoch 0 today, so seed and current coincide.
  const jmSubset = (jm) => ({
    community_id: jm.community_id, owner: jm.owner, owner_salt: jm.owner_salt,
    community_root: jm.community_root, root_epoch: jm.root_epoch || 0,
    channels: (jm.channels || []).map((c) => ({ id: c.id, name: c.name })),
    relays: jm.relays, name: jm.name,
  });

  const buildCommunityList = (s) => JSON.stringify({
    entries: s.communities.slice(0, 50).map((jm) => ({
      community_id: jm.community_id, seed: jmSubset(jm), current: jmSubset(jm), added_at: jm.added_at || 0,
    })),
    tombstones: Object.entries(s.tombstones).map(([community_id, removed_at]) => ({ community_id, removed_at })),
  });

  const buildInviteList = (s) => JSON.stringify({
    entries: Object.entries(s.invites).map(([community_id, inv]) => ({
      token: inv.token, signer_sk: inv.sk, community_id, url: inv.url, created_at: inv.created_at || 0,
    })),
    tombstones: [],
  });

  function mergeCommunityList(doc) {
    const s = st();
    let changed = false;
    for (const tb of doc.tombstones || []) {
      if ((tb.removed_at || 0) > (s.tombstones[tb.community_id] || 0)) {
        s.tombstones[tb.community_id] = tb.removed_at;
        changed = true;
      }
    }
    for (const e of (doc.entries || []).slice(0, 50)) {
      const jm = e.current || e.seed;
      if (!jm || jm.community_id !== e.community_id) continue;
      if (jm.community_id === COMMUNITY.community_id) continue; // built-in
      if ((e.added_at || 0) <= (s.tombstones[e.community_id] || 0)) continue; // tombstone wins
      if (s.communities.some((c) => c.community_id === e.community_id)) continue;
      if (communityId(jm.owner, jm.owner_salt) !== jm.community_id) continue; // self-certify before adopting keys
      if (!/^[0-9a-f]{64}$/.test(jm.community_root || '')) continue;
      s.communities.push({ ...jmSubset(jm), added_at: e.added_at || Date.now() });
      changed = true;
    }
    // a tombstone newer than an entry's added_at removes it locally too
    const keep = s.communities.filter((c) => (s.tombstones[c.community_id] || 0) <= (c.added_at || 0));
    if (keep.length !== s.communities.length) { s.communities = keep; changed = true; }
    if (changed) save(s);
    return changed;
  }

  function mergeInviteList(doc) {
    const s = st();
    let changed = false;
    for (const e of doc.entries || []) {
      if (!e.token || !e.community_id || !e.signer_sk) continue;
      if (!s.invites[e.community_id]) {
        s.invites[e.community_id] = { sk: e.signer_sk, token: e.token, url: e.url, created_at: e.created_at };
        changed = true;
      }
    }
    if (changed) save(s);
    return changed;
  }

  async function publishLists() {
    const ids = await selfCryptors();
    const s = st();
    const docs = [[13302, buildCommunityList(s)], [13303, buildInviteList(s)]];
    for (const id of ids)
      for (const [kind, doc] of docs) {
        try {
          const evt = await id.sign({
            kind, content: await id.enc(doc), tags: [], created_at: Math.floor(Date.now() / 1000),
          });
          publishOn(DM_RELAYS, evt);
        } catch {}
      }
  }

  let listsSynced = false;
  async function syncLists() {
    if (listsSynced) return;
    const ids = await selfCryptors();
    if (!ids.length) return;
    listsSynced = true;
    const evs = await queryOn(DM_RELAYS, { kinds: [13302, 13303], authors: ids.map((i) => i.pk) }, 3500);
    let changed = false;
    const remoteDocs = new Set();
    for (const kind of [13302, 13303])
      for (const id of ids) {
        const newest = evs.filter((e) => e.kind === kind && e.pubkey === id.pk).sort((a, b) => b.created_at - a.created_at)[0];
        if (!newest) continue;
        try {
          const raw = await id.dec(newest.content);
          remoteDocs.add(kind + ':' + raw);
          const doc = JSON.parse(raw);
          if (kind === 13302) changed = mergeCommunityList(doc) || changed;
          else changed = mergeInviteList(doc) || changed;
        } catch {}
      }
    if (changed) {
      // cache-only here too — subscription waits for the user to open Chat
      for (const jm of communities()) ensureRoom(jm, { subscribe: ui.chatOpen });
      scheduleRepaint();
    }
    // republish when any identity's copy is missing or stale
    const s = st();
    const current = [[13302, buildCommunityList(s)], [13303, buildInviteList(s)]];
    const anyMissing = ids.length * 2 > remoteDocs.size
      || current.some(([kind, doc]) => !remoteDocs.has(kind + ':' + doc));
    if (anyMissing && (s.communities.length || Object.keys(s.invites).length || Object.keys(s.tombstones).length))
      publishLists();
  }

  async function leaveCommunity(room) {
    const cid = room.jm.community_id;
    const id = await identity();
    const s = st();
    s.tombstones[cid] = Date.now();
    s.communities = s.communities.filter((c) => c.community_id !== cid);
    delete s.joined[cid];
    save(s);
    if (id) {
      const { created_at, ms } = msTags(Date.now());
      wrapRumor({ kind: 3306, pubkey: id.pubkey, content: 'leave', tags: [ms], created_at }, id.signer, room.guestbook)
        .then((w) => publishOn(room.relays, w)).catch(() => {});
    }
    rooms.delete(cid);
    publishLists();
    ui.msgView = 'home';
    ui.msgLeaveArm = false;
    ui.msgInvitePanel = false;
    render();
  }

  // ---- DMs ----------------------------------------------------------------

  const threadOf = (peer) => threads.get(peer) || threads.set(peer, new Map()).get(peer);

  function noteDM(peer, rumor, mine) {
    if (!peer || !rumor.id) return;
    threadOf(peer).set(rumor.id, { rumor, mine });
    bumpMsgRev();
    scheduleRepaint();
  }

  // Wraps nothing could open are NOT consumed. The usual reason is the
  // remote signer losing the race with the relay backfill on a fresh load
  // (the login signer resumes lazily, the stored wraps arrive first), or a
  // single bunker round-trip failing — and dropping the wrap there was how
  // whole stretches of DM history quietly went missing, differently on every
  // device. Keep them and retry as the decryptor set improves; a wrap that
  // never opens (a stranger's wrap that merely p-tags us) falls out after a
  // few full-strength passes.
  const pendingWraps = new Map(); // wrap.id -> { wrap, tries }
  const PENDING_MAX = 800;
  // Full-strength attempts before giving a wrap up. Kept low on purpose: a
  // bunker signer pays two relay round-trips per attempt, and a wrap that a
  // complete decryptor set failed to open twice is essentially never ours.
  const PENDING_TRIES = 3;
  let drainTimer = 0;
  let draining = false;

  function dmDecryptors() {
    const out = [];
    if (wallet.nostr && wallet.nostr.sk) out.push(wallet.nostr.sk);
    const login = hook('nostrLoginIdentity');
    if (login && login.signer && login.signer.decryptFrom) out.push(login.signer);
    return out;
  }
  // A "full-strength" attempt has every key this wallet expects: retries
  // only count against a wrap once the login signer (if one is linked) has
  // actually had its chance — the wallet key alone can never open a wrap
  // sealed to the login npub.
  function decryptorsComplete() {
    const login = hook('nostrLoginIdentity');
    return !login || !!(login.signer && login.signer.decryptFrom);
  }

  // Raw-key unwraps (seed-derived / pasted nsec — the common case) run in
  // the crypto worker: two ECDH ops + a seal verify per wrap is the boot
  // secp256k1 that used to run here. Remote signers can't export their key,
  // so their decryptFrom stays on the main thread, exactly as before.
  async function unwrapDMAny(wrap, d) {
    if (d instanceof Uint8Array) {
      const job = unwrapDMsOffthread([wrap], d);
      if (job) {
        const r = await job;
        if (r) return r[0]; // null here means "not ours", not "worker failed"
      }
    }
    return unwrapDM(wrap, d).catch(() => null);
  }

  async function openInboxWrap(wrap) {
    for (const d of dmDecryptors()) {
      const got = await unwrapDMAny(wrap, d);
      if (!got) continue;
      if (got.rumor.kind === 14) {
        // unwrapDM judges "mine" against the key that DECRYPTED, but this
        // wallet can hold several identities (wallet key + nostr login). A
        // sent-copy authored by any of them must thread under the RECIPIENT,
        // or every welcome DM the registrar sends lands in a self-thread.
        const mine = isMe(got.author);
        const to = got.rumor.tags?.find((x) => x[0] === 'p')?.[1];
        const peer = mine ? (to || got.peer || got.author) : got.author;
        noteDM(peer, got.rumor, mine);
        persistDms();
      } else if (got.rumor.kind === 7) {
        // a DM reaction (ours echoed back, or the peer's — 0xchat's shape)
        const target = got.rumor.tags?.find((x) => x[0] === 'e')?.[1];
        if (target) {
          (dmReacts.get(target) || dmReacts.set(target, new Map()).get(target)).set(got.author, got.rumor.content);
          scheduleRepaint();
        }
      } else if (got.rumor.kind === 3313 && !isMe(got.author)) {
        try {
          const b = openDirectBundle(got.rumor.content);
          if (b && !st().declined[got.rumor.id] && !communityById(b.community_id))
            pendingDirect.set(got.rumor.id, { bundle: b, from: got.author, rid: got.rumor.id });
          scheduleRepaint();
        } catch {}
      }
      return true;
    }
    return false;
  }

  async function handleInboxWrap(wrap) {
    if (seenWraps.has(wrap.id) || seenWraps.has(wrapKey(wrap.id))) return;
    seenWraps.add(wrap.id);
    if (await openInboxWrap(wrap)) { rememberWrap(wrap.id); return; }
    if (pendingWraps.size >= PENDING_MAX) pendingWraps.delete(pendingWraps.keys().next().value);
    pendingWraps.set(wrap.id, { wrap, tries: decryptorsComplete() ? 1 : 0 });
    scheduleDrain(8000);
  }

  function scheduleDrain(ms) {
    if (!pendingWraps.size) return;
    clearTimeout(drainTimer);
    drainTimer = setTimeout(() => { drainPendingWraps().catch(() => {}); }, ms);
  }

  async function drainPendingWraps() {
    if (draining || !pendingWraps.size) return;
    draining = true;
    try {
      // Wraps sealed to the login npub can't open without its signer. Wake it
      // up ourselves — the boot-time resume is a single attempt, and if it
      // loses to cold-start churn nothing else asks until the user happens to
      // touch a screen that calls identity(). Resume single-flights and
      // rate-limits itself, so asking here is cheap.
      if (!decryptorsComplete()) await Promise.resolve(hook('nostrLoginResume')).catch(() => null);
      if (!dmDecryptors().length) return;
      const complete = decryptorsComplete();
      // Each openInboxWrap decrypts a gift wrap — NIP-44 ECDH, real
      // secp256k1 work. A backlog decrypted in one tight loop blocks the main
      // thread for the whole burst (the boot-time jank that made a carousel
      // drag lurch). Cap each synchronous run to a frame's budget and yield so
      // input and paint get a turn; the backfill just takes a few extra frames.
      let chunkStart = performance.now();
      for (const [id, p] of [...pendingWraps]) {
        // A remote signer can die mid-pass; counting the remaining wraps as
        // full-strength failures would evict messages that were never really
        // tried. Stop here — the slow retry picks the rest up.
        if (complete && !decryptorsComplete()) break;
        if (await openInboxWrap(p.wrap)) { pendingWraps.delete(id); rememberWrap(id); }
        else if (complete && ++p.tries >= PENDING_TRIES) { pendingWraps.delete(id); rememberWrap(id); }
        if (performance.now() - chunkStart > 8) {
          await new Promise((r) => setTimeout(r));
          chunkStart = performance.now();
        }
      }
    } finally { draining = false; }
    // still holding wraps: the signer may connect later — keep a slow retry
    if (pendingWraps.size) scheduleDrain(decryptorsComplete() ? 30_000 : 60_000);
  }

  function openDirectBundle(json) {
    const b = JSON.parse(json);
    if (communityId(b.owner, b.owner_salt) !== b.community_id) return null;
    if (!/^[0-9a-f]{64}$/.test(b.community_root || '')) return null;
    if (!Array.isArray(b.channels) || b.channels.length > 256) return null;
    if (b.expires_at && Date.now() > b.expires_at) return null;
    return b;
  }

  function startDMs() {
    if (dmStarted) return;
    // Poll/advertise only the single DM identity (see dmSubKeys) — not the seed
    // key as a phantom second inbox.
    const pks = dmSubKeys();
    if (!pks.length) return;
    dmStarted = true;
    loadSeenWraps();
    // warm threads from the local cache. A self-thread of our own messages is
    // the residue of the old sent-copy misthreading (each welcome DM landed
    // under our own key) — sweep it rather than resurrect it; the cached
    // rows carry no tags, so they cannot be re-threaded to their recipients.
    const s = st();
    let swept = false;
    for (const [peer, list] of Object.entries(s.dms)) {
      if (isMe(peer) && list.every((m) => isMe(m.from))) {
        delete s.dms[peer];
        swept = true;
        continue;
      }
      for (const m of list)
        threadOf(peer).set(m.id, { rumor: { id: m.id, pubkey: m.from, content: m.text, created_at: m.t, kind: 14 }, mine: isMe(m.from) });
    }
    bumpMsgRev();
    if (swept) save(s);
    allUnsubs.push(subscribeOn(DM_RELAYS, { kinds: [1059], '#p': pks, limit: 400 }, (wrap) => {
      handleInboxWrap(wrap).catch(() => {});
    }));
    // Senders deliver to the relays our kind-10050 advertises — a list other
    // clients may have published with relays beyond our defaults. Read those
    // too, or a compliant sender's DM lands somewhere we never look (a reply
    // went only to damus/primal and no device ever showed it).
    (async () => {
      try {
        const lists = await Promise.all(pks.map((pk) => fetchInboxRelays(pk).catch(() => [])));
        const extras = [...new Set(lists.flat().map((r) => String(r || '').trim().replace(/\/$/, '')))]
          .filter((r) => /^wss:\/\//i.test(r) && !DM_RELAYS.includes(r))
          .slice(0, 3);
        if (extras.length && dmStarted)
          allUnsubs.push(subscribeOn(extras, { kinds: [1059], '#p': pks, limit: 400 }, (wrap) => {
            handleInboxWrap(wrap).catch(() => {});
          }));
      } catch {}
    })();
    ensureDmRelayList().catch(() => {});
  }

  // Publish a kind 10050 DM-relay list for the wallet key if none exists, so
  // other NIP-17 clients can find our inbox. Never touch a login npub's list
  // — the user's other clients own that. And when a login identity IS active,
  // don't advertise the seed key at all: it's internal, not a second inbox
  // (advertising it is what let DMs land on a phantom identity).
  async function ensureDmRelayList() {
    if (!wallet.nostr || !wallet.nostr.sk) return;
    if (hook('nostrLoginIdentity')) return;
    const pk = wallet.nostr.pk;
    const existing = await queryOn(DM_RELAYS, { kinds: [10050], authors: [pk] }, 2500);
    if (existing.length) return;
    const evt = finalizeEvent({
      kind: 10050,
      content: '',
      tags: DM_RELAYS.map((r) => ['relay', r]),
      created_at: Math.floor(Date.now() / 1000),
    }, wallet.nostr.sk);
    publishOn(DM_RELAYS, evt);
  }

  async function sendDM(peer) {
    const text = draftFor('dm:' + peer).trim();
    if (!text) return;
    const id = await identity();
    if (!id) { noIdToast(); return; }
    if (!(id.signer instanceof Uint8Array) && !id.signer.encryptTo) { toast(t('msgSignerNoDm')); return; }
    // Same optimistic shape as channel sends: the rumor is synchronous and on
    // screen at once. Wrapping the same rumor keeps the id, so the sent-copy
    // echo folds into this entry instead of duplicating it.
    const replyTo = ui.msgReplyTo && threadOf(peer).has(ui.msgReplyTo) ? ui.msgReplyTo : null;
    ui.msgReplyTo = null;
    const rumor = makeDMRumor(id.pubkey, peer, text, replyTo ? [['e', replyTo]] : []);
    const entry = { rumor, mine: true, pending: true };
    threadOf(peer).set(rumor.id, entry);
    clearDraft('dm:' + peer);
    ui.msgStick = true;
    render();
    try {
      // Sequential on purpose — a remote signer is happier signing one at a time.
      const toPeer = await wrapDM(id.signer, peer, rumor);
      const toSelf = await wrapDM(id.signer, id.pubkey, rumor);
      // Our own relays take the wrap immediately; the peer's declared inbox
      // (a lookup that can take seconds) is chased off the critical path.
      // Publishing the same wrap twice is harmless — relays dedupe on id.
      const ok = await publishOn(DM_RELAYS, toPeer);
      publishOn(DM_RELAYS, toSelf);
      fetchInboxRelays(peer).then((inbox) => {
        const extra = inbox.slice(0, 4).filter((r) => !DM_RELAYS.includes(r));
        if (extra.length) publishOn(extra, toPeer);
      }).catch(() => {});
      if (!ok) { toast(t('msgSendFailed')); return; }
      delete entry.pending;
      persistDms();
    } catch (e) {
      threadOf(peer).delete(rumor.id);
      toast(e.message || String(e));
      render();
    }
  }

  // React to a DM: the same kind-7-in-a-gift-wrap shape 0xchat uses, sent to
  // the peer and to our own inbox (the echo is what other devices fold in).
  // Optimistic like sendDM; one reaction per author, latest wins.
  async function sendDmReaction(peer, m, emoji) {
    const id = await identity();
    if (!id) { noIdToast(); return; }
    if (!(id.signer instanceof Uint8Array) && !id.signer.encryptTo) { toast(t('msgSignerNoDm')); return; }
    ui.msgSheet = null;
    const rumor = makeDMReaction(id.pubkey, peer, m.rumor.id, emoji);
    const r = dmReacts.get(m.rumor.id) || dmReacts.set(m.rumor.id, new Map()).get(m.rumor.id);
    const prev = r.get(id.pubkey);
    r.set(id.pubkey, emoji);
    render();
    try {
      const toPeer = await wrapDM(id.signer, peer, rumor);
      const toSelf = await wrapDM(id.signer, id.pubkey, rumor);
      seenWraps.add(toPeer.id); seenWraps.add(toSelf.id);
      const ok = await publishOn(DM_RELAYS, toPeer);
      publishOn(DM_RELAYS, toSelf);
      fetchInboxRelays(peer).then((inbox) => {
        const extra = inbox.slice(0, 4).filter((x) => !DM_RELAYS.includes(x));
        if (extra.length) publishOn(extra, toPeer);
      }).catch(() => {});
      if (!ok) toast(t('msgSendFailed'));
    } catch (e) {
      if (prev) r.set(id.pubkey, prev); else r.delete(id.pubkey);
      toast(e.message || String(e));
      render();
    }
  }

  function persistDms() {
    const s = st();
    const byRecent = [...threads.entries()]
      .map(([peer, m]) => [peer, [...m.values()].sort((a, b) => a.rumor.created_at - b.rumor.created_at)])
      .sort((a, b) => (b[1].at(-1)?.rumor.created_at || 0) - (a[1].at(-1)?.rumor.created_at || 0))
      .slice(0, 30);
    s.dms = {};
    for (const [peer, list] of byRecent)
      s.dms[peer] = list.filter((m) => !m.pending).slice(-CACHE_MAX)
        .map((m) => ({ id: m.rumor.id, from: m.rumor.pubkey, text: m.rumor.content, t: m.rumor.created_at }));
    save(s);
  }

  // ---- views --------------------------------------------------------------

  const timeLabel = (tms) => {
    const d = new Date(tms);
    const today = new Date().toDateString() === d.toDateString();
    return today
      ? d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
      : d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) +
        ' ' + d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
  };

  // Which bytes a face paints from, in order of preference:
  //   our own punk art, straight off disk at the size being drawn;
  //   the thumbnail we keep locally, which needs no network at all;
  //   the original, when we have nothing else yet.
  // The 64px profile avatar layers the original OVER the local copy: CSS
  // paints the first layer that has arrived, so the face is there instantly
  // and sharpens when the full-size one lands.
  function avatarBg(p, big) {
    const punk = localPunk(p.picture, big);
    if (punk) return `url(${JSON.stringify(punk)})`;
    const local = p.thumb && p.thumbFor === p.picture ? p.thumb : null;
    if (!local) return `url(${JSON.stringify(p.picture)})`;
    return (big ? `url(${JSON.stringify(p.picture)}),` : '') + `url(${JSON.stringify(local)})`;
  }

  const avatar = (pk, cls = 'chat-avatar', clickable = true) => {
    const p = profileOf(pk);
    // Someone we've never cached used to get an empty circle until a relay
    // answered — seconds of blankness on every boot, and for anyone whose
    // kind 0 carries no picture (or none at all, which never gets cached)
    // that repeated forever. The punk is derived from the pubkey alone, so
    // it can be drawn in the first frame: it's already the right answer for
    // everyone without a picture, and for a coinos user who kept the default
    // it IS their published picture. A real photo replaces it when it lands.
    //
    // `loading` is different and still gets the quiet circle: a name lookup
    // is in flight for that specific person, so a picture is expected and
    // punk art must not flash in front of it.
    const node = p && p.loading && !p.picture
      ? h('div', { class: cls + ' fallback loading' })
      : p === null
        ? fallbackAvatar(h, pk, null, cls)
      : p.picture 
        // A background paints synchronously from cache; a fresh <img> decodes
        // async, so recreating one per render made avatars visibly flash.
        //
        // The thumbnail we keep locally is the whole picture at this size, so
        // a 30px circle never asks the network for the original again. The
        // 64px profile avatar layers them: CSS paints the first layer that
        // has arrived, so the thumbnail shows instantly and the full-size
        // original takes over on top when it lands.
        ? h('div', { class: cls + ' ava-img', style: 'background-image:' + avatarBg(p, cls.includes('profile-avatar')) })
        : fallbackAvatar(h, pk, p.name, cls);
    // A face we keep painting is one worth keeping a thumbnail of.
    if (p && p.picture) makeThumb(pk, p);
    if (clickable) {
      node.classList.add('clickable');
      // Start the profile's own fetches on touch-DOWN, not on click. The gap
      // between the two is a hundred-odd milliseconds of free head start,
      // and unlike prefetching every row on paint (which cost sixty requests
      // for twenty rows and starved the profile batch) this only ever asks
      // about the person actually being tapped.
      node.addEventListener('pointerdown', () => { try { prefetchProfilePage(pk); } catch {} }, { passive: true });
      node.addEventListener('click', (e) => { e.stopPropagation(); openProfile(pk); });
    }
    return hook('wrapAvatar', pk, node) || hatStamp(pk, node) || node;
  };

  // The hats feature is a deferred chunk — until it lands, replay last
  // session's boot stamps (hat art + geometry it persisted) so a hat sits on
  // the head from the FIRST frame instead of popping in a beat later. Once
  // hatsReady answers, the stamps stand down: a null from wrapAvatar then
  // genuinely means "bare head".
  let _hatStamps = null;
  function hatStamp(pk, node) {
    if (hook('hatsReady')) return null;
    if (_hatStamps === null) {
      try { _hatStamps = JSON.parse(localStorage.getItem('hat-stamps') || '{}'); } catch { _hatStamps = {}; }
    }
    const s = _hatStamps[pk];
    if (!s || !s.a) return null;
    return h('span', { class: 'hat-wrap' }, node, h('span', { class: 'ava-hat', style: s.s, html: s.a }));
  }

  // ---- profiles: view + own kind-0 editor ---------------------------------

  const fullProfiles = new Map(); // pk -> { raw kind0 content object, fetched_at }
  const fullFetched = new Set();  // fetched from relays this session

  // The profile-page cache SURVIVES refreshes: bios and recent posts serve
  // instantly from storage while a background fetch freshens them. Bounded:
  // the last handful of viewed/warmed pages, notes trimmed to what the rows
  // render.
  const PROF_PAGE_CACHE = 'profPages';
  const pageCache = () => {
    try {
      const c = wallet.loadFeatureState(PROF_PAGE_CACHE, {}) || {};
      return { full: c.full || {}, notes: c.notes || {} };
    } catch { return { full: {}, notes: {} }; }
  };
  function persistPage(kind, pk, value) {
    try {
      const c = pageCache();
      c[kind][pk] = { t: Date.now(), v: value };
      for (const k of ['full', 'notes']) {
        const keys = Object.keys(c[k]).sort((a, b) => c[k][b].t - c[k][a].t);
        for (const drop of keys.slice(10)) delete c[k][drop];
      }
      wallet.saveFeatureState(PROF_PAGE_CACHE, c);
    } catch {}
  }
  const slimNote = (ev) => ({
    id: ev.id, pubkey: ev.pubkey, kind: 1, created_at: ev.created_at,
    content: String(ev.content || '').slice(0, 3000),
    tags: (ev.tags || []).filter((x) => x[0] === 'e' || x[0] === 'p'),
  });

  function fetchFullProfile(pk) {
    if (!fullProfiles.has(pk)) {
      const cached = pageCache().full[pk];
      if (cached) fullProfiles.set(pk, cached.v);
    }
    if (fullFetched.has(pk)) return;
    fullFetched.add(pk);
    queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [pk] }, 3500).then((evs) => {
      const newest = evs.sort((a, b) => b.created_at - a.created_at)[0];
      let m = {};
      try { m = newest ? JSON.parse(newest.content) : {}; } catch {}
      fullProfiles.set(pk, m);
      persistPage('full', pk, m);
      // A full fetch is the freshest word on this profile — stamp it into the
      // light cache (and persist) so a picture changed elsewhere replaces the
      // stale one everywhere within a session, not after the 24h TTL. The
      // repaint covers the header/chat avatars, not just an open profile page.
      const entry = {
        name: m.display_name || m.name || null, picture: m.picture || null,
        nip05: m.nip05 || null, lud16: typeof m.lud16 === 'string' ? m.lud16.trim() : null,
        about: typeof m.about === 'string' ? m.about.slice(0, 1000) : null,
        banner: typeof m.banner === 'string' ? m.banner.slice(0, 400) : null,
        t: Date.now(),
      };
      keepThumb(pk, entry);
      profiles.set(pk, entry);
      persistProfile(pk, entry);
      preloadPicture(entry);
      if (ui.profilePk === pk) render();
      else scheduleRepaint();
    }).catch(() => { if (!fullProfiles.has(pk)) fullProfiles.set(pk, {}); });
  }

  // Warm a profile PAGE (full kind-0 + latest notes + relay list) before
  // anyone taps it, so the page opens complete instead of behind spinners.
  // Queued with a small concurrency cap: likely tap-targets only, never a
  // whole room's member list at once.
  const prefetched = new Set();
  const prefetchQueue = [];
  let prefetching = 0;
  function prefetchProfilePage(pk) {
    if (!pk || prefetched.has(pk)) return;
    prefetched.add(pk);
    prefetchQueue.push(pk);
    drainPrefetch();
  }
  function drainPrefetch() {
    while (prefetching < 2 && prefetchQueue.length) {
      const pk = prefetchQueue.shift();
      prefetching++;
      Promise.allSettled([
        Promise.resolve(fetchFullProfile(pk)),
        Promise.resolve(notesFor(pk)),
      ]).finally(() => { prefetching--; drainPrefetch(); });
    }
  }

  function openProfile(pk) {
    ui.profilePk = pk;
    // Opened from inside a thread (an author's avatar/name), the profile
    // stacks ON TOP of it — back returns to the conversation. The screen
    // router otherwise keeps a thread above the profile, which is the order
    // for the other direction (a note row tapped on a profile page).
    ui.profOverThread = !!ui.noteThread;
    ui.profEdit = null; ui.profEditFilled = false; ui.logoutConfirm = null; ui.profCompose = null;
    render();
    fetchFullProfile(pk);
    notesFor(pk);
  }

  // ---- profile notes: latest public posts & replies -----------------------

  const NOTE_RELAYS = [...new Set([...PROFILE_RELAYS, ...DM_RELAYS])];

  // ---- zap tallies ---------------------------------------------------------
  // How much a post or chat message has been zapped: the public receipts
  // that e-tag it — NIP-57 kind 9735 (the recipient's LNURL server signs one
  // once the invoice is paid) and coinos' own Ark zap receipt (kind 9737,
  // the zapper publishes it beside the mailbox delivery). Summed per id,
  // deduped by receipt, painted as a little bolt + sats. A chat message is a
  // rumor with an id like any event, so a zap aimed at it e-tags that id —
  // the receipt reveals nothing but the id itself.
  const ZAP_KINDS = [9735, 9737];
  // ...and, in the same REQ, what else happened to a note: likes (kind 7)
  // and boosts (kind 6). One round trip for all three.
  const NOTE_KINDS = [9735, 9737, 7, 6];
  const reacts = new Map();  // note id -> Map(emoji -> Set<pubkey>)
  const boosts = new Map();  // note id -> Set<pubkey>
  const seenNoteEv = new Set(); // event ids already counted
  const myReactEv = new Map();  // note id -> the id of OUR reaction, so it can be withdrawn
  const zapTotals = new Map(); // id -> { sats, seen: Set<receipt id>, mine }
  const zapAsked = new Set();
  let zapQueue = new Set(), zapTimer = null, zapLiveUnsub = null, zapRecent = [];
  const zapRelays = () => [...new Set([...NOTE_RELAYS, ...((wallet.nostrRelays && wallet.nostrRelays()) || [])])];
  const tagOf = (ev, k) => (ev.tags.find((x) => x[0] === k) || [])[1];
  function receiptSats(ev) {
    if (ev.kind === 9737) {
      const net = tagOf(ev, 'network');
      if (net && net !== getNetwork()) return 0;
      return Math.max(0, parseInt(tagOf(ev, 'amount'), 10) || 0);
    }
    const b11 = tagOf(ev, 'bolt11');
    if (b11) { try { const d = decodeBolt11(b11); if (d && d.amountSat) return d.amountSat; } catch {} }
    // no readable invoice: the zap request inside says what was asked for
    try {
      const req = JSON.parse(tagOf(ev, 'description') || 'null');
      return Math.floor((parseInt(tagOf(req, 'amount'), 10) || 0) / 1000);
    } catch { return 0; }
  }
  function zapperOf(ev) {
    if (ev.kind === 9737) return ev.pubkey;
    if (tagOf(ev, 'P')) return tagOf(ev, 'P');
    try { return (JSON.parse(tagOf(ev, 'description') || 'null') || {}).pubkey || null; } catch { return null; }
  }
  // Where an event about a note goes. A zap receipt is money and has its own
  // bookkeeping (see below); a like and a boost are just tallies of who.
  function noteEvent(ev) {
    if (ev.kind === 7 || ev.kind === 6) {
      if (seenNoteEv.has(ev.id)) return;
      seenNoteEv.add(ev.id);
      // the LAST e tag is the note being reacted to (NIP-25)
      const ids = (ev.tags || []).filter((x) => x[0] === 'e' && x[1]).map((x) => x[1]);
      const id = ids[ids.length - 1];
      if (!id) return;
      if (ev.kind === 6) {
        if (!boosts.has(id)) boosts.set(id, new Set());
        boosts.get(id).add(ev.pubkey);
      } else {
        // '+' and an empty content both mean a plain like
        const emoji = !ev.content || ev.content === '+' ? '\u2764\ufe0f' : ev.content.slice(0, 12);
        if (!reacts.has(id)) reacts.set(id, new Map());
        const m = reacts.get(id);
        if (!m.has(emoji)) m.set(emoji, new Set());
        m.get(emoji).add(ev.pubkey);
        // ours, wherever it was sent from — so it can be taken back here
        if (myPubkeys().includes(ev.pubkey)) myReactEv.set(id, ev.id);
      }
      scheduleRepaint();
      return;
    }
    noteReceipt(ev);
  }

  function noteReceipt(ev) {
    const sats = receiptSats(ev);
    if (!sats) return;
    const my = myPubkeys();
    const from = zapperOf(ev);
    let changed = false;
    for (const x of ev.tags) {
      if (x[0] !== 'e' || !x[1]) continue;
      const cur = zapTotals.get(x[1]) || zapTotals.set(x[1], { sats: 0, seen: new Set(), mine: false }).get(x[1]);
      if (cur.seen.has(ev.id)) continue;
      cur.seen.add(ev.id);
      cur.sats += sats;
      // our own zap's receipt: the real thing has landed, so the optimistic
      // amount the chip has been carrying since the tap steps aside
      if (from && my.includes(from)) { cur.mine = true; voidPending(x[1], ev.created_at * 1000); }
      changed = true;
    }
    if (changed) { saveZapTotals(); scheduleRepaint(); }
  }
  // Ask once per id (batched per paint), and keep ONE live subscription on
  // the ids most recently on screen, so a zap landing while you watch —
  // yours included — shows up without a reload.
  function watchZaps(ids) {
    let fresh = false;
    for (const id of ids) if (id && !zapAsked.has(id)) { zapAsked.add(id); zapQueue.add(id); fresh = true; }
    if (!fresh || zapTimer) return;
    zapTimer = setTimeout(() => {
      zapTimer = null;
      const batch = [...zapQueue]; zapQueue = new Set();
      const relays = zapRelays();
      for (let i = 0; i < batch.length; i += 150) {
        const slice = batch.slice(i, i + 150);
        queryOn(relays, { kinds: NOTE_KINDS, '#e': slice }, 4000)
          .then((evs) => {
            evs.forEach(noteEvent);
            // the relays have spoken for these ids: their live tally is the
            // truth now, remembered or not (a zap that was deleted has to be
            // able to disappear)
            for (const id of slice) zapSeeds().delete(id);
            saveZapTotals();
            scheduleRepaint();
          }).catch(() => {});
      }
      zapRecent = [...batch.reverse(), ...zapRecent.filter((x) => !batch.includes(x))].slice(0, 200);
      if (zapLiveUnsub) { try { zapLiveUnsub(); } catch {} }
      zapLiveUnsub = subscribeOn(relays, { kinds: NOTE_KINDS, '#e': zapRecent, since: Math.floor(Date.now() / 1000) - 60 }, noteEvent);
    }, 250);
  }
  // Tallies are asked of the relays again on every boot, and that takes
  // seconds — long enough that a room full of zapped messages paints bare and
  // fills in afterwards. So the totals themselves are remembered (just the
  // numbers, never the receipts) and painted straight away; the moment the
  // relays answer for a message, their word replaces it.
  const ZAP_REMEMBER = 400; // tallies kept between sessions
  let zapSeed = null;
  function zapSeeds() {
    if (!zapSeed) {
      zapSeed = new Map();
      try {
        for (const [id, v] of Object.entries(st().zaps || {})) if (v && v.s) zapSeed.set(id, { sats: v.s, mine: !!v.m });
      } catch {}
    }
    return zapSeed;
  }
  let zapSaveT = null;
  function saveZapTotals() {
    clearTimeout(zapSaveT);
    zapSaveT = setTimeout(() => {
      try {
        const s2 = st();
        // Update what's recently been on screen, and KEEP the rest: opening a
        // DM thread must not forget what the community chat had learned.
        const out = { ...(s2.zaps || {}) };
        for (const id of zapRecent) {
          const z = zapTotals.get(id) || zapSeeds().get(id);
          if (z && z.sats) out[id] = z.mine ? { s: z.sats, m: 1 } : { s: z.sats };
          else delete out[id]; // the relays answered, and it's zero
        }
        let n = Object.keys(out).length;
        if (n > ZAP_REMEMBER) {
          const recent = new Set(zapRecent);
          for (const k of Object.keys(out)) { // insertion order: oldest first
            if (n <= ZAP_REMEMBER) break;
            if (!recent.has(k)) { delete out[k]; n--; }
          }
        }
        s2.zaps = out;
        save(s2);
      } catch {}
    }, 1500);
  }

  // After OUR zap the receipt trails the payment by seconds — ask again.
  function recheckZap(id) {
    for (const ms of [4000, 12000, 30000]) setTimeout(() => { zapAsked.delete(id); watchZaps([id]); }, ms);
  }
  const fmtSats = (n) => n < 1000 ? String(n)
    : n < 10000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k'
      : n < 1e6 ? Math.round(n / 1000) + 'k'
        : (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M';
  const BOLT_SVG = '<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" stroke="none" style="display:block"><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>';

  // A tapped zap takes a few seconds to pay, and its public receipt trails
  // the payment by seconds more — long enough that the tap looked ignored.
  // So the chip appears the instant you tap, carrying your amount and
  // pulsing while the payment is in flight; it goes solid when the payment
  // lands and hands over to the real receipt when that arrives. A failure
  // takes it straight back off.
  const ZAP_FLIGHT_MS = 45_000; // nothing reported back: assume it's gone
  const ZAP_PAID_MS = 5 * 60_000; // paid, but the receipt never showed
  // id -> { sats, at, state }, where state is:
  //   flying — tapped, payment in the air: counted on top, chip pulses
  //   paid   — the flow reported success: counted on top, chip solid
  //   void   — one of OUR receipts has been counted into the real total for
  //            this id, so the optimistic amount must not be added again.
  //            Kept rather than deleted, because the receipt usually beats
  //            the flow's own report: an ark zap publishes that receipt
  //            itself, and it returns over the live subscription before the
  //            send call resolves. Deleting would let the later settle
  //            resurrect the amount — which is how a 21-sat zap displayed 42.
  const zapPending = new Map();
  const pendTtl = (p) => (p.state === 'flying' ? ZAP_FLIGHT_MS : ZAP_PAID_MS);
  function pendingOf(id) {
    const p = zapPending.get(id);
    if (!p) return null;
    if (Date.now() - p.at > pendTtl(p)) { zapPending.delete(id); return null; }
    return p;
  }
  function markZapPending(id, sats) {
    if (!id || !sats) return;
    zapPending.set(id, { sats, at: Date.now(), state: 'flying' });
    scheduleRepaint();
    // repaint when the in-flight chip would expire, so a zap nobody ever
    // reported on doesn't pulse forever
    setTimeout(scheduleRepaint, ZAP_FLIGHT_MS + 200);
  }
  // A zap flow reporting back: paid (keep the amount, stop pulsing) or
  // failed (the chip was never real — take it off).
  function settleZap(id, ok, sats) {
    if (!id) return;
    const p = pendingOf(id);
    if (!ok) {
      if (p && p.state !== 'void') { zapPending.delete(id); scheduleRepaint(); }
      return;
    }
    if (p && p.state === 'void') return; // the receipt is already carrying it
    zapPending.set(id, { sats: sats || (p && p.sats) || 0, at: Date.now(), state: 'paid' });
    scheduleRepaint();
  }
  // One of our own receipts has been counted for this id: the real total
  // speaks for the zap now, so the optimistic amount stands down.
  function voidPending(id, evMs) {
    const p = zapPending.get(id);
    // ...unless it's the receipt of an OLDER zap of ours arriving (the first
    // paint fetches every receipt a message has). That one is already in the
    // total and says nothing about the zap currently in the air.
    if (p && p.state !== 'void' && evMs && evMs < p.at - 120_000) return;
    zapPending.set(id, { sats: 0, at: Date.now(), state: 'void' });
  }
  // The chip: a little bolt + the sats total. Absent until the first receipt
  // — or until you zap it yourself, which is its own kind of receipt.
  function zapChip(id, { onClick, cls = '' } = {}) {
    const z = zapTotals.get(id) || zapSeeds().get(id);
    const p = pendingOf(id);
    const optimistic = p && p.state !== 'void' ? p.sats : 0;
    const sats = (z ? z.sats : 0) + optimistic;
    if (!sats) return null;
    const flying = !!p && p.state === 'flying';
    return h('span', {
      class: 'zap-tally' + ((z && z.mine) || optimistic ? ' on' : '') + (flying ? ' flying' : '')
        + (onClick ? ' clickable' : '') + (cls ? ' ' + cls : ''),
      title: flying ? t('zapSending') : t('zapTallyTitle', { n: sats.toLocaleString() }),
      onClick: onClick ? (e) => { e.stopPropagation(); onClick(); } : undefined,
    }, h('span', { style: 'display:flex', html: BOLT_SVG }), fmtSats(sats));
  }
  // Zap a chat message or DM: same one-tap flow as a post (ark first,
  // Lightning fallback, the amount remembered from the first time).
  function zapMessage(pk, id) {
    zapNote(pk, { id });
    recheckZap(id);
  }
  const notesCache = new Map(); // pk -> { status: 'loading'|'ready', notes: [kind-1 events] }
  // NIP-65: where this author actually writes. Their notes and threads live
  // there first — our default relays are just the common ground.
  const relayListCache = new Map(); // pk -> Promise<string[]>
  function relaysOf(pk) {
    let p = relayListCache.get(pk);
    if (p) return p;
    // the feed's batched fetch has probably already asked for this one
    const known = relayListsNow().get(pk);
    if (known) { p = Promise.resolve(known.r || []); relayListCache.set(pk, p); return p; }
    p = queryOn([...new Set([...PROFILE_RELAYS, ...NOTE_RELAYS])], { kinds: [10002], authors: [pk] }, 3500)
      .then((evs) => {
        const newest = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
        if (!newest) return [];
        return [...new Set(newest.tags
          .filter((x) => x[0] === 'r' && x[1] && x[2] !== 'read' && /^wss:\/\//.test(x[1]))
          .map((x) => x[1].replace(/\/$/, '')))].slice(0, 4);
      })
      .catch(() => []);
    relayListCache.set(pk, p);
    return p;
  }
  const notesRelays = async (pk) => [...new Set([...NOTE_RELAYS, ...(await relaysOf(pk))])];

  // Posts of theirs we already hold. Tapping a face in the feed is the
  // common way onto a profile, and the feed we just came from is full of
  // that person's posts — an open thread holds their replies too. Painting
  // those first means the page opens with real content instead of an empty
  // column that fills in a beat later, and the relay fetch below replaces
  // them the moment it answers.
  function notesInHand(pk) {
    const out = new Map();
    for (const e of (feed && feed.notes) || []) if (e.pubkey === pk) out.set(e.id, e);
    for (const c of threadCache.values()) {
      if (c.root && c.root.pubkey === pk) out.set(c.root.id, c.root);
      for (const e of c.replies || []) if (e.pubkey === pk) out.set(e.id, e);
    }
    return [...out.values()].sort((a, b) => b.created_at - a.created_at);
  }

  function notesFor(pk) {
    let c = notesCache.get(pk);
    if (c) return c;
    // stored posts paint the page instantly; the relay fetch below freshens
    const stored = pageCache().notes[pk];
    const seed = stored ? stored.v : notesInHand(pk);
    // Seeded from memory the status stays 'loading': these are posts we
    // happen to have, not their page, so the real answer still replaces
    // them — but there is something to read while it comes.
    c = stored
      ? { status: 'ready', notes: stored.v }
      : { status: 'loading', notes: seed };
    notesCache.set(pk, c);
    (async () => {
      const evs = await queryOn(await notesRelays(pk), { kinds: [1], authors: [pk], limit: 30 }, 4500);
      const seen = new Set();
      const fresh = (evs || [])
        .filter((e) => !seen.has(e.id) && seen.add(e.id))
        .sort((a, b) => b.created_at - a.created_at);
      if (fresh.length || !c.notes.length) {
        c.notes = fresh;
        persistPage('notes', pk, fresh.slice(0, 20).map(slimNote)); // cache stays bounded
      }
    })().catch(() => {}).finally(() => {
      c.status = 'ready';
      if (ui.profilePk === pk) render();
    });
    return c;
  }

  // Infinite scroll: pull the next page of OLDER notes (until = oldest seen)
  // when the profile page nears its bottom. Guarded so scroll spam costs
  // nothing: one fetch in flight, and a short answer marks the end.
  // Registered at CONSTRUCTION, not init(): the public no-wallet profile
  // (a /username deep link over the unlock screen) scrolls too, and init
  // only runs once a wallet opens.
  if (typeof window !== 'undefined') {
    window.addEventListener('scroll', () => {
      // back at the top of the feed: the waiting posts belong on screen now
      if (ui.chatOpen && ui.msgView === 'feed' && atFeedTop()) flushPending(false);
      if (!ui.profilePk && !(ui.chatOpen && ui.msgView === 'feed')) return;
      if (window.innerHeight + window.scrollY < (document.documentElement.scrollHeight || 0) - 600) return;
      if (ui.profilePk) loadOlderNotes(ui.profilePk).catch(() => {});
      else loadOlderFeed().catch(() => {});
    }, { passive: true });
  }
  async function loadOlderNotes(pk) {
    const c = notesCache.get(pk);
    if (!c || c.status !== 'ready' || c.loadingMore || c.end) return;
    const oldest = c.notes[c.notes.length - 1];
    if (!oldest) { c.end = true; return; }
    c.loadingMore = true;
    render();
    try {
      const evs = await queryOn(await notesRelays(pk),
        { kinds: [1], authors: [pk], limit: 30, until: oldest.created_at - 1 }, 4500);
      const seen = new Set(c.notes.map((e) => e.id));
      const older = (evs || [])
        .filter((e) => !seen.has(e.id) && seen.add(e.id))
        .sort((a, b) => b.created_at - a.created_at);
      if (older.length) c.notes = [...c.notes, ...older];
      else c.end = true; // the relays have nothing older
    } catch {} finally {
      c.loadingMore = false;
      if (ui.profilePk === pk) render();
    }
  }


  // ---- follows: the kind-3 contact list -------------------------------------
  // Who you follow. Kept locally so the Follow button and the feed are right
  // in the first frame, and refreshed from relays behind that. A contact list
  // is a shared document — other clients keep relay hints in its content and
  // petnames in its tags — so publishing preserves everything we didn't write
  // and only ever adds or removes one p tag.
  const FOLLOWS = 'follows';
  let follows = null;      // { set: Set<pk>, tags, content, at }
  let followsAt = 0;       // when we last asked the relays
  let followsPub = false;  // a publish is in flight

  const mePk = () => (hook('nostrLoginIdentity') || {}).pubkey || (wallet.nostr && wallet.nostr.pk) || null;
  const pTags = (tags) => (tags || []).filter((x) => x[0] === 'p' && /^[0-9a-f]{64}$/.test(x[1] || ''));

  function followsNow() {
    if (!follows) {
      let s = null;
      try { s = wallet.loadFeatureState(FOLLOWS, null); } catch {}
      const tags = (s && s.tags) || [];
      follows = { set: new Set(pTags(tags).map((x) => x[1])), tags, content: (s && s.c) || '', at: (s && s.at) || 0 };
    }
    return follows;
  }
  function saveFollows(f) {
    follows = f;
    try { wallet.saveFeatureState(FOLLOWS, { tags: f.tags, c: f.content, at: f.at }); } catch {}
  }
  const isFollowing = (pk) => followsNow().set.has(pk);

  // Fetch the newest list from the relays. Older than what we hold is
  // ignored: a relay that missed our last publish must not un-follow people.
  async function syncFollows({ force = false } = {}) {
    const me = mePk();
    if (!me) return followsNow();
    if (!force && Date.now() - followsAt < 10 * 60_000) return followsNow();
    followsAt = Date.now();
    try {
      const evs = await queryOn(zapRelays(), { kinds: [3], authors: [me] }, 5000);
      const newest = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
      const cur = followsNow();
      if (newest && newest.created_at > cur.at) {
        saveFollows({
          set: new Set(pTags(newest.tags).map((x) => x[1])),
          tags: newest.tags || [], content: newest.content || '', at: newest.created_at,
        });
        feedAuthorsChanged();
        scheduleRepaint();
      }
    } catch { followsAt = 0; }
    return followsNow();
  }

  // Follow or unfollow, on the freshest list the relays will give us — the
  // local copy alone would quietly drop anyone another client added since.
  // The button flips immediately and goes back if the publish fails.
  async function toggleFollow(pk) {
    if (!pk || followsPub) return;
    const id = await requireIdentity();
    if (pk === id.pubkey) return;
    followsPub = true;
    const before = followsNow();
    // paint the answer now, decide the real list a beat later
    saveFollows({ ...before, set: new Set(before.set.has(pk) ? [...before.set].filter((x) => x !== pk) : [...before.set, pk]) });
    render();
    try {
      await syncFollows({ force: true });
      // The list to publish is the relays' copy if it's genuinely newer than
      // what we held, and otherwise what we held BEFORE the optimistic paint
      // — reading our own paint back as fact made a follow publish a list
      // without it, and a mute publish a list without the mute.
      const fetched = followsNow();
      const base = fetched.at > before.at ? fetched : before;
      const had = base.set.has(pk);
      const tags = had
        ? base.tags.filter((x) => !(x[0] === 'p' && x[1] === pk))
        : [...base.tags, ['p', pk]];
      const created_at = Math.max(Math.floor(Date.now() / 1000), base.at + 1);
      const partial = { kind: 3, content: base.content || '', created_at, tags };
      const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
      const ok = await publishOn(zapRelays(), evt);
      if (!ok) throw new Error(t('msgSendFailed'));
      saveFollows({ set: new Set(pTags(tags).map((x) => x[1])), tags, content: base.content || '', at: created_at });
      feedAuthorsChanged();
      syncInbox({ force: true }).catch(() => {}); // the SW's friend filter reads this list
      toast(had ? t('feedUnfollowed') : t('feedFollowed'));
    } catch (e) {
      saveFollows(before);
      if (!(e instanceof NoIdentity)) toast(e.message || String(e));
    } finally {
      followsPub = false;
      render();
    }
  }

  // ---- outbox: where each person actually publishes -------------------------
  // NIP-65. Asking our own three relays for everyone's posts only ever finds
  // the people who happen to use them — the rest are invisible, and it looks
  // like they stopped posting. So each author's own WRITE relays are read
  // instead. Lists are fetched in batches and kept for a week; the authors are
  // then covered greedily, so a feed of hundreds of people is a handful of
  // sockets that between them reach everyone rather than one socket each.
  const RELAY_LISTS = 'relayLists';
  const RELAY_LIST_TTL = 7 * 24 * 3600_000;
  // Sockets we'll open for one pass. Ten covered all but 66 of a real
  // 862-follow list; twenty-five covered all but 26. Amethyst runs near a
  // hundred — this is the same idea, kept to a number a phone can hold.
  const OUTBOX_MAX = 24;
  // Write relays taken from any one list. Three looks sufficient — everyone
  // ends up covered — but covered is not the same as read: people publish to
  // several relays and each holds a different slice. Measured over 250 real
  // authors, of the 60 with a write list, 45 declared MORE than three, and
  // seven of twenty-five sampled had posts living only on their fourth or
  // later relay.
  const PER_AUTHOR = 6;
  let relayLists = null;  // pk -> { r: [url], t }

  function relayListsNow() {
    if (!relayLists) {
      relayLists = new Map();
      try {
        for (const [pk, v] of Object.entries(wallet.loadFeatureState(RELAY_LISTS, {}) || {}))
          if (v && Date.now() - (v.t || 0) < RELAY_LIST_TTL) relayLists.set(pk, v);
      } catch {}
    }
    return relayLists;
  }
  function saveRelayLists() {
    try {
      const out = {};
      // the people we follow are the ones worth remembering; a page visit
      // shouldn't push them out
      const keep = new Set([...followsNow().set]);
      let spare = 200 - keep.size;
      for (const [pk, v] of relayListsNow()) {
        if (keep.has(pk)) out[pk] = v;
        else if (spare-- > 0) out[pk] = v;
      }
      wallet.saveFeatureState(RELAY_LISTS, out);
    } catch {}
  }
  // A relay list is written by whoever owns it, and some of them are wrong:
  // one in this wallet's follows has three URLs crammed into a single r tag,
  // space-separated. Fed to the pool that throws, and every author covered by
  // that relay quietly returns nothing. So each one has to parse as a URL,
  // and anything else is dropped rather than trusted.
  const okRelay = (u) => {
    if (typeof u !== 'string' || /\s/.test(u) || u.length > 200) return false;
    try { const p2 = new URL(u); return p2.protocol === 'wss:' && !!p2.host; } catch { return false; }
  };
  const writeRelaysIn = (ev) => [...new Set((ev.tags || [])
    .filter((x) => x[0] === 'r' && x[2] !== 'read' && okRelay(x[1]))
    .map((x) => String(x[1]).replace(/\/+$/, '')))].slice(0, PER_AUTHOR);

  // One REQ per hundred authors, against our own relays — a relay list is
  // small, widely mirrored, and worth having before anything else is asked.
  // Authors with no list at all are remembered as such, so we don't ask again
  // every time the feed refreshes.
  async function fetchRelayLists(pks) {
    const want = [...new Set(pks)].filter((pk) => !relayListsNow().has(pk));
    if (!want.length) return;
    for (let i = 0; i < want.length; i += 100) {
      const batch = want.slice(i, i + 100);
      const evs = await queryOn(NOTE_RELAYS, { kinds: [10002], authors: batch }, 4500).catch(() => []);
      const newest = new Map();
      for (const ev of evs || []) {
        const cur = newest.get(ev.pubkey);
        if (!cur || ev.created_at > cur.created_at) newest.set(ev.pubkey, ev);
      }
      for (const pk of batch) {
        const ev = newest.get(pk);
        relayListsNow().set(pk, { r: ev ? writeRelaysIn(ev) : [], t: Date.now() });
      }
    }
    saveRelayLists();
  }

  // The fewest relays that between them carry every author: take the relay
  // covering the most people not yet covered, repeat.
  //
  // Our own relays are then asked about EVERYONE as well, not just the people
  // with no list. Measured over eight busy accounts, each source holds posts
  // the other misses — reading only the author's own relays found 7 to 40
  // notes ours had never seen, and ours held plenty theirs didn't. The feed
  // wants the union, so the outbox adds reach rather than replacing it.
  function outboxPlan(authors) {
    const lists = relayListsNow();
    const byRelay = new Map();
    const orphans = [];
    for (const pk of authors) {
      const r = (lists.get(pk) || {}).r || [];
      if (!r.length) { orphans.push(pk); continue; }
      for (const url of r) {
        if (!byRelay.has(url)) byRelay.set(url, new Set());
        byRelay.get(url).add(pk);
      }
    }
    const orphaned = new Set(orphans);
    const covered = authors.filter((pk) => !orphaned.has(pk)); // the rest are on our relays below
    let left = new Set(covered);
    const plan = [];
    // Covering every author ONCE was the old stopping rule, and it was the
    // wrong goal: it finished in nineteen sockets of a twenty-four socket
    // budget and left posts unread on the relays it never opened. So the
    // greedy runs again over whoever the unused relays still reach, until
    // the budget is actually spent. Measured on the same 250 authors: 1303
    // notes before, 1624 after — a quarter more, for sockets we were already
    // willing to open.
    for (;;) {
      while (left.size && plan.length < OUTBOX_MAX) {
        let best = null, bestN = 0;
        for (const [url, set] of byRelay) {
          let n = 0;
          for (const pk of set) if (left.has(pk)) n++;
          if (n > bestN) { bestN = n; best = url; }
        }
        if (!best) break;
        const take = [...byRelay.get(best)].filter((pk) => left.has(pk));
        plan.push({ relays: [best], authors: take });
        for (const pk of take) left.delete(pk);
        byRelay.delete(best);
      }
      if (plan.length >= OUTBOX_MAX || !byRelay.size) break;
      // everyone the relays we HAVEN'T opened can still reach
      const again = new Set();
      for (const set of byRelay.values()) for (const pk of set) again.add(pk);
      if (!again.size) break;
      left = again;
    }
    plan.push({ relays: zapRelays(), authors });
    return plan;
  }

  // ---- the feed: posts from the people you follow ---------------------------
  // Their kind-1 notes, newest first, replies left out — a reply belongs to
  // its thread, and a timeline of half-conversations reads like eavesdropping.
  // The last screenful is kept locally so the feed opens with posts in it
  // rather than a spinner, exactly like the profile pages do.
  const FEED_CACHE = 'feedNotes';
  const FEED_LIMIT = 80;
  const FEED_PAGE = 20;    // posts on screen at once, grown as you scroll
  const FEED_KEEP = 200;   // in memory
  const FEED_STORE = 50;   // ...and on disk
  let feed = null;         // { status, notes, end, loadingMore }
  let feedUnsubs = [];
  let feedAt = 0;

  // A reply, as against a post that merely POINTS at another one. NIP-10
  // marks a reply's e tags 'root' or 'reply'; a quote's are 'mention', and
  // NIP-18 quotes carry a q tag instead. Treating every e tag as a reply hid
  // quote-posts from the feed — the thing Amethyst shows as a card with the
  // quoted note inside it.
  const isReply = (ev) => {
    const es = (ev.tags || []).filter((x) => x[0] === 'e');
    if (!es.length) return false;
    if (es.some((x) => x[3] === 'root' || x[3] === 'reply')) return true;
    if (es.every((x) => x[3] === 'mention')) return false;
    // unmarked (the deprecated positional form): a q tag means it's a quote,
    // otherwise assume the older convention, where e meant reply
    return !(ev.tags || []).some((x) => x[0] === 'q');
  };
  // Everyone you follow. This was capped at 500, which on an 862-follow list
  // meant 362 people were silently missing from the feed — 164 of the 166
  // posts a wider net found in one six-hour window were theirs.
  const FEED_AUTHORS_MAX = 2000;
  const REQ_AUTHORS = 400; // authors per REQ, so one filter stays a sane size
  const feedAuthors = () => [...followsNow().set].slice(0, FEED_AUTHORS_MAX);

  function feedNow() {
    if (!feed) {
      let stored = [];
      try { stored = wallet.loadFeatureState(FEED_CACHE, []) || []; } catch {}
      feed = { status: stored.length ? 'ready' : 'loading', notes: stored, shown: FEED_PAGE };
      refreshFeed();
    }
    return feed;
  }
  // A follow list that changed means a feed built from the wrong authors.
  function feedAuthorsChanged() {
    if (!feed) return;
    feedAt = 0;
    refreshFeed();
  }
  // How far from the top counts as "reading", rather than "sitting at the top
  // of the feed". Inserting a post above what someone is reading moves the
  // words under their eyes; at the top there is nothing to disturb.
  const FEED_TOP_PX = 120;
  const atFeedTop = () => {
    try { return (window.scrollY || 0) < FEED_TOP_PX; } catch { return true; }
  };

  function mergeFeed(evs, opts = {}) {
    const c = feedNow();
    const known = new Set([...c.notes, ...(c.pending || [])].map((e) => e.id));
    const add = (evs || []).filter((e) => e.kind === 1 && !isReply(e) && !isMuted(e.pubkey) && !known.has(e.id) && known.add(e.id));
    if (!add.length) return false;
    // A post that arrived on its own while you were reading waits behind the
    // pill instead of shoving the page down. Anything you asked for — a
    // refresh, a scroll to the bottom, the first load — goes straight in.
    if (opts.live && !atFeedTop() && c.notes.length) {
      c.pending = [...(c.pending || []), ...add].sort((a, b) => b.created_at - a.created_at).slice(0, FEED_KEEP);
      return true;
    }
    c.notes = [...c.notes, ...add].sort((a, b) => b.created_at - a.created_at).slice(0, FEED_KEEP);
    // posts arriving at the TOP shouldn't cost you the ones you'd scrolled to
    const fresh = add.filter((e) => e.created_at >= (c.notes[0] || {}).created_at).length;
    if (fresh) c.shown = Math.min((c.shown || FEED_PAGE) + fresh, c.notes.length);
    try { wallet.saveFeatureState(FEED_CACHE, c.notes.slice(0, FEED_STORE).map(slimNote)); } catch {}
    return true;
  }

  // Let the waiting posts in. Called by the pill, and by simply scrolling
  // back to the top — once you are up there they cost nothing to show.
  function flushPending(scroll) {
    const c = feed;
    if (!c || !(c.pending || []).length) return;
    const add = c.pending;
    c.pending = [];
    const seen = new Set(c.notes.map((e) => e.id));
    c.notes = [...c.notes, ...add.filter((e) => !seen.has(e.id))]
      .sort((a, b) => b.created_at - a.created_at).slice(0, FEED_KEEP);
    c.shown = Math.min((c.shown || FEED_PAGE) + add.length, c.notes.length);
    try { wallet.saveFeatureState(FEED_CACHE, c.notes.slice(0, FEED_STORE).map(slimNote)); } catch {}
    render();
    if (scroll) { try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch { window.scrollTo(0, 0); } }
  }
  // One pass over the plan: each relay is asked only for the authors it
  // actually carries. The slowest relay doesn't hold up the rest — every
  // answer merges as it lands.
  // `merge` rides along to mergeFeed: a catch-up after being away is exactly
  // as disruptive as a live arrival if you were reading halfway down, so it
  // goes behind the pill too. A first load, or paging older posts onto the
  // bottom, does not.
  async function feedPass(extra = {}, merge = {}) {
    const authors = feedAuthors();
    if (!authors.length) return false;
    await fetchRelayLists(authors);
    const plan = outboxPlan(authors);
    let got = false;
    await Promise.all(plan.flatMap(({ relays, authors: a }) => {
      const chunks = [];
      for (let i = 0; i < a.length; i += REQ_AUTHORS) chunks.push(a.slice(i, i + REQ_AUTHORS));
      return chunks.map(async (chunk) => {
        const evs = await queryOn(relays, { kinds: [1], authors: chunk, limit: FEED_LIMIT, ...extra }, 5000).catch(() => []);
        if (mergeFeed(evs, merge)) { got = true; scheduleRepaint(); }
      });
    }));
    return got;
  }
  async function refreshFeed(opts = {}) {
    if (!feedAuthors().length) { if (feed) feed.status = 'ready'; return; }
    if (!opts.force && Date.now() - feedAt < 30_000) return;
    feedAt = Date.now();
    try { await feedPass({}, { live: !!opts.force }); } catch {} finally {
      if (feed) feed.status = 'ready';
      scheduleRepaint();
    }
    watchFeed();
  }
  // While the feed is what's on screen, new posts arrive by themselves — on
  // the same relays the pass above reads, one subscription each.
  function watchFeed() {
    stopFeedWatch();
    if (!feedAuthors().length || !ui.chatOpen || ui.msgView !== 'feed') return;
    const since = Math.floor(Date.now() / 1000) - 60;
    for (const { relays, authors } of outboxPlan(feedAuthors()))
      for (let i = 0; i < authors.length; i += REQ_AUTHORS)
        feedUnsubs.push(subscribeOn(relays, { kinds: [1], authors: authors.slice(i, i + REQ_AUTHORS), since },
          (ev) => { if (mergeFeed([ev], { live: true })) scheduleRepaint(); }));
  }
  function stopFeedWatch() {
    for (const u of feedUnsubs) { try { u(); } catch {} }
    feedUnsubs = [];
  }
  // Reaching the bottom shows another twenty. Only when the window has caught
  // up with everything we hold do we go back to the relays for older posts —
  // rendering a hundred notes to show twenty was the whole cost here.
  async function loadOlderFeed() {
    const c = feedNow();
    if (c.shown < c.notes.length) {
      c.shown = Math.min(c.shown + FEED_PAGE, c.notes.length);
      render();
      if (c.shown < c.notes.length) return; // still serving from what we have
    }
    if (c.status !== 'ready' || c.loadingMore || c.end) return;
    const oldest = c.notes[c.notes.length - 1];
    if (!oldest || !feedAuthors().length) { c.end = true; return; }
    c.loadingMore = true;
    render();
    try {
      if (await feedPass({ until: oldest.created_at - 1 })) c.shown += FEED_PAGE;
      else c.end = true;
    } catch {} finally {
      c.loadingMore = false;
      render();
    }
  }

  // Note content, safely: text stays text nodes — relay content must never
  // reach innerHTML. URLs become links (image URLs inline), npub mentions a
  // clickable @name, other nostr: refs a dim stub.
  // Markdown, narrowly. A kind 1 is specified as plain text — NIP-10 says
  // markup SHOULD NOT be used — but bridges and cross-posters emit it anyway,
  // and what we did with it was the worst of the three options: the URL
  // inside ![cover](…) rendered as a picture while the ![cover]( was left
  // sitting above it as litter. So the whole construct is one token now.
  //
  // Images and links ONLY. Not headings, not bold, not italics: # opens a
  // hashtag and * turns up in ordinary prose, so honouring those would
  // mangle normal posts to pretty up the rare bridged one.
  const MD_LINK = '!?\\[[^\\]\\n]{0,300}\\]\\(\\s*<?https?:\\/\\/[^\\s>)]+>?[^)\\n]{0,300}\\)';
  const NOTE_SPLIT = new RegExp('(' + MD_LINK + '|https?:\\/\\/[^\\s]+|nostr:(?:npub|nprofile|note|nevent|naddr)1[a-z0-9]+)', 'gi');
  const MD_PARTS = new RegExp('^(!?)\\[([^\\]\\n]{0,300})\\]\\(\\s*<?(https?:\\/\\/[^\\s>)]+)>?[^)\\n]{0,300}\\)$', 'i');

  // A YouTube link is a video, so show the video. All three shapes it comes
  // in: the long one, the short one, and a Shorts link.
  const YT = /^https?:\/\/(?:www\.|m\.)?(?:youtube\.com\/(?:watch\?(?:[^\s]*&)?v=([\w-]{6,})|shorts\/([\w-]{6,})|live\/([\w-]{6,}))|youtu\.be\/([\w-]{6,}))/i;
  const youtubeId = (url) => { const m = YT.exec(url || ''); return m ? (m[1] || m[2] || m[3] || m[4]) : null; };
  const ytStart = (url) => {
    const m = /[?&](?:t|start)=(\d+)/.exec(url || '') || /[?&]t=(\d+)s/.exec(url || '');
    return m ? Math.max(0, parseInt(m[1], 10) || 0) : 0;
  };

  // The still, with a play button over it, and the player itself only once
  // it's tapped. A feed of ten videos would otherwise load ten YouTube
  // players — every one of them telling Google what you're scrolling past
  // before you've decided to watch anything. One tap, and it plays in place.
  function youtubeEmbed(url, vid) {
    const start = ytStart(url);
    const src = 'https://www.youtube-nocookie.com/embed/' + vid
      + '?autoplay=1&rel=0' + (start ? '&start=' + start : '');
    const frame = h('div', { class: 'yt-embed' },
      h('img', {
        class: 'yt-poster', loading: 'lazy', alt: '',
        src: 'https://i.ytimg.com/vi/' + vid + '/hqdefault.jpg',
        onError: (e) => { e.target.style.display = 'none'; },
      }),
      h('button', {
        class: 'yt-play', 'aria-label': t('playVideo'), title: t('playVideo'),
        onClick: (e) => {
          e.stopPropagation();
          const box = e.currentTarget.parentElement;
          if (!box || box.dataset.playing) return;
          box.dataset.playing = '1';
          box.textContent = '';
          const f = document.createElement('iframe');
          f.src = src;
          f.title = 'YouTube';
          f.allow = 'accelerometer; autoplay; encrypted-media; picture-in-picture; web-share';
          f.referrerPolicy = 'strict-origin-when-cross-origin';
          f.allowFullscreen = true;
          box.append(f);
        },
      }, h('span', { style: 'display:flex', html: '<svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor" style="display:block"><path d="M8 5v14l11-7z"/></svg>' })),
      h('a', {
        class: 'yt-open', href: url, target: '_blank', rel: 'noopener noreferrer',
        title: t('openInYouTube'), onClick: (e) => e.stopPropagation(),
      }, '\u2197'));
    return frame;
  }

  // ---- quoted notes ---------------------------------------------------------
  // A nostr:note1/nevent1 in someone's post IS a post, so show it: the thing
  // they're talking about, inside what they said about it. Fetched once per
  // id and remembered, so a feed that quotes the same note ten times asks for
  // it once.
  const quoted = new Map(); // id -> { status, ev }
  function quotedNote(ref) {
    let c = quoted.get(ref.id);
    if (c) return c;
    c = { status: 'loading', ev: null };
    quoted.set(ref.id, c);
    (async () => {
      const relays = [...new Set([...(ref.relays || []), ...zapRelays()])];
      const evs = await queryOn(relays, { ids: [ref.id] }, 4500).catch(() => []);
      c.ev = (evs || [])[0] || null;
      c.status = c.ev ? 'ready' : 'missing';
      scheduleRepaint();
    })();
    return c;
  }

  // The card. Deliberately not a noteRow: a quote is context, not another
  // post to act on — no reply, no boost, no zap of its own. Tapping it opens
  // the note properly, which is where those live.
  function quoteCard(ref, depth) {
    const c = quotedNote(ref);
    if (c.status === 'loading') {
      return h('div', { class: 'quote-card quote-loading' },
        h('span', { class: 'spinner sm' }), h('span', { class: 'small faint' }, t('noteRefLoading')));
    }
    if (!c.ev) {
      return h('div', { class: 'quote-card' },
        h('span', { class: 'small faint' }, t('noteRefNotFound')));
    }
    const ev = c.ev;
    return h('div', {
      class: 'quote-card clickable',
      onClick: (e) => { e.stopPropagation(); openNoteThread(ev); },
    },
      h('div', { class: 'row gap6', style: 'align-items:center;min-width:0' },
        avatar(ev.pubkey, 'chat-avatar mini', false),
        h('span', { class: 'quote-name' }, displayName(ev.pubkey)),
        h('span', { class: 'small faint', style: 'white-space:nowrap' }, timeLabel(ev.created_at * 1000))),
      h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' },
        // one level deep only: a quote of a quote of a quote is a rabbit
        // hole, and the inner one stays a link you can follow
        ...noteBody(ev.content, depth + 1)));
  }

  // One URL, rendered as whatever it points at. `isImage` is markdown saying
  // so outright — plenty of perfectly good picture URLs carry no extension
  // (a CDN path, a /media/ route), and ![…] is the author telling us what it
  // is, which beats guessing from the filename.
  function urlNode(url, { label = null, isImage = false } = {}) {
    if (/\.(mp4|webm|mov|m4v)(\?[^\s]*)?$/i.test(url)) {
      // metadata-only preload: the poster frame paints, nothing streams
      // until the viewer presses play
      return h('video', { src: url, class: 'note-video', controls: true,
        preload: 'metadata', playsinline: true,
        onError: (e) => { e.target.style.display = 'none'; } });
    }
    if (isImage || /\.(png|jpe?g|gif|webp|avif)(\?[^\s]*)?$/i.test(url)) {
      // tap it to see it properly — a 320px-tall crop of someone's
      // photograph is a thumbnail, not the picture they posted
      return h('img', {
        src: url, class: 'note-img clickable', loading: 'lazy', alt: label || '',
        onClick: (e) => { e.stopPropagation(); ctx.openImage && ctx.openImage(url); },
        // a picture we were TOLD was a picture and which won't load leaves
        // nothing behind — the alt text is already in the sentence above it
        onError: (e) => { e.target.style.display = 'none'; },
      });
    }
    if (youtubeId(url)) return youtubeEmbed(url, youtubeId(url));
    const shown = label || (url.length > 64 ? url.slice(0, 61) + '…' : url);
    return h('a', { href: url, target: '_blank', rel: 'noopener noreferrer' }, shown);
  }

  function noteBody(text, depth = 0) {
    const out = [];
    for (const part of String(text || '').split(NOTE_SPLIT)) {
      if (!part) continue;
      const md = MD_PARTS.exec(part);
      if (md) {
        const [, bang, label, url] = md;
        out.push(urlNode(url, { label: label || null, isImage: !!bang }));
      } else if (/^https?:\/\//i.test(part)) {
        out.push(urlNode(part));
      } else if (/^nostr:(npub|nprofile)1/i.test(part)) {
        const ref = parseNostrRef(part.slice(6));
        if (ref && ref.type === 'pubkey') out.push(h('a', { href: '#', onClick: (e) => { e.preventDefault(); openProfile(ref.pk); } }, '@' + displayName(ref.pk)));
        else out.push(h('span', { class: 'faint' }, part.slice(6, 18) + '…'));
      } else if (/^nostr:(note|nevent)1/i.test(part)) {
        const ref = parseNostrRef(part.slice(6));
        if (ref && ref.type === 'event') {
          // the note they're quoting, shown inside what they said about it —
          // except one level down, where it goes back to being a link
          out.push(depth ? h('a', {
            href: '#', onClick: (e) => { e.preventDefault(); e.stopPropagation(); openNoteRef(ref); },
          }, t('noteRefLink')) : quoteCard(ref, depth));
        } else out.push(h('span', { class: 'faint' }, part.slice(6, 18) + '…'));
      } else if (/^nostr:/i.test(part)) {
        out.push(h('span', { class: 'faint' }, part.slice(6, 18) + '…'));
      } else out.push(part);
    }
    return out;
  }

  // Zap a specific note. With a default amount configured this is ONE TAP:
  // the zap fires instantly (ark first, Lightning fallback) and reports by
  // toast, no form, no leaving the page. Without one, a small setup screen
  // asks once and remembers.
  // Whether a ⚡ makes sense for this author from this wallet: not
  // ourselves, and an instant path (Ark) or a Lightning fallback exists.
  const canZapPk = (pk) => !!pk && !isMe(pk) && !!(hook('arkReady') || hook('canLnZap'));
  function zapNote(pk, ev) {
    const npubStr = npubOf(pk);
    const def = ctx.zapDefaultSat ? ctx.zapDefaultSat() : 0;
    if (!def) { ui.zapSetup = { pk, npub: npubStr, eventId: ev.id, amount: '21' }; render(); return; }
    markZapPending(ev.id, def); // the chip answers the tap; the flow reports back
    if (!hook('zapNpub', pk, npubStr, ev.id, def) && !hook('lnZapNpub', pk, npubStr, ev.id, def)) {
      // no instant path in this build — the classic form flow
      settleZap(ev.id, false);
      ui.profilePk = null;
      ui.chatOpen = false;
      ui.tab = 'send';
      render();
      if (!hook('zapNpub', pk, npubStr, ev.id)) hook('lnZapNpub', pk, npubStr, ev.id);
    }
  }

  // First ⚡ tap ever: pick the amount one time, then every zap is one tap.
  function zapSetupScreen() {
    const s = ui.zapSetup;
    return h('div', { class: 'col', style: 'gap:16px' },
      ctx.brandHeader(false),
      h('div', { class: 'card col', style: 'gap:10px' },
        h('h3', { style: 'margin:0' }, '⚡ ' + t('zapSetupTitle')),
        h('div', { class: 'small muted' }, t('zapSetupDesc')),
        h('div', { class: 'input-group' },
          h('input', { type: 'number', min: '1', value: s.amount, onInput: (e) => { s.amount = e.target.value; } }),
          h('span', { class: 'small muted', style: 'align-self:center;padding:0 8px' }, 'sats')),
        h('button', { class: 'btn-primary btn-block', onClick: () => {
          const n = parseInt(s.amount, 10);
          if (!n || n <= 0) { toast(t('enterValidAmtForN', { n: 1 })); return; }
          ctx.setZapDefaultSat(n);
          const { pk, npub, eventId } = s;
          ui.zapSetup = null;
          render();
          markZapPending(eventId, n);
          if (!hook('zapNpub', pk, npub, eventId, n) && !hook('lnZapNpub', pk, npub, eventId, n)) settleZap(eventId, false);
          recheckZap(eventId);
        } }, t('zapSetupSave'))),
      h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.zapSetup = null; render(); } }, t('back')));
  }

  // One post as a feed row (avatar · name · time · body), twitter/jumble
  // style: rows share a scrollable container and are split by hairlines
  // rather than floating in their own cards. Tapping a row opens its thread.
  // ---- what you can do to a post -------------------------------------------
  // Like, boost, quote, and — behind the ellipsis — mute or block its author.
  // Each publishes to the author's own relays as well as ours, so the person
  // being answered actually sees it.
  const myReactOn = (id) => {
    const m = reacts.get(id);
    if (!m) return null;
    const mine = myPubkeys();
    for (const [emoji, who] of m) for (const pk of mine) if (who.has(pk)) return emoji;
    return null;
  };
  const iBoosted = (id) => {
    const set = boosts.get(id);
    return !!set && myPubkeys().some((pk) => set.has(pk));
  };
  const noteRelaysFor = async (ev) =>
    [...new Set([...zapRelays(), ...(await relaysOf(ev.pubkey))])];

  // A like is kind 7 on the note (NIP-25). Tapping it again withdraws it the
  // only way nostr has: a deletion request for the reaction we sent.
  // Reply: open (or re-aim) the thread and put the cursor in the box.
  function replyToNote(ev) {
    if (ui.noteThread && ui.noteThread.rootId === rootIdOf(ev)) {
      ui.noteThread.focusId = ev.id;
      render();
    } else openNoteThread(ev);
    if (ui.noteThread) ui.noteThread.refocus = true;
    setTimeout(() => document.querySelector('.thread-reply-input')?.focus(), 120);
  }

  async function unreact(ev) {
    const id = await requireIdentity();
    const relays = await noteRelaysFor(ev);
    {
      // Taking a like back is the only withdrawal nostr has: a deletion
      // request naming the reaction. Relays that honour it drop it; the ones
      // that don't go on showing it to other people — worth knowing, not
      // worth refusing to try.
      const m = reacts.get(ev.id);
      if (m) for (const [emoji, who] of [...m]) { for (const pk of myPubkeys()) who.delete(pk); if (!who.size) m.delete(emoji); }
      render();
      const mineEv = myReactEv.get(ev.id);
      if (!mineEv) return;
      myReactEv.delete(ev.id);
      const gone = { kind: 5, content: '', created_at: Math.floor(Date.now() / 1000), tags: [['e', mineEv], ['k', '7']] };
      const del = id.signer instanceof Uint8Array ? finalizeEvent(gone, id.signer) : await id.signer.signEvent(gone);
      publishOn(relays, del).catch(() => {});
      return;
    }
  }

  // React with whichever emoji was picked (NIP-25 takes any content).
  async function reactTo(ev, emoji) {
    const id = await requireIdentity();
    const relays = await noteRelaysFor(ev);
    const partial = {
      kind: 7, content: emoji || '❤️', created_at: Math.floor(Date.now() / 1000),
      tags: [['e', ev.id], ['p', ev.pubkey], CLIENT_TAG],
    };
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
    myReactEv.set(ev.id, evt.id);
    noteEvent(evt); // on screen before the relays answer
    render();
    publishOn(relays, evt).catch(() => {});
  }

  // A boost is kind 6 carrying the note it repeats (NIP-18).
  async function boostNote(ev) {
    if (iBoosted(ev.id)) { toast(t('postBoostedAlready')); return; }
    const id = await requireIdentity();
    const relays = await noteRelaysFor(ev);
    const partial = {
      kind: 6, content: JSON.stringify(ev), created_at: Math.floor(Date.now() / 1000),
      tags: [['e', ev.id, relays[0] || '', 'mention'], ['p', ev.pubkey], CLIENT_TAG],
    };
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
    noteEvent(evt);
    render();
    const ok = await publishOn(relays, evt);
    toast(ok ? t('postBoosted') : t('msgSendFailed'));
  }

  // A quote is your own post with theirs referenced inside it: the composer
  // opens with the reference already in the text, and the q tag goes on at
  // publish time so clients can render the embed.
  function quoteNote(ev) {
    ui.quoteOf = { id: ev.id, pubkey: ev.pubkey };
    const ref = 'nostr:' + (neventOf(ev.id, ev.pubkey) || ev.id);
    const cur = composeText().replace(/\s+$/, '');
    const next = (cur ? cur + '\n\n' : '') + ref;
    ui.profCompose = next;
    setDraft(POST_DRAFT, next);
    ui.noteThread = null;
    ui.profilePk = null;
    ui.chatOpen = true;
    ui.msgView = 'feed';
    feedNow();
    render();
    setTimeout(() => { const el = document.querySelector('.chat-page textarea'); if (el) { el.focus(); el.setSelectionRange(0, 0); } }, 80);
  }

  // ---- mute list (NIP-51 kind 10000) ---------------------------------------
  // Muting hides someone's posts everywhere in this app and publishes the
  // list, so it follows you to other clients. Blocking is the same list plus
  // an unfollow — the stronger, more deliberate door.
  const MUTES = 'mutes';
  let mutes = null; // { set, tags, content, at }
  let mutesAt = 0;
  function mutesNow() {
    if (!mutes) {
      let st2 = null;
      try { st2 = wallet.loadFeatureState(MUTES, null); } catch {}
      const tags = (st2 && st2.tags) || [];
      mutes = { set: new Set(pTags(tags).map((x) => x[1])), tags, content: (st2 && st2.c) || '', at: (st2 && st2.at) || 0 };
    }
    return mutes;
  }
  const isMuted = (pk) => mutesNow().set.has(pk);
  function saveMutes(m) {
    mutes = m;
    try { wallet.saveFeatureState(MUTES, { tags: m.tags, c: m.content, at: m.at }); } catch {}
  }
  async function syncMutes({ force = false } = {}) {
    const me = mePk();
    if (!me) return mutesNow();
    if (!force && Date.now() - mutesAt < 10 * 60_000) return mutesNow();
    mutesAt = Date.now();
    try {
      const evs = await queryOn(zapRelays(), { kinds: [10000], authors: [me] }, 5000);
      const newest = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
      const cur = mutesNow();
      if (newest && newest.created_at > cur.at) {
        saveMutes({ set: new Set(pTags(newest.tags).map((x) => x[1])), tags: newest.tags || [], content: newest.content || '', at: newest.created_at });
        scheduleRepaint();
      }
    } catch { mutesAt = 0; }
    return mutesNow();
  }
  // Same care as the follow list: publish onto the freshest copy the relays
  // will give us, preserving anything in it we didn't write (the encrypted
  // content other clients keep their private mutes in, above all).
  async function toggleMute(pk, { block = false } = {}) {
    const id = await requireIdentity();
    if (pk === id.pubkey) return;
    const before = mutesNow();
    saveMutes({ ...before, set: new Set(before.set.has(pk) ? [...before.set].filter((x) => x !== pk) : [...before.set, pk]) });
    render();
    try {
      await syncMutes({ force: true });
      const fetched = mutesNow(); // see the note in toggleFollow
      const base = fetched.at > before.at ? fetched : before;
      const had = base.set.has(pk);
      const tags = had ? base.tags.filter((x) => !(x[0] === 'p' && x[1] === pk)) : [...base.tags, ['p', pk]];
      const created_at = Math.max(Math.floor(Date.now() / 1000), base.at + 1);
      const partial = { kind: 10000, content: base.content || '', created_at, tags };
      const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
      const ok = await publishOn(zapRelays(), evt);
      if (!ok) throw new Error(t('msgSendFailed'));
      saveMutes({ set: new Set(pTags(tags).map((x) => x[1])), tags, content: base.content || '', at: created_at });
      if (block && !had && isFollowing(pk)) await toggleFollow(pk);
      toast(had ? t('postUnmuted') : block ? t('postBlocked') : t('postMuted'));
      render();
    } catch (e) {
      saveMutes(before);
      if (!(e instanceof NoIdentity)) toast(e.message || String(e));
      render();
    }
  }

  // The ellipsis sheet: the actions that don't earn a button of their own.
  function noteSheet() {
    if (!ui.noteSheet) return null;
    const ev = ui.noteSheet;
    const close = () => { ui.noteSheet = null; render(); };
    const mine = isMe(ev.pubkey);
    const item = (icon, label, onClick, danger) => h('button', {
      class: 'btn-block', style: 'text-align:left' + (danger ? ';color:var(--red,#c0392b)' : ''),
      onClick: () => { close(); onClick(); },
    }, icon + '  ' + label);
    return h('div', {
      class: 'confirm-pop-backdrop',
      onClick: (e) => { if (e.target === e.currentTarget) close(); },
    },
      h('div', { class: 'card col confirm-pop', style: 'gap:8px' },
        h('div', { class: 'row gap6', style: 'align-items:center' },
          avatar(ev.pubkey, 'chat-avatar', false),
          h('div', { class: 'chat-name' }, displayName(ev.pubkey))),
        item('❝', t('postQuote'), () => quoteNote(ev)),
        item('↻', t('postBoost'), () => boostNote(ev).catch(() => {})),
        item('⧉', t('copy'), async () => {
          try { await navigator.clipboard.writeText('nostr:' + (neventOf(ev.id, ev.pubkey) || ev.id)); toast(t('copied')); } catch {}
        }),
        mine ? null : item('\u{1F507}', isMuted(ev.pubkey) ? t('postUnmute') : t('postMute'), () => toggleMute(ev.pubkey).catch(() => {})),
        mine || isMuted(ev.pubkey) ? null : item('⛔', t('postBlock'), () => toggleMute(ev.pubkey, { block: true }).catch(() => {}), true),
        h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back'))));
  }

  // The things you can do to a post, in a row of their own across the bottom
  // of it: reply, boost, quote, react, zap. Counts sit beside their own icon,
  // because a count belongs to the thing it counts. Spread across the full
  // width so each is a comfortable target rather than five buttons huddled in
  // a corner.
  const ICON = (d, fill) => '<svg width="19" height="19" viewBox="0 0 24 24" fill="' + (fill ? 'currentColor' : 'none')
    + '" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="display:block">' + d + '</svg>';
  const I_REPLY = ICON('<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>');
  const I_BOOST = ICON('<path d="M17 2.5l3.5 3.5-3.5 3.5"/><path d="M3.5 11.5v-1a4 4 0 0 1 4-4h13"/><path d="M7 21.5L3.5 18 7 14.5"/><path d="M20.5 12.5v1a4 4 0 0 1-4 4h-13"/>');
  const I_QUOTE = ICON('<path stroke="none" d="M7.2 17c.5 0 1-.3 1.2-.7l1.4-2.9c.1-.3.2-.6.2-.9V8c0-.6-.4-1-1-1H6c-.6 0-1 .4-1 1v4c0 .6.4 1 1 1h2l-1 2.1c-.5.9.2 1.9 1.2 1.9zm10 0c.5 0 1-.3 1.2-.7l1.4-2.9c.1-.3.2-.6.2-.9V8c0-.6-.4-1-1-1H16c-.6 0-1 .4-1 1v4c0 .6.4 1 1 1h2l-1 2.1c-.5.9.2 1.9 1.2 1.9z"/>', true);
  const I_HEART = (on) => ICON('<path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 1 0-7.8 7.8l1.1 1L12 21l7.7-7.7 1.1-1a5.5 5.5 0 0 0 0-7.7z"/>', on);
  const I_ZAP = ICON('<path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/>', true);

  function noteActions(pk, ev, { canZap }) {
    const mineReact = myReactOn(ev.id);
    const rm = reacts.get(ev.id);
    const likeN = rm ? [...rm.values()].reduce((n, who) => n + who.size, 0) : 0;
    const boostN = (boosts.get(ev.id) || new Set()).size;
    const btn = (icon, label, count, on, onClick) => h('button', {
      class: 'note-act' + (on ? ' on' : ''), title: label, 'aria-label': label,
      onClick: (e) => { e.stopPropagation(); onClick(); },
    },
      typeof icon === 'string' && icon.startsWith('<svg')
        ? h('span', { style: 'display:flex', html: icon })
        : h('span', { class: 'note-act-emoji' }, icon),
      count ? h('span', { class: 'note-act-n' }, String(count)) : null);
    return h('div', { class: 'row note-acts' },
      btn(I_REPLY, t('msgReply'), 0, false, () => replyToNote(ev)),
      btn(I_BOOST, t('postBoost'), boostN, iBoosted(ev.id), () => boostNote(ev).catch(() => {})),
      btn(I_QUOTE, t('postQuote'), 0, false, () => quoteNote(ev)),
      // tap to choose how you feel about it; tap again to take it back
      btn(mineReact || I_HEART(false), t('postLike'), likeN, !!mineReact,
        () => { if (mineReact) unreact(ev).catch(() => {}); else { ui.reactPick = ev; render(); } }),
      canZap ? btn(I_ZAP, t('zapTitle'), 0, false, () => { zapNote(pk, ev); recheckZap(ev.id); }) : null);
  }

  // The emoji row, same set the chat sheet offers.
  function reactPicker() {
    if (!ui.reactPick) return null;
    const ev = ui.reactPick;
    const close = () => { ui.reactPick = null; render(); };
    return h('div', {
      class: 'confirm-pop-backdrop',
      onClick: (e) => { if (e.target === e.currentTarget) close(); },
    },
      h('div', { class: 'card col msg-sheet' },
        h('div', { class: 'msg-sheet-emojis' },
          REACT_EMOJIS.map((e2) => h('button', {
            onClick: () => { close(); reactTo(ev, e2).catch(() => {}); },
          }, e2))),
        h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back'))));
  }

  function noteRow(pk, ev, name, { open = true, focus = false } = {}) {
    // NOT prefetchProfilePage: that fetches the author's whole page — their
    // kind 0, their relay list, their last thirty notes — and a feed row is
    // not a profile tap. Twenty rows meant sixty requests, which is how the
    // batched profile fetch below ended up starved and the rows settled as
    // punks. The name and face come from the batch; the page loads when the
    // profile is actually opened.
    profileOf(pk);
    const isReply = ev.tags.some((x) => x[0] === 'e');
    const canZap = !isMe(pk) && !!(hook('arkReady') || hook('canLnZap'));
    // an optimistic post mid-publish: visible but not yet a real event —
    // dimmed, and no thread/reply/zap until its signed self takes over
    const pending = !!ev.pending;
    const openable = open && !pending;
    if (!pending) watchZaps([ev.id]);
    return h('div', {
      class: 'row',
      style: 'gap:10px;align-items:flex-start;padding:10px 0'
        + (openable ? ';cursor:pointer' : '')
        + (pending ? ';opacity:.55' : '')
        + (focus ? ';background:var(--accent-soft,rgba(128,128,128,.08));border-radius:8px;padding-left:8px;padding-right:8px;margin:0 -8px' : ''),
      // closest('button') guard: on touch, a ⚡ tap must never double as a
      // row tap even if propagation quirks let the click reach us
      onClick: openable ? (e) => { if (e.target && e.target.closest && e.target.closest('button')) return; openNoteThread(ev); } : undefined,
    },
      // the avatar is its own tap-target (profile), even inside an openable
      // row — its handler stops propagation, so the row still opens the thread
      avatar(pk, 'chat-avatar note-avatar'),
      h('div', { class: 'col grow', style: 'min-width:0;gap:3px' },
        h('div', { class: 'row between', style: 'align-items:center;gap:8px' },
          h('div', { class: 'row', style: 'gap:7px;align-items:baseline;min-width:0' },
            h('span', {
              // the name, like the avatar, is its own tap-target (profile)
              style: 'font-weight:600;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;cursor:pointer',
              onPointerdown: () => { try { prefetchProfilePage(pk); } catch {} },
              onClick: (e) => { e.stopPropagation(); openProfile(pk); },
            }, name),
            h('span', { class: 'small faint', style: 'white-space:nowrap' },
              (isReply ? '↩ ' + t('profReplyTag') + ' · ' : '') + timeLabel(ev.created_at * 1000)),
            zapChip(ev.id, { onClick: canZap ? () => { zapNote(pk, ev); recheckZap(ev.id); } : null })),
          pending ? null : h('button', {
            // the overflow stays up here; reply, boost, quote, react and zap
            // are a row of their own under the post
            class: 'btn-sm', title: t('postMore'), 'aria-label': t('postMore'),
            style: 'flex-shrink:0',
            onClick: (e) => { e.stopPropagation(); ui.noteSheet = ev; render(); },
          }, '\u22ef')),
        h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, ...noteBody(ev.content)),
        pending ? null : noteActions(pk, ev, { canZap })));
  }

  // ---- thread view: a note in its conversation ----------------------------
  const threadCache = new Map(); // root id -> { status, root, replies }
  const noteSep = () => h('div', { style: 'height:1px;background:var(--border,rgba(128,128,128,.18));margin:0 -14px' });
  function rootIdOf(ev) {
    const es = ev.tags.filter((x) => x[0] === 'e');
    const marked = es.find((x) => x[3] === 'root');
    return (marked || es[0] || [])[1] || ev.id;
  }
  function threadFor(seed) {
    const rootId = rootIdOf(seed);
    let c = threadCache.get(rootId);
    if (c) return c;
    c = { status: 'loading', rootId, root: seed.id === rootId ? seed : null, replies: [] };
    threadCache.set(rootId, c);
    (async () => {
      // the conversation's home relays are the root author's (NIP-10 outbox);
      // the seed's author is the best guess until the root is known
      const relays = await notesRelays((c.root || seed).pubkey);
      const [roots, replies] = await Promise.all([
        c.root ? Promise.resolve([]) : queryOn(relays, { kinds: [1], ids: [rootId] }, 4000),
        queryOn(relays, { kinds: [1], '#e': [rootId], limit: 80 }, 4500),
      ]);
      if (!c.root) c.root = (roots || [])[0] || null;
      const seen = new Set([rootId]);
      c.replies = (replies || [])
        .filter((e) => !seen.has(e.id) && seen.add(e.id))
        .sort((a, b) => a.created_at - b.created_at);
      c.status = 'ready';
      if (ui.noteThread && ui.noteThread.rootId === rootId) {
        render();
        // The inline reply box may have MOVED on this render (it slots under
        // the focused note once that note exists) — a focus taken before the
        // load finished died with the old position. Re-take it if the reply
        // button asked for it.
        if (ui.noteThread.refocus) {
          ui.noteThread.refocus = false;
          setTimeout(() => document.querySelector('.thread-reply-input')?.focus(), 30);
        }
      }
    })().catch(() => {
      c.status = 'ready';
      if (ui.noteThread && ui.noteThread.rootId === rootId) render();
    });
    return c;
  }
  function openNoteThread(ev) {
    ui.noteThread = { rootId: rootIdOf(ev), focusId: ev.id, seed: ev };
    ui.profOverThread = false; // a freshly opened thread goes on top
    render();
  }
  // A nostr:nevent / nostr:note reference: the thread loader needs the real
  // event (its tags name the root, its author names the home relays), so
  // fetch it by id — the reference's relay hints first — then open.
  async function openNoteRef(ref) {
    toast(t('noteRefLoading'));
    const relays = [...new Set([...(ref.relays || []), ...NOTE_RELAYS])];
    const evs = await queryOn(relays, { ids: [ref.id] }, 4000).catch(() => []);
    const ev = (evs || [])[0];
    if (ev) openNoteThread(ev);
    else toast(t('noteRefNotFound'));
  }
  // Publish a kind-1 reply to the focused note (NIP-10 markers), addressed to
  // the conversation's own relays plus ours, and shown optimistically.
  // A new top-level kind-1 note, published to the identity's own relays —
  // the profile page's compose button. OPTIMISTIC: a provisional copy sits
  // at the top of the feed before any signing or relay round-trip (a remote
  // signer alone can take seconds), swapped for the signed event on success
  // and withdrawn on failure.
  async function publishPost(text, media = []) {
    const id = await requireIdentity();
    const temp = {
      id: 'pending:' + Math.random().toString(36).slice(2),
      pubkey: id.pubkey, content: text, created_at: Math.floor(Date.now() / 1000),
      tags: [], pending: true,
    };
    const caches = [...new Set([id.pubkey, ui.profilePk].filter(Boolean))]
      .map((pk) => notesCache.get(pk)).filter(Boolean);
    for (const c of caches) c.notes = [temp, ...c.notes];
    // your own post belongs at the top of your own feed too, before any
    // relay has heard of it
    if (feed) { feed.notes = [temp, ...feed.notes]; }
    render();
    try {
      // NIP-92: what we uploaded, described, so clients needn't sniff the URL
      const imeta = media.filter((m) => m && m.url)
        .map((m) => ['imeta', 'url ' + m.url, ...(m.m ? ['m ' + m.m] : [])]);
      // NIP-18 quote: the reference is already in the text; the tags let a
      // client render the quoted post inline and tell its author
      const q = ui.quoteOf && text.includes(ui.quoteOf.id.slice(0, 8))
        ? [] : ui.quoteOf ? [['q', ui.quoteOf.id], ['p', ui.quoteOf.pubkey]] : [];
      const partial = { kind: 1, content: text, created_at: temp.created_at, tags: [...imeta, ...q, CLIENT_TAG] };
      const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
      const relays = [...new Set([...(await notesRelays(id.pubkey)), ...wallet.nostrRelays()])];
      const ok = await publishOn(relays, evt);
      if (!ok) throw new Error(t('msgSendFailed'));
      ui.quoteOf = null;
      for (const c of caches) c.notes = c.notes.map((e) => (e.id === temp.id ? evt : e));
      if (feed) feed.notes = feed.notes.map((e) => (e.id === temp.id ? evt : e));
      render();
      return evt;
    } catch (e) {
      for (const c of caches) c.notes = c.notes.filter((e) => e.id !== temp.id);
      if (feed) feed.notes = feed.notes.filter((e) => e.id !== temp.id);
      render();
      throw e;
    }
  }

  async function publishReply(c, s, text) {
    const id = await requireIdentity();
    const target = c.replies.find((e) => e.id === s.focusId) || c.root || s.seed;
    const rootId = c.rootId;
    const pTags = [...new Set([
      target.pubkey,
      ...(c.root ? [c.root.pubkey] : []),
      ...target.tags.filter((x) => x[0] === 'p' && /^[0-9a-f]{64}$/.test(x[1] || '')).map((x) => x[1]),
    ])].filter((pk) => pk !== id.pubkey).slice(0, 8);
    const imeta = (ui.postMedia || []).filter((m) => m && m.url && text.includes(m.url))
      .map((m) => ['imeta', 'url ' + m.url, ...(m.m ? ['m ' + m.m] : [])]);
    const partial = {
      kind: 1,
      content: text,
      created_at: Math.floor(Date.now() / 1000),
      tags: [
        ['e', rootId, '', 'root'],
        ...(target.id !== rootId ? [['e', target.id, '', 'reply']] : []),
        ...pTags.map((pk) => ['p', pk]),
        ...imeta,
        CLIENT_TAG,
      ],
    };
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
    const relays = [...new Set([...(await notesRelays(target.pubkey)), ...wallet.nostrRelays()])];
    const ok = await publishOn(relays, evt);
    if (!ok) throw new Error(t('msgSendFailed'));
    c.replies = [...c.replies, evt];
    return evt;
  }

  function threadScreen() {
    const s = ui.noteThread;
    const c = threadFor(s.seed);
    const row = (ev) => noteRow(ev.pubkey, ev, displayName(ev.pubkey), { open: false, focus: ev.id === s.focusId && ev.id !== c.rootId });
    // The reply box sits INLINE, right under the note it answers — it used
    // to live at the bottom of the thread, where nobody scrolled to find it.
    const replyBox = () => h('div', { class: 'col', style: 'gap:8px;padding:2px 0 10px' },
      s.preview ? draftPreview(s.draft) : null,
      h('div', { class: 'row', style: 'gap:8px;align-items:center' },
      h('input', {
        type: 'text', class: 'grow thread-reply-input', placeholder: t('threadReplyHint'),
        value: s.draft || '',
        // a render per keystroke only while the preview is open; the morph
        // leaves a focused field alone, so this can't fight the typing
        onInput: (e) => { s.draft = e.target.value; if (s.preview) render(); },
        onKeydown: (e) => { if (e.key === 'Enter') e.target.closest('.col').querySelector('.thread-reply-send')?.click(); },
      }),
      // A reply can carry a picture too — same upload, same imeta tag, same
      // paperclip. The URL lands in the draft, which is what every client
      // reads as the media.
      ctx.uploadImage ? h('button', {
        class: 'attach-btn', title: t('feedAttach'), 'aria-label': t('feedAttach'), disabled: !!ui.postUploading,
        onClick: () => document.getElementById('reply-file')?.click(),
      }, ui.postUploading ? h('span', { class: 'spinner sm' }) : h('span', { style: 'display:flex', html: CLIP })) : null,
      h('input', {
        type: 'file', id: 'reply-file', accept: 'image/*,video/*', style: 'display:none',
        onChange: async (e) => {
          const f = e.target.files && e.target.files[0];
          e.target.value = '';
          await attachTo(f, (url) => {
            s.draft = ((s.draft || '').replace(/\s+$/, '') + ' ' + url).trim();
            const inp = document.querySelector('.thread-reply-input');
            if (inp) inp.value = s.draft;
            s.preview = true; // same as the composer: show what was attached
          });
        },
      }),
      previewBtn(!!s.preview, () => { s.preview = !s.preview; render(); }),
      h('button', {
        class: 'btn-primary thread-reply-send', disabled: !!s.sending || !!ui.postUploading,
        onClick: async () => {
          const text = (s.draft || '').trim();
          if (!text) return;
          s.sending = true; render();
          try {
            await publishReply(c, s, text);
            s.draft = '';
            ui.postMedia = (ui.postMedia || []).filter((m) => !text.includes(m.url));
            // the input may still be focused, and the morph won't touch a
            // focused field's value — clear it by hand
            const inp = document.querySelector('.thread-reply-input');
            if (inp) inp.value = '';
            toast(t('threadReplied'));
          } catch (e) { if (!e.silent) toast(e.message); }
          s.sending = false; render();
        },
      }, s.sending ? h('span', { class: 'spinner sm' }) : t('threadReplySend'))));
    // rows with the reply box slotted under the focused note (the root when
    // nothing narrower is focused; appended at the end if the focused note
    // hasn't loaded yet, so the box never disappears entirely)
    const kids = [];
    let boxPlaced = false;
    const place = (ev) => {
      if (boxPlaced) return;
      if (ev.id === s.focusId || (!s.focusId && c.root && ev.id === c.root.id)) {
        kids.push(replyBox());
        boxPlaced = true;
      }
    };
    if (c.root) { kids.push(row(c.root)); place(c.root); }
    else {
      kids.push(h('div', { class: 'small faint', style: 'padding:10px 0' },
        c.status === 'loading' ? '…' : t('threadRootMissing')));
    }
    for (const ev of c.replies) { kids.push(noteSep(), row(ev)); place(ev); }
    if (c.status === 'loading') kids.push(h('div', { class: 'row', style: 'justify-content:center;padding:12px' }, h('span', { class: 'spinner sm' })));
    else if (!c.replies.length) kids.push(h('div', { class: 'small faint', style: 'text-align:center;padding:10px 0' }, t('threadNoReplies')));
    if (!boxPlaced) kids.push(replyBox());
    return h('div', { class: 'col', style: 'gap:16px' },
      // full header: search/chat/settings stay reachable mid-thread (only
      // the public no-wallet surface drops the action row)
      ctx.brandHeader(!ui.pubProf && wallet.loaded),
      h('div', { class: 'card col', style: 'gap:0;padding:2px 14px' }, ...kids),
      h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.noteThread = null; render(); } }, t('back')));
  }

  async function publishProfileFields(fields, opts = {}) {
      const id = await requireIdentity();
      const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [id.pubkey] }, 3000);
      const newest = evs.sort((a, b) => b.created_at - a.created_at)[0];
      let base = {};
      try { base = newest ? JSON.parse(newest.content) : {}; } catch {}
      if (opts.onlyWhen && !opts.onlyWhen(base)) return true; // condition says leave it be
      const merged = { ...base };
      // fillOnly fields are offers, not orders: the onboarding wizard suggests
      // a name and a punk for profiles that have none — it must never RENAME
      // (or re-face) an identity that already has one.
      const fill = new Set(opts.fillOnly || []);
      const taken = (k) => (k === 'name' ? !!(base.name || base.display_name) : !!base[k]);
      for (const [k, v] of Object.entries(fields || {})) {
        if (!v) continue;
        if (fill.has(k) && taken(k)) continue;
        if (opts.fieldWhen && opts.fieldWhen[k] && !opts.fieldWhen[k](base)) continue;
        merged[k] = v;
      }
      if (merged.name && !(fill.has('name') && taken('name'))) merged.display_name = merged.name;
      if (JSON.stringify(merged) === JSON.stringify(base)) return true; // nothing to say
      const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: Math.floor(Date.now() / 1000) };
      const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
      const ok = await publishOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], evt);
      if (!ok) throw new Error(t('msgSendFailed'));
      fullProfiles.set(id.pubkey, merged);
      profiles.set(id.pubkey, { name: merged.name || null, picture: merged.picture || null, t: Date.now() });
      return true;
    }

  async function saveProfile() {
    const id = await identity();
    if (!id) { noIdToast(); return; }
    const e = ui.profEdit;
    e.migrationName = null;
    ui.profSaving = true;
    render();
    try {
      // merge over the newest published kind 0 so unknown fields round-trip
      const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [id.pubkey] }, 3000);
      const newest = evs.sort((a, b) => b.created_at - a.created_at)[0];
      let base = {};
      try { base = newest ? JSON.parse(newest.content) : {}; } catch {}
      // A changed username claims first — if the name is taken (or invalid)
      // the save stops here and the editor stays open to fix it.
      const oldAddr = hook('namesAddress');
      let addr = oldAddr;
      const want = (e.uname || '').trim().toLowerCase();
      if (oldAddr && want && want !== oldAddr.split('@')[0]) {
        if (!/^[a-z0-9][a-z0-9._-]{0,29}$/.test(want)) throw new Error(t('profUnameInvalid'));
        await hook('namesClaimName', want, { quietProfile: true });
        addr = want + '@' + oldAddr.split('@')[1];
      }
      const merged = { ...base };
      for (const [k, v] of [['name', e.name], ['about', e.about], ['picture', e.picture], ['banner', e.banner]]) {
        if (v.trim()) merged[k] = v.trim();
        else delete merged[k];
      }
      // The address doubles as the lightning address and NIP-05. Fill them
      // when empty; move them when they pointed at our (old) address. A
      // deliberately foreign lud16/nip05 is the user's business.
      if (addr) {
        for (const k of ['lud16', 'nip05'])
          if (!merged[k] || merged[k] === oldAddr) merged[k] = addr;
      }
      if (merged.name) merged.display_name = merged.name;
      const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: Math.floor(Date.now() / 1000) };
      const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
      const ok = await publishOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], evt);
      if (!ok) throw new Error(t('msgSendFailed'));
      fullProfiles.set(id.pubkey, merged);
      profiles.set(id.pubkey, { name: merged.name || null, picture: merged.picture || null });
      ui.profEdit = null; ui.profEditFilled = false;
      toast(t('profSaved'));
    } catch (err) {
      if (ui.profEdit === e && e.uname === err.migrationName) e.migrationName = err.migrationName;
      toast(err.message || String(err));
    } finally {
      ui.profSaving = false;
      render();
    }
  }

  function profileScreen() {
    const pk = ui.profilePk;
    const mine = isMe(pk) || (ctx.shownPubkey && pk === ctx.shownPubkey());
    // History can outlive an account switch; only restore our own editor.
    if (!mine && ui.profEdit) { ui.profEdit = null; ui.profEditFilled = false; }
    const logoutBtn = () => h('button', {
      class: 'btn-block', style: 'color:var(--red,#c0392b);display:flex;align-items:center;justify-content:center;gap:8px',
      onClick: () => { ui.logoutConfirm = true; render(); },
    },
      h('span', { style: 'display:flex', html: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>' }),
      t('logout'));
    // One Log out button; the popup offers the two exits — leave (wallets
    // stay saved, one unlock away) or leave and take everything with you.
    // The full wipe still routes through the Delete-all warning after this.
    // Two stages in one popup: the plain logout choices, then — if "forget
    // all data" is picked — the delete-everything warning right here. The old
    // flow detoured to the Accounts page for that confirmation, which read
    // as broken navigation (and left people thinking data was wiped when
    // only a confirm screen had opened).
    const logoutPop = () => !ui.logoutConfirm ? null : h('div', {
      class: 'confirm-pop-backdrop',
      onClick: (e) => { if (e.target === e.currentTarget) { ui.logoutConfirm = null; render(); } },
    },
      ui.logoutConfirm === 'forget'
        ? h('div', { class: 'card col confirm-pop', style: 'gap:10px' },
            h('h3', { style: 'margin:0' }, t('logoutForget') + '?'),
            h('div', { class: 'notice err small' }, t('clearAllWarn')),
            h('button', {
              class: 'btn-block', style: 'color:var(--red,#c0392b)',
              onClick: () => { ui.logoutConfirm = null; ctx.logoutForget(); },
            }, t('clearAll')),
            h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.logoutConfirm = true; render(); } }, t('back')))
        : h('div', { class: 'card col confirm-pop', style: 'gap:10px' },
            h('h3', { style: 'margin:0' }, t('logout') + '?'),
            h('p', { class: 'small muted', style: 'margin:0' }, t('logoutPopBlurb')),
            h('button', { class: 'btn-primary btn-block', onClick: () => {
              ui.logoutConfirm = null;
              ui.profilePk = null; ui.profEdit = null; ui.profEditFilled = false;
              ctx.logout && ctx.logout();
            } }, t('logout')),
            ctx.logoutForget ? h('button', {
              class: 'btn-block', style: 'color:var(--red,#c0392b)',
              onClick: () => { ui.logoutConfirm = 'forget'; render(); },
            }, t('logoutForget')) : null,
            h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.logoutConfirm = null; render(); } }, t('back'))));
    // The identity switcher: every account signed in on this device as an
    // avatar + name row (tap = switch, nothing logged out), and the door to
    // add a new one.
    const switchPop = () => {
      if (!ui.switchIdPop) return null;
      const close = () => { ui.switchIdPop = null; render(); };
      const others = (ctx.identities ? ctx.identities() : []).filter((x) => !x.active);
      return h('div', {
        class: 'confirm-pop-backdrop',
        onClick: (e) => { if (e.target === e.currentTarget) close(); },
      },
        h('div', { class: 'card col confirm-pop', style: 'gap:10px' },
          h('h3', { style: 'margin:0' }, t('switchIdentityTitle')),
          h('p', { class: 'small muted', style: 'margin:0' }, t('switchIdentityDesc')),
          h('div', { class: 'col', style: 'gap:0' },
            others.map((x) => h('div', {
              class: 'row gap6 clickable', style: 'align-items:center;padding:8px 0;border-bottom:1px solid var(--line)',
              onClick: () => { ui.switchIdPop = null; ctx.switchIdentity(x.id); },
            },
              x.pk ? avatar(x.pk, 'chat-avatar', false) : h('div', { class: 'chat-avatar fallback' }),
              h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
                h('div', { class: 'chat-name', style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, x.pk ? displayName(x.pk) : x.label),
                h('div', { class: 'small muted', style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap' },
                  (x.pk ? x.label : t('identityNoKey'))
                  + (x.network && x.network !== 'mainnet' ? ' · ' + x.network : '')
                  + (x.watch ? ' · ' + t('watchOnlyTag') : '')))))),
          h('button', { class: 'btn-primary btn-block', onClick: () => { ui.switchIdPop = null; ctx.signInAnother(); } }, t('signInNew')),
          h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back'))));
    };
    const full = fullProfiles.get(pk);
    // Your own profile reads like anyone else's — npub, bio, latest posts —
    // with the editor behind an explicit Edit button (it used to BE the
    // page, which made looking at your own profile feel like a form). The
    // seed comes from the local name/picture cache so the form opens
    // instantly; saveProfile re-fetches the newest kind 0 before merging,
    // so a stale seed can't clobber anything.
    const myAddr = mine ? hook('namesAddress') : null;
    const openEditor = () => {
      const p = (full === undefined ? profileOf(pk) : full) || {};
      ui.profEdit = {
        uname: myAddr ? myAddr.split('@')[0] : '',
        name: (full || {}).display_name || p.name || '',
        about: p.about || '',
        picture: p.picture || '',
        banner: (full || {}).banner || '',
      };
      ui.profEditFilled = full !== undefined;
      render();
    };
    // Once the real kind 0 lands, top up fields still sitting empty — never
    // ones the user (or the cache) already filled.
    if (mine && ui.profEdit && !ui.profEditFilled && full !== undefined) {
      ui.profEditFilled = true;
      const e = ui.profEdit;
      if (!e.name && !e.touched?.name) e.name = full.display_name || full.name || '';
      for (const key of ['about', 'picture', 'banner'])
        if (!e[key] && !e.touched?.[key]) e[key] = full[key] || '';
    }
    const name = displayName(pk);
    const npub = npubOf(pk) || pk;
    const field = (label, key, ph = '', multi = false) => h('label', { class: 'field' },
      h('span', { class: 'lab' }, label),
      h(multi ? 'textarea' : 'input', {
        ...(multi ? { rows: '4', style: 'font-family:var(--sans);min-height:72px' } : { type: 'text' }),
        placeholder: ph, value: ui.profEdit[key],
        // render per keystroke so the page-top preview (name/picture/banner)
        // tracks the draft live — the morph never rewrites a focused field,
        // so this can't fight the typing
        onInput: (ev) => {
          ui.profEdit[key] = ev.target.value;
          (ui.profEdit.touched ||= {})[key] = true;
          render();
        },
      }));
    // A lightning address worth showing: not an npub-shaped machine address
    // (npub1…@some.relay duplicates the npub below) and not the same string
    // as the nip05 already on screen.
    // The address must not wait for the kind 0: our own claimed name is
    // authoritative locally, a deep link carries the address in the URL
    // (seeded as `addr`), and the light cache remembers it from last time.
    const lp = profileOf(pk) || {};
    const rawNip05 = (full && full.nip05) || (mine && myAddr) || lp.nip05 || lp.addr || null;
    const nip05 = rawNip05 ? String(rawNip05).replace(/^_@/, '') : null;
    const lud16 = (full && full.lud16 ? String(full.lud16) : null) || lp.lud16 || null;
    const showLud = lud16 && !/^npub1/i.test(lud16) && lud16 !== nip05;
    // an about of "~" or a lone character is noise, not a bio.
    // Until the full kind 0 lands, the light profile cache answers — it was
    // filled by the same batched fetch that named this person in the feed,
    // so the bio is already in hand and the page doesn't grow a paragraph
    // half a second after it opens. Once `full` is known it is the truth,
    // including when it says there is no bio.
    const about = full !== undefined
      ? (typeof full.about === 'string' ? full.about.trim() : '')
      : (typeof lp.about === 'string' ? lp.about.trim() : '');
    const showAbout = about.length > 1;
    // The cover photo: nostr's standard kind-0 `banner`. Legacy coinos.io
    // wore these proudly — migrated accounts bring theirs along, and anyone
    // can set one in the editor below. WHILE EDITING, the draft is the
    // truth: an uploaded (or pasted) picture/banner previews immediately at
    // the top of the page instead of waiting for Save — and clearing a field
    // previews the removal too.
    const draft = mine && ui.profEdit ? ui.profEdit : null;
    const urlish = (s) => (typeof s === 'string' && /^https?:\/\//i.test(s.trim()) ? s.trim() : null);
    const bannerUrl = draft ? urlish(draft.banner)
      : full !== undefined ? urlish(full.banner)
      // same as the bio: the cached copy holds the space so the whole page
      // doesn't drop by the height of a cover photo when it arrives
      : urlish(lp.banner);
    const draftPic = draft && urlish(draft.picture);
    return h('div', { class: 'col', style: 'gap:16px' },
      // full header on profiles too — losing the search button here made
      // finding the NEXT person a trek back home
      ctx.brandHeader(!ui.pubProf && wallet.loaded),
      h('div', { class: 'card col', style: 'gap:12px' },
        bannerUrl ? h('div', { class: 'profile-banner', style: `background-image:url(${JSON.stringify(bannerUrl)})` }) : null,
        h('div', { class: 'row gap6', style: 'align-items:center' },
          draftPic
            ? h('div', { class: 'chat-avatar profile-avatar ava-img', style: `background-image:url(${JSON.stringify(draftPic)})` })
            : avatar(pk, 'chat-avatar profile-avatar', false),
          h('div', { class: 'col grow', style: 'min-width:0;gap:2px' },
            h('div', { class: 'chat-title' }, draft && draft.name.trim() ? draft.name.trim() : name),
            nip05 ? h('div', { class: 'muted small break' }, nip05) : null,
            showLud ? h('div', { class: 'muted small break' }, '⚡ ' + lud16) : null,
            // the hat pitch lives beside the avatar it decorates
            mine ? hook('hatShopEntry') : null)),
        // no spinner while the kind 0 loads — prefetch keeps this rare, and
        // an empty beat reads calmer than a spinner
        // The bio rides the same renderer as notes: npub mentions become
        // @names, other nostr: refs truncate to stubs, URLs linkify — and
        // overflow-wrap catches any remaining unbreakable token (a raw npub
        // in a bio was punching clean through the card).
        showAbout && !ui.profEdit
          ? h('p', { class: 'small', style: 'margin:0;white-space:pre-wrap;overflow-wrap:anywhere' },
              ...noteBody(about.slice(0, 1000)))
          : null,
        // the npub, tap to copy — on every profile including your own; it
        // only steps aside while the (long) edit form is open
        ui.profEdit ? null : h('button', {
          class: 'addr-box break npub-box', title: t('copy'),
          style: 'font-size:11px;cursor:pointer;text-align:left;width:100%',
          onClick: async () => { try { await navigator.clipboard.writeText(npub); toast(t('copied')); } catch {} },
        }, npub),
        ui.profEdit
          ? h('div', { class: 'col', style: 'gap:8px' },
              // the username IS the payment address and NIP-05 — the frozen
              // @domain suffix is there so people make that connection
              myAddr ? h('label', { class: 'field' },
                h('span', { class: 'lab' }, t('profUsername')),
                h('div', { class: 'row', style: 'align-items:center;gap:0' },
                  h('input', {
                    type: 'text', style: 'flex:1;min-width:0',
                    autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
                    value: ui.profEdit.uname,
                    onInput: (ev) => {
                      ui.profEdit.uname = ev.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, '');
                      ev.target.value = ui.profEdit.uname;
                      ui.profEdit.migrationName = null;
                      render();
                    },
                  }),
                  h('span', { class: 'muted', style: 'white-space:nowrap;padding:0 8px' }, '@' + myAddr.split('@')[1]))) : null,
              // Offered only for a submitted name confirmed as legacy-only.
              ui.profEdit.migrationName && ui.profEdit.migrationName === ui.profEdit.uname
                && myAddr && myAddr.split('@')[1] === 'coinos.io' ? h('button', {
                type: 'button', class: 'linklike small', style: 'align-self:flex-start',
                onClick: () => {
                  location.href = `https://coinos.io/migrate?to=${encodeURIComponent(myAddr)}&back=${encodeURIComponent(location.origin + '/')}`;
                },
              }, t('onbHaveCoinos')) : null,
              field(t('profDisplayName'), 'name'),
              field(t('profAbout'), 'about', '', true),
              field(t('profPicture'), 'picture', 'https://…'),
              // or skip the URL entirely: pick a photo, we upload and fill it
              h('div', { class: 'row gap6' },
                h('button', {
                  class: 'btn-sm', type: 'button', disabled: !!ui.profUploading,
                  onClick: () => document.getElementById('prof-pic-file')?.click(),
                }, ui.profUploading ? h('span', { class: 'spinner sm' }) : t('profUploadPic')),
                h('input', {
                  id: 'prof-pic-file', type: 'file', accept: 'image/*', style: 'display:none',
                  onChange: async (e) => {
                    const f = e.target.files && e.target.files[0];
                    e.target.value = '';
                    if (!f || !ctx.uploadImage) return;
                    ui.profUploading = true; render();
                    try { if (ui.profEdit) ui.profEdit.picture = await ctx.uploadImage(f); }
                    catch (err) { toast(err.message); }
                    ui.profUploading = false; render();
                  },
                })),
              field(t('profBanner'), 'banner', 'https://…'),
              h('div', { class: 'row gap6' },
                h('button', {
                  class: 'btn-sm', type: 'button', disabled: !!ui.profUploading,
                  onClick: () => document.getElementById('prof-banner-file')?.click(),
                }, ui.profUploading ? h('span', { class: 'spinner sm' }) : t('profUploadBanner')),
                h('input', {
                  id: 'prof-banner-file', type: 'file', accept: 'image/*', style: 'display:none',
                  onChange: async (e) => {
                    const f = e.target.files && e.target.files[0];
                    e.target.value = '';
                    if (!f || !ctx.uploadImage) return;
                    ui.profUploading = true; render();
                    try { if (ui.profEdit) ui.profEdit.banner = await ctx.uploadImage(f); }
                    catch (err) { toast(err.message); }
                    ui.profUploading = false; render();
                  },
                })),
              h('button', { class: 'btn-primary btn-block', disabled: ui.profSaving, onClick: saveProfile },
                ui.profSaving ? h('span', { class: 'spinner sm' }) : t('save')),
              h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.profEdit = null; ui.profEditFilled = false; render(); } }, t('cancel')))
          : mine
            ? h('div', { class: 'col', style: 'gap:8px' },
                h('div', { class: 'row gap6 wrap' },
                  h('button', { class: 'btn-primary grow', onClick: openEditor }, t('profEdit')),
                  h('button', { class: 'grow', onClick: () => { ui.profCompose = ui.profCompose == null ? draftFor(POST_DRAFT) : null; render(); } }, t('profNewPost'))),
                // The post draft rides the same persisted draft store as DMs
                // and channels: a reload (say, to reconnect a signer) brings
                // the half-written post back, composer open. Posting clears
                // it; Cancel just closes the composer and keeps the text.
                postComposer(),
                // the non-destructive way out: add another identity (Nostr,
                // passkey, Google) next to this one and switch between them
                // on the Accounts screen — logout stays for actually leaving
                ctx.signInAnother ? h('button', {
                  class: 'btn-block', style: 'display:flex;align-items:center;justify-content:center;gap:8px',
                  onClick: () => {
                    // other identities on this device → pick from a list;
                    // none yet → straight to the sign-in doors
                    const others = ctx.identities ? ctx.identities().filter((x) => !x.active) : [];
                    if (others.length) { ui.switchIdPop = true; render(); } else ctx.signInAnother();
                  },
                },
                  h('span', { style: 'display:flex', html: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>' }),
                  t('signInAnother')) : null,
                logoutBtn())
            : ui.pubProf
              ? null // no wallet open: messaging and paying both need one
              : h('div', { class: 'row gap6 wrap' },
                h('button', { class: 'btn-primary grow', onClick: () => {
                  const peer = pk;
                  ui.profilePk = null;
                  ui.chatOpen = true;
                  ui.msgView = 'dm';
                  ui.msgPeer = peer;
                  ui.msgStick = true;
                  render();
                } }, t('msgDmsTitle')),
                h('button', { class: 'grow', onClick: () => {
                  const npubStr = npubOf(pk);
                  // leave the whole messaging surface, not just the profile —
                  // a lingering search or thread would win the screen router
                  // and the Send tab would never appear
                  ui.profilePk = null;
                  ui.profOverThread = false;
                  ui.noteThread = null;
                  ui.userSearch = null;
                  ui.chatOpen = false;
                  ui.tab = 'send';
                  render();
                  hook('matchSendText', npubStr);
                } }, t('profPay')),
                // Follow: their posts join your feed, and the service worker
                // learns to treat their DMs as a friend's rather than a
                // stranger's.
                h('button', {
                  class: (isFollowing(pk) ? 'btn-ghost ' : '') + 'grow', disabled: followsPub,
                  onClick: () => toggleFollow(pk),
                }, isFollowing(pk) ? t('feedFollowing') : t('feedFollow')))),
      // Their public notes: the PAGE scrolls (no inner scrollbox), older
      // pages stream in as you near the bottom (the init() scroll listener →
      // loadOlderNotes), and on phones the feed goes full-bleed — edge to
      // edge, no card walls (see .notes-feed).
      (() => {
        const c = notesFor(pk);
        // while loading with nothing to show: an invisible copy of the
        // empty-state line holds the height, so the page doesn't jump when
        // the answer lands (no spinner). With posts already in hand — from
        // the feed we came from — those are shown instead of the blank.
        if (c.status === 'loading' && !c.notes.length)
          return h('div', { class: 'small faint', style: 'text-align:center;visibility:hidden' }, t('profNotesNone'));
        if (!c.notes.length)
          return h('div', { class: 'small faint', style: 'text-align:center' }, t('profNotesNone'));
        return h('div', { class: 'col', style: 'gap:8px' },
          h('div', { class: 'small muted', style: 'padding:0 2px' }, t('profNotesTitle')),
          h('div', { class: 'card col notes-feed', style: 'gap:0' },
            ...c.notes.flatMap((ev, i) => [
              i ? h('div', { style: 'height:1px;background:var(--border,rgba(128,128,128,.18));margin:0 -14px' }) : null,
              noteRow(pk, ev, name),
            ])),
          c.loadingMore
            ? h('div', { class: 'row gap6', style: 'justify-content:center;padding:4px 0' },
                h('span', { class: 'spinner sm' }))
            : null);
      })(),
      h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.profilePk = null; ui.profOverThread = false; ui.pubProf = null; ui.profEdit = null; ui.profEditFilled = false; ui.profCompose = null; render(); } }, t('back')),
      mine ? logoutPop() : null,
      mine ? switchPop() : null);
  }

  const backBtn = (onClick) => h('button', { class: 'iconbtn chat-back', onClick }, '‹');

  // ---- the post composer ----------------------------------------------------
  // Shared by the profile page and the feed. A picture is uploaded the moment
  // it's picked and its URL appended to the text — which is how every nostr
  // client reads media — with a NIP-92 imeta tag published beside it for the
  // ones that would rather have the metadata than sniff the URL.
  const composeText = () => (ui.profCompose == null ? draftFor(POST_DRAFT) : ui.profCompose || '');
  // Upload, then hand the URL to whichever draft asked for it.
  async function attachTo(file, place) {
    if (!file || !ctx.uploadImage) return;
    ui.postUploading = true; render();
    try {
      const url = await ctx.uploadImage(file);
      (ui.postMedia ||= []).push({ url, m: file.type || '' });
      place(url);
    } catch (e) { toast(e.message || String(e)); }
    ui.postUploading = false; render();
  }
  const attachMedia = (file) => attachTo(file, (url) => {
    const cur = composeText().replace(/\s+$/, '');
    const next = (cur ? cur + '\n' : '') + url;
    ui.profCompose = next;
    setDraft(POST_DRAFT, next);
    // you just attached a picture; showing it IS the answer to the question
    // attaching one raises
    ui.postPreview = true;
  });
  const CLIP = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>';
  const EYE = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';

  // ---- draft preview --------------------------------------------------------
  // A post is written as plain text, but it doesn't ARRIVE as plain text: a
  // URL ending in .jpg becomes a picture, a youtu.be link becomes a player, a
  // nostr: reference becomes the note it points at, an npub becomes a name.
  // You could only find out by posting. This runs the draft through noteBody
  // — the very renderer the feed uses — so the preview is not a lookalike of
  // the real thing, it IS the real thing.
  function draftPreview(text) {
    const body = String(text || '').trim();
    return h('div', { class: 'draft-preview' },
      h('div', { class: 'draft-preview-tag' }, t('composePreviewTag')),
      body
        ? h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, ...noteBody(body))
        : h('div', { class: 'small faint' }, t('composePreviewEmpty')));
  }
  const previewBtn = (on, toggle) => h('button', {
    class: 'attach-btn' + (on ? ' on' : ''),
    title: on ? t('composePreviewHide') : t('composePreview'),
    'aria-label': on ? t('composePreviewHide') : t('composePreview'),
    onClick: toggle,
  }, h('span', { style: 'display:flex', html: EYE }));
  function postComposer() {
    if (ui.profCompose == null && !draftFor(POST_DRAFT)) return null;
    const text = composeText();
    return h('div', { class: 'col', style: 'gap:8px' },
      h('textarea', {
        rows: '3', placeholder: t('profComposePh'),
        style: 'font-family:var(--sans);min-height:64px',
        value: text,
        onInput: (ev) => {
          ui.profCompose = ev.target.value;
          setDraft(POST_DRAFT, ev.target.value);
          // only while the preview is open — otherwise typing costs a render
          // per keystroke for nothing. The morph never rewrites a focused
          // field, so this can't fight the typing.
          if (ui.postPreview) render();
        },
      }),
      ui.postPreview ? draftPreview(text) : null,
      h('div', { class: 'row gap6' },
        h('button', { class: 'btn-primary grow', disabled: !!ui.postUploading, onClick: async () => {
          const body = composeText().trim();
          if (!body) return;
          const media = (ui.postMedia || []).filter((m) => body.includes(m.url));
          // the post is on screen instantly (publishPost is optimistic) —
          // close the composer now; a failure reopens it with the text intact
          ui.profCompose = null;
          ui.postMedia = [];
          setDraft(POST_DRAFT, '');
          try { await publishPost(body, media); toast(t('profPosted')); }
          catch (e) {
            ui.profCompose = body;
            ui.postMedia = media;
            setDraft(POST_DRAFT, body);
            if (!e.silent) toast(e.message || String(e));
            render();
          }
        } }, t('profPostBtn')),
        ctx.uploadImage ? h('button', {
          class: 'attach-btn', title: t('feedAttach'), 'aria-label': t('feedAttach'), disabled: !!ui.postUploading,
          onClick: () => document.getElementById('post-file')?.click(),
        }, ui.postUploading ? h('span', { class: 'spinner sm' }) : h('span', { style: 'display:flex', html: CLIP })) : null,
        previewBtn(!!ui.postPreview, () => { ui.postPreview = !ui.postPreview; render(); }),
        h('input', {
          type: 'file', id: 'post-file', accept: 'image/*,video/*', style: 'display:none',
          onChange: async (e) => { const f = e.target.files && e.target.files[0]; e.target.value = ''; await attachMedia(f); },
        }),
        h('button', { class: 'btn-ghost', onClick: () => { ui.profCompose = null; render(); } }, t('cancel'))));
  }

  // ---- the feed view --------------------------------------------------------
  function feedView() {
    const c = feedNow();
    const authors = feedAuthors();
    const visible = c.notes.filter((ev) => !isMuted(ev.pubkey));
    const rows = visible.slice(0, c.shown || FEED_PAGE).flatMap((ev, i) => [
      i ? h('div', { style: 'height:1px;background:var(--border,rgba(128,128,128,.18));margin:0 -14px' }) : null,
      noteRow(ev.pubkey, ev, displayName(ev.pubkey)),
    ]);
    // Posts that arrived while you were reading, waiting to be let in. A
    // floating pill rather than an insertion: it says how many, and the tap
    // that shows them also takes you up to them.
    const waiting = (c.pending || []).length;
    const pill = waiting
      ? h('button', {
          class: 'feed-new-pill',
          onClick: () => flushPending(true),
        }, '↑ ' + (waiting === 1 ? t('feedOneNew') : t('feedNNew', { n: waiting })))
      : null;
    // the chat shell draws the brand header; this is just the page under it
    return h('div', { class: 'card col chat-page', style: 'gap:10px' },
        pill,
        h('div', { class: 'row gap6', style: 'align-items:center' },
          backBtn(() => { ui.msgView = 'home'; stopFeedWatch(); render(); }),
          h('h3', { style: 'margin:0' }, t('feedTitle')),
          h('button', {
            class: 'btn-sm', style: 'margin-left:auto',
            onClick: () => { ui.profCompose = ui.profCompose == null ? (draftFor(POST_DRAFT) || '') : null; render(); },
          }, t('profNewPost'))),
        postComposer(),
        !authors.length
          ? h('div', { class: 'col', style: 'gap:8px' },
              h('div', { class: 'small muted' }, t('feedNoFollows')),
              h('button', { class: 'btn-sm', onClick: () => { stopFeedWatch(); hook('openUserSearch'); render(); } }, t('feedFindPeople')))
          : c.status === 'loading' && !visible.length
            ? h('div', { class: 'row gap6', style: 'justify-content:center;padding:12px 0' }, h('span', { class: 'spinner sm' }))
            : !visible.length
              ? h('div', { class: 'small faint', style: 'text-align:center;padding:12px 0' }, t('feedEmpty'))
              : h('div', { class: 'card col notes-feed', style: 'gap:0' }, ...rows),
        c.loadingMore
          ? h('div', { class: 'row gap6', style: 'justify-content:center;padding:4px 0' }, h('span', { class: 'spinner sm' }))
          : null,
        noteSheet(),
        reactPicker());
  }


  // ---- user search: the header magnifier ----------------------------------
  // Same engine the Send form and DMs use (registrar names + Primal cache +
  // NIP-50 relays); tapping a result opens their profile, and profile-Back
  // lands here again since the search state survives.
  const userSearcher = makeSearcher((q, rows) => {
    if (ui.userSearch && ui.userSearch.q === q) { ui.userSearch.rows = rows; render(); }
    for (const r of rows || []) if (r.pk) prefetchProfilePage(r.pk);
  });
  function userSearchScreen() {
    const s = ui.userSearch;
    return h('div', { class: 'col', style: 'gap:16px' },
      ctx.brandHeader(!ui.pubProf && wallet.loaded),
      h('div', { class: 'card col', style: 'gap:10px' },
        h('h3', { style: 'margin:0' }, t('searchUsers')),
        h('input', {
          type: 'text', class: 'user-search-input', placeholder: t('searchUsersHint'), value: s.q,
          autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
          onInput: (e) => { s.q = e.target.value; userSearcher.update(s.q); },
        }),
        s.rows && s.rows.length
          ? h('div', { class: 'list' }, resultRows(h, s.rows, (r) => {
              if (r.pk) { openProfile(r.pk); render(); }
            }, (pk, node) => hook('wrapAvatar', pk, node)))
          : s.rows && s.q.trim().length >= 2
            ? h('div', { class: 'small faint', style: 'text-align:center;padding:6px' }, t('searchNoResults'))
            : h('div', { class: 'small faint', style: 'text-align:center;padding:6px' }, t('searchUsersEmpty'))),
      h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.userSearch = null; render(); } }, t('back')));
  }

  // ---- presence & typing --------------------------------------------------
  // Both ride the channel stream as 21059 wraps, so they stay inside the
  // community's encryption — who's around is members-only, not a public
  // status broadcast. 21059 sits in NIP-01's ephemeral range, but measured
  // against the relays we actually use (relay.coinos.io, nos.lol) neither
  // drops them, so they carry a NIP-40 expiration and relay.coinos.io sweeps
  // the kind on a timer; nothing here may assume the relay forgets.
  // Presence only exists while someone is watching a room. A member nobody
  // saw beat is dated by their last message instead, the way an offline
  // contact still shows a last-seen.

  const PRESENCE = 20100;
  const TYPING = 20101;
  const BEAT_MS = 60_000; // how often we announce ourselves
  const ONLINE_MS = 100_000; // a beat older than this is no longer "online"
  const TYPING_MS = 7_000; // how long a typing ping stands
  const TYPE_THROTTLE = 5_000; // and how rarely we send one

  const lastPing = new Map(); // channelId + kind -> ms

  async function ping(room, chId, kind) {
    const key = chId + ':' + kind;
    const gap = kind === PRESENCE ? BEAT_MS : TYPE_THROTTLE;
    if (Date.now() - (lastPing.get(key) || 0) < gap) return;
    lastPing.set(key, Date.now());
    try {
      const id = await identity();
      if (!id) return;
      const { created_at, ms } = msTags(Date.now());
      const rumor = {
        kind, pubkey: id.pubkey, content: '',
        tags: [['channel', chId], ['epoch', String(EPOCH)], ms], created_at,
      };
      // NIP-40: a beat is worthless once it's stale, so relays that honour
      // expiration may drop it instead of keeping it forever.
      const wrap = await wrapRumor(rumor, id.signer, room.chStream(chId),
        { ephemeral: true, expiration: created_at + 300 });
      await publishOn(room.relays, wrap);
    } catch { lastPing.delete(key); }
  }

  // Keep beating while a room is on screen — otherwise everyone would look
  // online for exactly one render and then go dark.
  let beatTimer = null;
  function keepBeating() {
    if (beatTimer) return;
    beatTimer = setInterval(() => {
      if (!ui.chatOpen || ui.msgView !== 'room') return;
      const jm = communityById(ui.msgCommunity) || COMMUNITY;
      const room = rooms.get(jm.community_id);
      if (!room) return;
      const chans = roomChannels(room);
      const ch = chans.find((c) => c.id === ui.msgChannel) || chans[0];
      if (ch) ping(room, ch.id, PRESENCE);
      scheduleRepaint(); // let "online" lapse into "last seen" on its own
    }, 30_000);
  }

  // When we last had any sign of someone: a beat, or failing that the newest
  // thing they said anywhere in the community.
  function lastSeenMs(room, pk) {
    let ts = room.presence.get(pk) || 0;
    for (const msgs of room.byChannel.values())
      for (const m of msgs.values())
        if (m.author === pk) ts = Math.max(ts, eventMs(m.rumor) || 0);
    return ts;
  }

  const isOnline = (room, pk) => Date.now() - (room.presence.get(pk) || 0) < ONLINE_MS;

  function typingNow(room, chId) {
    const my = myPubkeys();
    const out = [];
    for (const [pk, ts] of room.typing)
      if (ts.ch === chId && Date.now() - ts.t < TYPING_MS && !my.includes(pk)) out.push(pk);
    return out;
  }

  // Telegram's wording, and its kindness: exact minutes while it's fresh,
  // then a vague "recently" rather than advertising how long someone's been away.
  function seenLabel(room, pk) {
    if (isOnline(room, pk)) return t('msgOnline');
    const ts = lastSeenMs(room, pk);
    if (!ts) return t('msgSeenRecently');
    const mins = Math.floor((Date.now() - ts) / 60_000);
    if (mins < 1) return t('msgSeenJustNow');
    if (mins < 60) return t('msgSeenMins', { n: mins });
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return t('msgSeenHours', { n: hrs });
    const days = Math.floor(hrs / 24);
    if (days <= 7) return t('msgSeenDays', { n: days });
    return t('msgSeenRecently');
  }

  // Recipient search for New message: debounced, sequenced, cached upstream.
  const dmSearch = { rows: null, busy: false };
  const dmSearcher = makeSearcher((q, rows) => {
    dmSearch.rows = rows;
    dmSearch.busy = false;
    scheduleRepaint();
  });
  const dmSearcherUpdate = dmSearcher.update.bind(dmSearcher);
  dmSearcher.update = (q) => {
    const willSearch = q && q.trim().length >= 2;
    if (willSearch) { dmSearch.busy = dmSearch.rows === null || !dmSearch.rows.length; }
    dmSearcherUpdate(q);
  };

  const stickToBottom = () => {
    queueMicrotask(() => {
      const log = document.querySelector('.chat-log');
      if (log && ui.msgStick !== false) log.scrollTop = log.scrollHeight;
    });
  };

  // The chat card is sized to the viewport, so the mobile keyboard shrinks it:
  // the composer stays on screen, but the log keeps its old scroll offset and
  // the newest messages vanish under the fold. Follow the bottom edge through
  // every viewport change (keyboard, rotation, browser chrome) — unless the
  // user has deliberately scrolled up, which msgStick already remembers.
  const onViewportResize = () => { if (ui.chatOpen) stickToBottom(); };

  // A remote signer that a reload dropped: say so where the typing happens,
  // rather than letting someone write a message and only then be told. The
  // identity itself is still known — it's the ability to sign as it that's
  // missing — so this offers to fetch it back rather than to log in again.
  function signerNotice() {
    if (wallet.watchOnly) {
      return h('div', { class: 'row gap6 chat-signer-off', style: 'align-items:center' },
        h('span', { class: 'small muted grow' }, '\u{1F512} ' + t('msgLockedChat')),
        h('button', { class: 'btn-sm', onClick: () => { ui.justLocked = false; ui.screen = 'vault'; render(); } }, t('unlock')));
    }
    const id = hook('nostrLoginIdentity');
    if (!id || id.signer) return null;
    return h('div', { class: 'row gap6 chat-signer-off', style: 'align-items:center' },
      h('span', { class: 'small muted grow' }, t('msgSignerOff')),
      h('button', {
        class: 'btn-sm', disabled: !!ui.msgReconnecting,
        onClick: async () => {
          ui.msgReconnecting = true; render();
          const s = await hook('nostrLoginResume');
          ui.msgReconnecting = false;
          // Success needs no announcement — the notice itself goes away.
          if (!s) { ui.chatOpen = false; ui.screen = 'wallet'; ui.tab = 'settings'; ui.settingsPage = 'nostr'; }
          render();
        },
      }, ui.msgReconnecting ? h('span', { class: 'spinner sm' }) : t('msgReconnect')));
  }

  // Enter sends; Shift+Enter (the textarea's native edit) and Ctrl+J insert
  // a newline. Height follows the text as it's typed — imperatively, since
  // typing doesn't re-render — with rows as the re-render fallback.
  const growComposer = (el) => {
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 120) + 'px';
  };
  const composer = (placeholder, onSend, onType, draftKey) =>
    h('div', { class: 'col', style: 'gap:6px' },
      signerNotice(),
    h('div', { class: 'chat-compose' },
      h('textarea', {
        class: 'grow', id: 'msg-draft', placeholder, rows: String(Math.min(5, draftFor(draftKey).split('\n').length)),
        value: draftFor(draftKey), maxlength: '2000',
        onInput: (e) => { setDraft(draftKey, e.target.value); growComposer(e.target); if (onType && e.target.value) onType(); },
        onKeydown: (e) => {
          if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); onSend(); return; }
          if (e.ctrlKey && (e.key === 'j' || e.key === 'J')) {
            e.preventDefault();
            const el = e.target;
            const { selectionStart: s0, selectionEnd: s1, value } = el;
            el.value = value.slice(0, s0) + '\n' + value.slice(s1);
            el.selectionStart = el.selectionEnd = s0 + 1;
            setDraft(draftKey, el.value);
            growComposer(el);
          }
        },
        // Focus summons the keyboard; some browsers resize only after its
        // animation, so re-stick once now and once when it has settled.
        onFocus: () => { stickToBottom(); setTimeout(stickToBottom, 350); },
      }),
      h('button', { class: 'btn-primary btn-sm', onClick: onSend }, t('msgSend'))));

  // ---- home ---------------------------------------------------------------

  function homeView() {
    startDMs();
    // Threads you've since replied to should stop being strangers to the
    // worker; throttled inside, so this is cheap on every render.
    syncInbox().catch(() => {});
    for (const jm of communities()) ensureRoom(jm);

    for (const peer of threads.keys()) profileOf(peer); // names and faces, in one batch
    const dmRows = [...threads.entries()]
      .map(([peer, m]) => {
        const last = [...m.values()].sort((a, b) => a.rumor.created_at - b.rumor.created_at).at(-1);
        return { peer, last, unread: dmUnread(peer, m) };
      })
      .filter((x) => x.last)
      .sort((a, b) => b.last.rumor.created_at - a.last.rumor.created_at);

    // Being here answers the header dot — including anything that lands while
    // the list is open, since arrivals repaint it and the rows below say who.
    {
      const my = myPubkeys();
      let newest = 0;
      for (const msgs of threads.values())
        newest = Math.max(newest, newestFrom(msgs.values(), (m) => !m.mine));
      for (const room of rooms.values())
        for (const msgs of room.byChannel.values())
          newest = Math.max(newest, newestFrom(msgs.values(), (m) => !my.includes(m.author)));
      markRead(HOME_READ, newest);
    }

    const kids = [];

    // Chat takes the whole screen, so home carries the way back to the wallet.
    kids.push(h('div', { class: 'row gap6', style: 'align-items:center' },
      backBtn(() => { ui.chatOpen = false; render(); }),
      h('h3', { style: 'margin:0' }, t('tabMessages')),
      anyUnread()
        ? h('button', { class: 'linklike small', style: 'margin-left:auto', onClick: markAllRead }, t('msgMarkAllRead'))
        : null));

    // A locked wallet can't decrypt or sign — say so up top, where the rooms
    // that quietly won't open are listed.
    const lockedRow = signerNotice();
    if (lockedRow && wallet.watchOnly) kids.push(lockedRow);

    if (pendingLink) kids.push(linkInviteCard());
    for (const [rid, inv] of pendingDirect) kids.push(directInviteCard(rid, inv));

    // offer push once — it covers messages AND payments
    if (typeof Notification !== 'undefined' && Notification.permission === 'default' && !st().pushDismissed)
      kids.push(h('div', { class: 'notice info col', style: 'gap:8px' },
        h('div', {}, t('msgPushOffer')),
        h('div', { class: 'row gap6' },
          h('button', {
            class: 'btn-primary btn-sm',
            onClick: async () => { const ok = await registerPush({ interactive: true }); toast(ok ? t('msgPushOn') : t('msgPushFailed')); render(); },
          }, t('msgPushEnable')),
          h('button', {
            class: 'btn-ghost btn-sm',
            onClick: () => { const s = st(); s.pushDismissed = true; save(s); render(); },
          }, t('msgDismiss')))));
    // A browser with no push service at all: the offer above is beside the
    // point (permission may even be granted), so say what's actually wrong
    // wherever the user got to. Inside the Android build that carries its own
    // push, the answer is a different one — see pushAdvice.
    if (st().noPushService && !st().push)
      kids.push(h('div', { class: 'notice info small' }, pushAdvice()));

    // ---- the feed, above the conversations: it's the thing you read, they're
    // the things you answer
    kids.push(h('div', { class: 'list' },
      h('div', {
        class: 'item chat-thread-row',
        onClick: () => { ui.msgView = 'feed'; feedNow(); watchFeed(); render(); },
      },
      h('div', { class: 'chat-avatar fallback' }, '\u2605'),
      h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
        h('span', { class: 'chat-name' }, t('feedTitle')),
        h('div', { class: 'muted small' },
          followsNow().set.size === 1 ? t('feedFollowing1')
            : followsNow().set.size ? t('feedFollowingN', { n: followsNow().set.size })
            : t('feedNoFollowsShort'))))));

    // ---- DMs
    kids.push(h('div', { class: 'row between', style: 'align-items:baseline' },
      h('h3', { style: 'margin:0' }, t('msgDmsTitle')),
      h('button', { class: 'btn-sm', onClick: () => { ui.msgHomePanel = ui.msgHomePanel === 'newdm' ? null : 'newdm'; if (ui.msgHomePanel === 'newdm') warmSearch(); render(); } }, t('msgNewDm'))));
    if (ui.msgHomePanel === 'newdm') {
      const openThread = (pk) => {
        dmSearcher.clear();
        ui.msgNewDmTo = '';
        ui.msgHomePanel = null;
        ui.msgView = 'dm';
        ui.msgPeer = pk;
        ui.msgStick = true;
        render();
      };
      kids.push(h('div', { class: 'col gap6' },
        h('div', { class: 'row gap6' },
          h('input', {
            class: 'grow', type: 'text', placeholder: t('msgSearchPlaceholder'),
            value: ui.msgNewDmTo || '',
            onInput: (e) => { ui.msgNewDmTo = e.target.value; dmSearcher.update(e.target.value); },
          }),
          h('button', {
            class: 'btn-sm', onClick: () => {
              const pk = parseNostrPubkey(ui.msgNewDmTo);
              if (!pk) { toast(t('msgBadNpub')); return; }
              openThread(pk);
            },
          }, t('msgOpen'))),
        dmSearch.rows === null ? null
          : dmSearch.busy ? h('div', { class: 'row gap6', style: 'align-items:center;padding:4px 0' },
              h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('msgSearching')))
          : dmSearch.rows.length
            ? h('div', { class: 'list' }, resultRows(h, dmSearch.rows, (r) => openThread(r.pk), (pk, node) => hook('wrapAvatar', pk, node)))
            : h('div', { class: 'small muted' }, t('msgNoMatches'))));
    }
    // A long DM history must not bury the communities below it: past a
    // handful, the rest waits behind "show all". (No cap for barely-over —
    // a "show 2 more" button costs more than the rows it hides.)
    const DM_PREVIEW = 5;
    const shownDms = (ui.msgAllDms || dmRows.length <= DM_PREVIEW + 2) ? dmRows : dmRows.slice(0, DM_PREVIEW);
    kids.push(
      dmRows.length
        ? h('div', { class: 'list' }, shownDms.map(({ peer, last, unread }) =>
            h('div', {
              class: 'item chat-thread-row' + (unread ? ' unread' : ''),
              onClick: () => { ui.msgView = 'dm'; ui.msgPeer = peer; ui.msgStick = true; render(); },
            },
            avatar(peer),
            h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
              h('div', { class: 'row between' },
                h('span', { class: 'chat-name' }, displayName(peer)),
                h('span', { class: 'chat-time thread-when' },
                  timeLabel(last.rumor.created_at * 1000),
                  unread ? h('i', { class: 'thread-dot' }) : null)),
              h('div', { class: 'muted small chat-preview' }, (last.mine ? t('msgYouPrefix') + ' ' : '') + last.rumor.content)))))
        : h('div', { class: 'muted small' }, t('msgNoDms')));
    if (shownDms.length < dmRows.length)
      kids.push(h('button', { class: 'linklike small', onClick: () => { ui.msgAllDms = true; render(); } },
        t('msgShowAllDms', { n: dmRows.length })));
    else if (ui.msgAllDms && dmRows.length > DM_PREVIEW + 2)
      kids.push(h('button', { class: 'linklike small', onClick: () => { ui.msgAllDms = false; render(); } },
        t('msgShowFewerDms')));

    // ---- communities
    kids.push(h('div', { class: 'row between mt16', style: 'align-items:baseline' },
      h('h3', { style: 'margin:0' }, t('msgCommunitiesTitle')),
      h('div', { class: 'row gap6' },
        h('button', { class: 'btn-sm', onClick: () => { ui.msgHomePanel = ui.msgHomePanel === 'join' ? null : 'join'; render(); } }, t('msgJoin')),
        h('button', { class: 'btn-sm', onClick: () => { ui.msgHomePanel = ui.msgHomePanel === 'create' ? null : 'create'; render(); } }, t('msgCreate')))));
    if (ui.msgHomePanel === 'join')
      kids.push(h('div', { class: 'row gap6' },
        h('input', {
          class: 'grow', type: 'text', placeholder: t('msgInvitePlaceholder'),
          value: ui.msgJoinText || '', onInput: (e) => { ui.msgJoinText = e.target.value; },
        }),
        h('button', { class: 'btn-sm', onClick: () => joinFromText(ui.msgJoinText) }, t('msgJoin'))));
    if (ui.msgHomePanel === 'create')
      kids.push(h('div', { class: 'row gap6' },
        h('input', {
          class: 'grow', type: 'text', placeholder: t('msgNamePlaceholder'), maxlength: '64',
          value: ui.msgNewName || '', onInput: (e) => { ui.msgNewName = e.target.value; },
        }),
        h('button', { class: 'btn-sm', onClick: () => createCommunity(ui.msgNewName || '') }, t('msgCreate'))));
    kids.push(h('div', { class: 'list' }, communities().map((jm) => {
      const room = rooms.get(jm.community_id);
      const name = room?.folded?.metadata?.name || jm.name;
      // Last session's settled count anchors the number: while the guestbook
      // replay is still streaming in (multiple relays, bursts past the fold
      // debounce), the live tally climbs through intermediate values — take
      // the max so the count doesn't visibly tick upward on every refresh.
      // Once the replay settles, the cache is rewritten to the live figure,
      // so a genuine departure still shows (one quiet step down, not a climb).
      const live = room ? [...room.members.values()].filter((m) => m.state === 'join').length : 0;
      const memberCount = Math.max(live, (st().memberCounts || {})[jm.community_id] || 0);
      const unread = room ? roomUnread(room) : false;
      return h('div', {
        class: 'item chat-thread-row' + (unread ? ' unread' : ''),
        onClick: () => { ui.msgView = 'room'; ui.msgCommunity = jm.community_id; ui.msgChannel = null; ui.msgStick = true; render(); },
      },
      h('div', { class: 'chat-avatar fallback' }, name.slice(0, 2)),
      h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
        h('div', { class: 'row between' },
          h('span', { class: 'chat-name' }, name),
          unread ? h('i', { class: 'thread-dot' }) : null),
        h('div', { class: 'muted small' },
          memberCount ? t('msgMembers', { n: memberCount }) : t('msgEncrypted'))));
    })));

    return h('div', { class: 'card col chat-page', style: 'gap:10px' }, ...kids);
  }

  function linkInviteCard() {
    const pl = pendingLink;
    return h('div', { class: 'notice info col', style: 'gap:8px' },
      pl.state === 'loading' ? h('div', { class: 'row gap6' }, h('span', { class: 'spinner sm' }), t('msgInviteLoading'))
      : pl.state === 'error' ? h('div', { class: 'row between' },
          h('span', {}, pl.error),
          h('button', { class: 'linklike', onClick: () => { pendingLink = null; render(); } }, t('msgDismiss')))
      : h('div', { class: 'col', style: 'gap:8px' },
          h('div', {}, t('msgInviteTo', { name: pl.bundle.name || 'community' })),
          h('div', { class: 'muted small' }, t('msgInviteFounder', { npub: (npubOf(pl.bundle.owner) || '').slice(0, 16) + '…' })),
          h('div', { class: 'row gap6' },
            h('button', { class: 'btn-primary btn-sm', onClick: () => acceptBundle(pl.bundle, { invitedBy: pl.bundle.creator_npub }) }, t('msgJoin')),
            h('button', { class: 'btn-ghost btn-sm', onClick: () => { pendingLink = null; render(); } }, t('msgDismiss')))));
  }

  function directInviteCard(rid, inv) {
    return h('div', { class: 'notice info col', style: 'gap:8px' },
      h('div', {}, t('msgDirectInvite', { name: inv.bundle.name || 'community', from: displayName(inv.from) })),
      h('div', { class: 'row gap6' },
        h('button', {
          class: 'btn-primary btn-sm',
          onClick: () => { pendingDirect.delete(rid); acceptBundle(inv.bundle, { invitedBy: inv.from }); },
        }, t('msgJoin')),
        h('button', {
          class: 'btn-ghost btn-sm',
          onClick: () => { const s = st(); s.declined[rid] = 1; save(s); pendingDirect.delete(rid); render(); },
        }, t('msgDismiss'))));
  }

  // ---- room ---------------------------------------------------------------

  function messageRows(room, chId) {
    const my = myPubkeys();
    const msgs = [...(room.byChannel.get(chId)?.values() || [])]
      .filter((m) => !room.deletes.has(m.rumor.id))
      .filter((m) => !(room.folded && room.folded.banned.has(m.author)))
      .sort((a, b) => eventMs(a.rumor) - eventMs(b.rumor));
    markRead(chRead(chId), newestFrom(msgs, (m) => !my.includes(m.author)));
    if (!msgs.length)
      return [h('div', { class: 'muted small', style: 'text-align:center;padding:24px 0' }, t('msgEmpty'))];
    let lastAuthor = null, lastT = 0;
    watchZaps(msgs.slice(-150).map((m) => m.rumor.id));
    return msgs.map((m) => {
      const tms = eventMs(m.rumor);
      const mine = my.includes(m.author);
      const edit = room.edits.get(m.rumor.id);
      const text = edit && edit.author === m.author ? edit.rumor.content : m.rumor.content;
      const grouped = m.author === lastAuthor && tms - lastT < 5 * 60_000;
      lastAuthor = m.author; lastT = tms;
      const reacts = room.reactions.get(m.rumor.id);
      const counts = new Map();
      if (reacts) for (const emoji of reacts.values()) counts.set(emoji, (counts.get(emoji) || 0) + 1);
      // this wallet's own reaction (any of its identities) — highlighted, and
      // choosing another emoji replaces it (one reaction per author, the fold
      // keeps the latest)
      const myReact = reacts && my.map((pk) => reacts.get(pk)).find(Boolean);
      return h(
        'div', { class: 'chat-row' + (mine ? ' mine' : '') + (grouped ? ' grouped' : '') },
        grouped ? h('div', { class: 'chat-avatar spacer' }) : avatar(m.author),
        h('div', { class: 'chat-body' },
          grouped ? null : h('div', { class: 'chat-meta' },
            h('span', {
              class: 'chat-name clickable' + (m.author === room.jm.owner ? ' owner' : ''),
              onClick: () => openProfile(m.author),
            },
              displayName(m.author),
              m.author === room.jm.owner ? h('span', { class: 'chat-badge' }, t('msgAdmin')) : null),
            h('span', { class: 'chat-time' }, timeLabel(tms))),
          h('div', {
            class: 'chat-bubble clickable',
            // Telegram-style: a tap on the message opens its action sheet
            // (quick reactions, reply, copy, delete). Links, images and the
            // hover × keep their own clicks; a desktop text-selection drag
            // ends in a click too, and must not pop the sheet over the copy.
            onClick: (e) => {
              if (e.target.closest && e.target.closest('a, button, img')) return;
              const sel = window.getSelection && window.getSelection();
              if (sel && String(sel).length) return;
              ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id;
              render();
            },
          },
            replyQuote(room, chId, m),
            ...noteBody(text),
            edit ? h('span', { class: 'chat-edited' }, ' ', t('msgEdited')) : null,
            mine
              ? h('button', { class: 'chat-del', title: t('msgDelete'), onClick: () => deleteMessage(room, chId, m) }, '×')
              : null,
            // reactions tuck inside the bubble, under the text (Telegram-style);
            // the zap total leads the row, and tapping it zaps again
            ((zc) => counts.size || zc
              ? h('div', { class: 'chat-reacts' },
                  zc,
                  [...counts.entries()].map(([emoji, n]) =>
                    h('span', {
                      class: 'chat-react clickable' + (emoji === myReact ? ' on' : ''),
                      title: t('msgReact'),
                      onClick: (e) => { e.stopPropagation(); sendReaction(room, chId, m, emoji); },
                    }, emoji, n > 1 ? ' ' + n : '')))
              : null)(zapChip(m.rumor.id, { cls: 'chat-react', onClick: !mine && canZapPk(m.author) ? () => zapMessage(m.author, m.rumor.id) : null }))))
      );
    });
  }

  function roomView() {
    const jm = communityById(ui.msgCommunity) || COMMUNITY;
    const room = ensureRoom(jm);
    const chans = roomChannels(room);
    const ch = chans.find((c) => c.id === ui.msgChannel) || chans[0];
    const name = room.folded?.metadata?.name || jm.name;
    const members = [...room.members.entries()].filter(([, m]) => m.state === 'join');
    const memberCount = members.length;
    const onlineCount = members.filter(([pk]) => isOnline(room, pk)).length;
    stickToBottom();
    keepBeating();
    if (ch) ping(room, ch.id, PRESENCE);

    return h('div', { class: 'card col chat-card chat-page' },
      h('div', { class: 'row between chat-head' },
        h('div', { class: 'row gap6', style: 'align-items:center;min-width:0' },
          backBtn(() => { ui.msgView = 'home'; ui.msgReplyTo = null; ui.msgSheet = null; render(); }),
          h('div', {
            class: 'col clickable', style: 'gap:2px;min-width:0',
            onClick: () => { ui.msgMembers = !ui.msgMembers; render(); },
          },
            h('div', { class: 'chat-title' }, name),
            h('div', { class: 'muted small' },
              memberCount ? t('msgMembers', { n: memberCount }) : t('msgEncrypted'),
              onlineCount ? h('span', { class: 'online-count' }, ' · ', t('msgNOnline', { n: onlineCount })) : null))),
        h('div', { class: 'row gap6', style: 'align-items:center' },
          // One channel needs no label — naming it only asks people to notice a
          // choice they don't have. Several become a picker.
          chans.length > 1
            ? h('select', {
                class: 'chan-pick',
                onChange: (e) => { ui.msgChannel = e.target.value; ui.msgStick = true; ui.msgReplyTo = null; ui.msgSheet = null; subChannel(room, e.target.value); render(); },
              }, chans.map((c) => h('option', { value: c.id, selected: c.id === ch?.id }, '#' + c.name)))
            : null,
          h('button', {
            class: 'iconbtn bell' + (roomNotify(jm.community_id) ? ' on' : ''),
            title: roomNotify(jm.community_id) ? t('msgNotifyOn') : t('msgNotifyOff'),
            onClick: () => toggleRoomNotify(jm.community_id),
            html: roomNotify(jm.community_id)
              ? '<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0" fill="none"/></svg>'
              : '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M13.7 21a2 2 0 0 1-3.4 0"/><path d="M18 8a6 6 0 0 0-9.3-5"/><path d="M6.3 6.3A6 6 0 0 0 6 8c0 7-3 9-3 9h15"/><path d="m2 2 20 20"/></svg>',
          }),
          h('button', {
            class: 'btn-sm', title: t('msgInviteTitle'),
            onClick: () => { ui.msgInvitePanel = !ui.msgInvitePanel; render(); },
          }, t('msgAddPerson')))),
      ui.msgInvitePanel ? invitePanel(room) : null,
      ui.msgMembers ? memberPanel(room, members) : null,
      h('div', {
        class: 'chat-log',
        onScroll: (e) => {
          const el = e.target;
          ui.msgStick = el.scrollHeight - el.scrollTop - el.clientHeight < 60;
        },
      }, ...(ch ? messageRows(room, ch.id) : [])),
      ch ? typingLine(room, ch.id) : null,
      ch ? replyBar(room, ch.id) : null,
      composer(
        chans.length > 1 ? t('msgPlaceholder', { channel: ch ? ch.name : '' }) : t('msgPlaceholderPlain'),
        () => ch && sendMessage(room, ch.id),
        () => ch && ping(room, ch.id, TYPING),
        ch ? 'ch:' + ch.id : 'ch:'),
      ch && ui.msgSheet ? messageSheet(room, ch.id) : null);
  }

  // "Alice is typing…" — named up to two, counted beyond that.
  function typingLine(room, chId) {
    const who = typingNow(room, chId);
    if (!who.length) return null;
    const label = who.length === 1 ? t('msgTyping', { name: displayName(who[0]) })
      : who.length === 2 ? t('msgTyping2', { a: displayName(who[0]), b: displayName(who[1]) })
      : t('msgTypingMany', { n: who.length });
    return h('div', { class: 'chat-typing' },
      h('span', { class: 'typing-dots' }, h('i'), h('i'), h('i')),
      h('span', { class: 'small muted' }, label));
  }

  function memberPanel(room, members) {
    const rows = members
      .map(([pk]) => ({ pk, online: isOnline(room, pk), seen: lastSeenMs(room, pk) }))
      .sort((a, b) => (b.online - a.online) || (b.seen - a.seen));
    return h('div', { class: 'col chat-members' },
      ...rows.map((r) => h('div', {
        class: 'item chat-thread-row',
        onClick: () => openProfile(r.pk),
      },
        h('span', { class: 'ava-wrap' + (r.online ? ' online' : '') }, avatar(r.pk)),
        h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
          h('div', { class: 'row gap6', style: 'align-items:center;min-width:0' },
            h('span', { class: 'chat-name' }, displayName(r.pk)),
            r.pk === room.jm.owner ? h('span', { class: 'chat-badge' }, t('msgAdmin')) : null),
          h('div', { class: 'muted small' + (r.online ? ' is-online' : '') }, seenLabel(room, r.pk))))));
  }

  function invitePanel(room) {
    const builtin = room.jm.community_id === COMMUNITY.community_id;
    return h('div', { class: 'col chat-invite', style: 'gap:8px' },
      h('div', { class: 'row gap6' },
        h('button', {
          class: 'btn-sm', disabled: ui.msgMinting,
          onClick: async () => {
            ui.msgMinting = true; render();
            try {
              const url = await mintInviteLink(room);
              if (url) { await navigator.clipboard.writeText(url); toast(t('msgLinkCopied')); }
            } finally { ui.msgMinting = false; render(); }
          },
        }, ui.msgMinting ? h('span', { class: 'spinner sm' }) : t('msgCopyInvite')),
        h('input', {
          class: 'grow', type: 'text', placeholder: t('msgNpubPlaceholder'),
          value: ui.msgInviteTo || '', onInput: (e) => { ui.msgInviteTo = e.target.value; },
        }),
        h('button', {
          class: 'btn-sm',
          onClick: () => { sendDirectInvite(room, ui.msgInviteTo); ui.msgInviteTo = ''; render(); },
        }, t('msgSend'))),
      // Owners can add channels (an owner-signed control edition), but a naming
      // field sitting open is a question nobody asked — it reads as something
      // you're meant to fill in right after making a community.
      myPubkeys().includes(room.jm.owner)
        ? (ui.msgChannelPanel
            ? h('div', { class: 'row gap6' },
                h('input', {
                  class: 'grow', type: 'text', placeholder: t('msgChannelPlaceholder'), maxlength: '64',
                  value: ui.msgNewChannel || '', onInput: (e) => { ui.msgNewChannel = e.target.value; },
                  onKeydown: (e) => { if (e.key === 'Enter') createChannel(room, ui.msgNewChannel); },
                }),
                h('button', { class: 'btn-sm', onClick: () => createChannel(room, ui.msgNewChannel) }, t('msgCreate')),
                h('button', { class: 'btn-ghost btn-sm', onClick: () => { ui.msgChannelPanel = false; render(); } }, t('cancel')))
            : h('div', { class: 'row' },
                h('button', {
                  class: 'btn-sm',
                  onClick: () => { ui.msgChannelPanel = true; render(); },
                }, t('msgNewChannel'))))
        : null,
      // leaving discards the keys on this identity — two taps, default community exempt
      builtin ? null : h('div', { class: 'row' },
        h('button', {
          class: 'btn-ghost btn-sm ' + (ui.msgLeaveArm ? 'btn-danger' : ''),
          onClick: () => {
            if (ui.msgLeaveArm) leaveCommunity(room);
            else { ui.msgLeaveArm = true; render(); }
          },
        }, ui.msgLeaveArm ? t('msgLeaveConfirm') : t('msgLeave'))));
  }

  // ---- dm thread ----------------------------------------------------------

  // The DM flavor of the message action sheet: reactions + Reply + Copy.
  // No Delete — a gift-wrapped DM can't be retracted from the peer's relays.
  function dmSheet(peer) {
    const m = threadOf(peer).get(ui.msgSheet);
    if (!m) { ui.msgSheet = null; return null; }
    const my = myPubkeys();
    const reacts = dmReacts.get(m.rumor.id);
    const myReact = reacts && my.map((pk) => reacts.get(pk)).find(Boolean);
    const close = () => { ui.msgSheet = null; render(); };
    const item = (icon, label, onClick) => h('button', { class: 'msg-sheet-item', onClick },
      h('span', { class: 'msg-sheet-ico' }, icon), label);
    return h('div', {
      class: 'confirm-pop-backdrop',
      onClick: (e) => { if (e.target === e.currentTarget) close(); },
    },
      h('div', { class: 'card col msg-sheet' },
        h('div', { class: 'msg-sheet-emojis' },
          REACT_EMOJIS.map((e2) => h('button', {
            class: e2 === myReact ? 'on' : '',
            onClick: () => { close(); sendDmReaction(peer, m, e2); },
          }, e2))),
        item('↩', t('msgReply'), () => {
          ui.msgReplyTo = m.rumor.id;
          close();
          setTimeout(() => document.getElementById('msg-draft')?.focus(), 50);
        }),
        !m.mine && canZapPk(m.rumor.pubkey) ? item('⚡', t('msgZap'), () => { close(); zapMessage(m.rumor.pubkey, m.rumor.id); }) : null,
        item('⧉', t('copy'), async () => {
          try { await navigator.clipboard.writeText(m.rumor.content); toast(t('copied')); } catch {}
          close();
        })));
  }

  function dmView() {
    startDMs();
    const peer = ui.msgPeer;
    if (!peer) { ui.msgView = 'home'; return homeView(); }
    const thread = threads.get(peer) || new Map();
    const msgs = [...thread.values()].sort((a, b) => a.rumor.created_at - b.rumor.created_at);
    // Looking at the thread is reading it — including anything that lands while
    // it's still open, since every arrival repaints us.
    markRead(dmRead(peer), newestFrom(msgs, (m) => !m.mine));
    stickToBottom();
    const my = myPubkeys();
    const dmQuote = (m) => {
      const replyId = (m.rumor.tags || []).find((x) => x[0] === 'e')?.[1];
      const src = replyId && thread.get(replyId);
      if (!src) return null;
      return h('div', { class: 'chat-quote' },
        h('span', { class: 'chat-quote-name' }, displayName(src.rumor.pubkey)),
        h('span', { class: 'chat-quote-text' }, String(src.rumor.content || '').replace(/\s+/g, ' ').slice(0, 90)));
    };
    watchZaps(msgs.slice(-150).map((m) => m.rumor.id));
    const dmChips = (m) => {
      const reacts = dmReacts.get(m.rumor.id);
      const zc = zapChip(m.rumor.id, { cls: 'chat-react', onClick: !m.mine && canZapPk(m.rumor.pubkey) ? () => zapMessage(m.rumor.pubkey, m.rumor.id) : null });
      if ((!reacts || !reacts.size) && !zc) return null;
      const myReact = reacts && my.map((pk) => reacts.get(pk)).find(Boolean);
      const counts = new Map();
      if (reacts) for (const emoji of reacts.values()) counts.set(emoji, (counts.get(emoji) || 0) + 1);
      return h('div', { class: 'chat-reacts' },
        zc,
        [...counts.entries()].map(([emoji, n]) => h('span', {
          class: 'chat-react clickable' + (emoji === myReact ? ' on' : ''),
          onClick: (e) => { e.stopPropagation(); sendDmReaction(peer, m, emoji); },
        }, emoji, n > 1 ? ' ' + n : '')));
    };
    const dmReplyBar = () => {
      const m = ui.msgReplyTo && thread.get(ui.msgReplyTo);
      if (!m) { ui.msgReplyTo = null; return null; }
      return h('div', { class: 'reply-bar' },
        h('div', { class: 'col grow', style: 'gap:1px;min-width:0' },
          h('span', { class: 'small', style: 'font-weight:650' }, '↩ ', displayName(m.rumor.pubkey)),
          h('span', { class: 'small muted chat-quote-text' }, String(m.rumor.content || '').replace(/\s+/g, ' ').slice(0, 90))),
        h('button', { class: 'chat-del', style: 'position:static;display:flex;flex-shrink:0', onClick: () => { ui.msgReplyTo = null; render(); } }, '×'));
    };
    return h('div', { class: 'card col chat-card chat-page' },
      h('div', { class: 'row chat-head gap6', style: 'align-items:center' },
        backBtn(() => { ui.msgView = 'home'; ui.msgReplyTo = null; ui.msgSheet = null; render(); }),
        avatar(peer),
        h('div', { class: 'col clickable', style: 'gap:2px;min-width:0', onClick: () => openProfile(peer) },
          h('div', { class: 'chat-title' }, displayName(peer)),
          h('div', { class: 'muted small' }, t('msgDmEncrypted')))),
      h('div', {
        class: 'chat-log',
        onScroll: (e) => {
          const el = e.target;
          ui.msgStick = el.scrollHeight - el.scrollTop - el.clientHeight < 60;
        },
      },
      ...(msgs.length
        ? msgs.map((m) =>
            h('div', { class: 'chat-row dm' + (m.mine ? ' mine' : '') },
              h('div', { class: 'chat-body' },
                h('div', {
                  class: 'chat-bubble clickable' + (m.mine ? ' me' : ''),
                  // same tap-for-actions as community bubbles
                  onClick: (e) => {
                    if (e.target.closest && e.target.closest('a, button, img')) return;
                    const sel = window.getSelection && window.getSelection();
                    if (sel && String(sel).length) return;
                    ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id;
                    render();
                  },
                }, dmQuote(m), ...noteBody(m.rumor.content), dmChips(m)),
                h('div', { class: 'chat-time' }, timeLabel(m.rumor.created_at * 1000)))))
        : [h('div', { class: 'muted small', style: 'text-align:center;padding:24px 0' }, t('msgNoDmsYet'))])),
      dmReplyBar(),
      composer(t('msgDmPlaceholder'), () => sendDM(peer), null, 'dm:' + peer),
      ui.msgSheet ? dmSheet(peer) : null);
  }

  // ---- feature ------------------------------------------------------------

  function messagesTab() {
    if (ui.msgView === 'feed') return feedView();
    if (ui.msgView === 'room') return roomView();
    if (ui.msgView === 'dm') return dmView();
    return homeView();
  }

  return {
    id: 'messages',
    // The app came back after being backgrounded. A phone freezes a hidden
    // tab: the relay sockets are cut and every post made in the meantime is
    // simply missing, which is why the feed used to sit there looking stale
    // until you pulled it down by hand. So: re-dial and catch up. The gap is
    // fetched (force, past the thirty-second throttle) and the live
    // subscriptions are rebuilt, since the ones we had are talking to
    // sockets that no longer exist.
    resumed(awayMs) {
      if (!ui.chatOpen || ui.msgView !== 'feed') return;
      // a blink between apps didn't kill anything
      if (awayMs && awayMs < 5_000) return;
      refreshFeed({ force: true }).catch(() => {});
      return true;
    },
    // A zap flow reporting how its payment went, so the chip that appeared
    // on tap can stop pulsing (paid) or disappear (failed / never fired).
    // Also the way a zap sent from a form reaches the tally right away,
    // without waiting on its receipt.
    zapSettled(eventId, ok, sats) { settleZap(eventId, ok, sats); return true; },
    // the right thing to say about push on THIS device, wherever it's asked
    pushAdvice() { return pushAdvice(); },
    // Chat lives behind a header button and takes over the whole screen —
    // no balance card, no tabs; each view carries its own way back.
    // The bare avatar node for the app header's identity menu.
    // The header rebuilds every render; recreating the <img> each time makes
    // the picture visibly flash during boot's render bursts. There is exactly
    // one header avatar, so the node itself is reused until the profile
    // (or account) actually changes.
    // A seed minted seconds ago has no kind-0 anywhere — don't make the
    // avatar sit white while a relay lookup confirms that; paint the punk now.
    identityGenerated() {
      // Synchronous on purpose: identity() can await a signer resume, and
      // the header sat avatar-less for that beat. A generated seed's pubkey
      // is right here — paint the punk before the next frame.
      const pk = (hook('nostrLoginIdentity') || {}).pubkey || (wallet.nostr && wallet.nostr.pk);
      if (!pk) return;
      const entry = { name: null, picture: null, t: Date.now() };
      profiles.set(pk, entry);
      persistProfile(pk, entry);
      scheduleRepaint();
    },
    headerAvatar(pk) {
      // A fresh node every render: the morph keeps the live element (and its
      // loaded image) in place when nothing changed, which is exactly what
      // the old cached-node trick faked — and reusing one node in two trees
      // let the morph strip its children when positions paired it wrong.
      return avatar(pk, 'chat-avatar header-ava', false);
    },
    // Conversations waiting on us, for the header's message button.
    unreadMessages() {
      // A device with no read watermarks yet (a fresh restore or brand-new
      // wallet) will show the dot the moment the community messages land —
      // which is always: the default community is never empty, the welcome
      // DM is on its way, and read state is device-local. Paint it from the
      // first frame instead of popping it in when the fetch returns. NB the
      // guard must key on "no MESSAGES landed yet", not "no rooms": init()
      // creates the coinos room synchronously before the first paint, so a
      // rooms.size check defeated the optimism it was written for.
      const s = st();
      const anyMsgs = threads.size > 0
        || [...rooms.values()].some((r) => [...r.byChannel.values()].some((m) => m.size));
      if (!Object.keys(s.read || {}).length && !anyMsgs) return 1;
      return unreadCount();
    },
    notifySettingsCards() { return [notifyCard()]; },
    screenView() {
      // A profile deep link mid-resolution holds the frame over EVERY screen
      // — an auto-restored wallet would otherwise flash its home page for the
      // beat the registrar lookup takes. The shell shows the name straight
      // off the URL; no spinner, the empty beat reads calmer.
      if (ui.pubProfPending) return h('div', { class: 'col', style: 'gap:16px' },
        ctx.brandHeader(false),
        h('div', { class: 'card col', style: 'gap:12px' },
          h('div', { class: 'row gap6', style: 'align-items:center' },
            h('div', { class: 'chat-avatar profile-avatar fallback loading' }),
            h('div', { class: 'chat-title' }, ui.pubProfPending))));
      if (ui.screen !== 'wallet') {
        // The public (no-wallet) surface: a deep-linked profile, and the
        // threads reachable from it, are public nostr content — shown
        // without an account. Back falls through to the app's own screens.
        if (ui.pubProf) {
          if (ui.profOverThread && ui.profilePk) return profileScreen();
          if (ui.noteThread) return threadScreen();
          if (ui.profilePk) return profileScreen();
        }
        return null;
      }
      if (ui.zapSetup) return zapSetupScreen();
      if (ui.profOverThread && ui.profilePk) return profileScreen();
      if (ui.noteThread) return threadScreen();
      if (ui.profilePk) return profileScreen();
      if (ui.userSearch && !ui.chatOpen) return userSearchScreen();
      if (!ui.chatOpen) return null;
      return h('div', { class: 'col', style: 'gap:16px' },
        ctx.brandHeader(true),
        messagesTab());
    },
    // The header magnifier: search anyone on nostr, results open profiles.
    userSearchAvailable() { return true; },
    openUserSearch() {
      ui.chatOpen = false;
      ui.profilePk = null;
      ui.userSearch = { q: '', rows: null };
      warmSearch(); // the field is about to be typed into — open the pipes
      return true;
    },
    // nostr-login just connected or resumed a signer: wraps the backfill
    // couldn't open a moment ago can be opened now — drain right away.
    nostrSignerLive() { scheduleDrain(0); },
    // Anyone (ark's history, other features) can open a profile or render a
    // small clickable identity chip.
    showProfile(pk) { openProfile(pk); return true; },
    // The light profile cache, read-only — lets the onboarding wizard skip
    // asks (like the avatar picker) that a loaded identity already answered.
    cachedProfile(pk) { return profileOf(pk); },
    // Start fetching a profile (and its picture bytes) NOW — the login flow
    // calls this the moment it knows the identity, so the avatar is already
    // in cache by the time the home screen first paints.
    warmProfile(pk) { try { prefetchProfilePage(pk); profileOf(pk); } catch {} return true; },
    // Publish (merge) kind-0 fields for the current identity — the onboarding
    // wizard sets name + picture through this.
    publishProfile(fields, opts = {}) { return publishProfileFields(fields, opts); },
    // A migrated coinos.io account brings its face with it: fetch the legacy
    // avatar and cover art and fill our kind 0's EMPTY slots — fill, never
    // overwrite, so an existing nostr identity keeps its own look. The light
    // cache is pre-warmed so the wizard's punk-picker skip sees the picture
    // before the publish round-trips.
    async adoptLegacyProfile(username) {
      try {
        const u = await fetch(`https://coinos.io/api/users/${encodeURIComponent(username)}`).then((r) => r.json());
        if (!u) return true;
        const hosted = (v) => `https://coinos.io/api/public/${v}.webp`;
        const picture = u.profile ? hosted(u.profile)
          : typeof u.picture === 'string' && /^https?:\/\//i.test(u.picture) ? u.picture : null;
        const banner = !u.banner ? null
          : /^https?:\/\//i.test(String(u.banner)) ? String(u.banner) : hosted(u.banner);
        if (!picture && !banner) return true;
        const pk = myPubkeys()[0];
        if (pk && picture) {
          const cur = profiles.get(pk);
          if (!(cur && cur.picture)) {
            profiles.set(pk, { ...(cur || {}), picture, t: Date.now() });
            preloadPicture({ picture });
            scheduleRepaint();
          }
        }
        await publishProfileFields({ picture, banner }, { fillOnly: ['picture', 'banner'] });
      } catch {}
      return true;
    },
    // A payment-address rename released the old name: repoint the kind 0's
    // lud16 and nip05 — but only where they pointed at the released address
    // (or were empty). Deliberately different values are not ours to touch.
    addressRenamed(oldAddr, newAddr) {
      const follows = (k) => (base) => !base[k] || base[k] === oldAddr;
      return publishProfileFields({ lud16: newAddr, nip05: newAddr }, {
        onlyWhen: (base) => ['lud16', 'nip05'].some((k) => follows(k)(base) && base[k] !== newAddr),
        fieldWhen: { lud16: follows('lud16'), nip05: follows('nip05') },
      }).catch(() => {});
    },
    profileChip(pk, size) {
      const big = size === 'lg';
      return h('span', {
        class: 'zap-chip' + (big ? ' lg' : ''),
        onClick: (e) => { e.stopPropagation(); openProfile(pk); },
      }, avatar(pk, 'chat-avatar ' + (big ? 'chip-lg' : 'mini'), false),
        h('span', { class: big ? '' : 'small' }, displayName(pk)));
    },
    init() {
      // your own profile is the likeliest first tap — warm it early
      setTimeout(() => {
        try { const me = ctx.shownPubkey && ctx.shownPubkey(); if (me) prefetchProfilePage(me); } catch {}
      }, 2500);
      if (urlInvite && !pendingLink) {
        loadLinkInvite(urlInvite);
        setTimeout(() => { ui.chatOpen = true; ui.msgView = 'home'; render(); }, 0);
      }
      ui.pubProf = null; // a wallet is open now — its chrome owns the profile
      window.addEventListener('resize', onViewportResize);
      window.visualViewport?.addEventListener('resize', onViewportResize);
      allUnsubs.push(() => {
        window.removeEventListener('resize', onViewportResize);
        window.visualViewport?.removeEventListener('resize', onViewportResize);
      });
      startDMs();
      // Communities are built from CACHE ONLY at boot (subscribe:false) — the
      // unread dot reads the last-known messages, but none of the gift-wrap
      // verify/decrypt runs until the user opens Chat (homeView subscribes
      // them). This keeps the home screen (and the balance carousel) off the
      // hook for the ~500ms of secp256k1 a full community backfill costs.
      for (const jm of communities()) { try { ensureRoom(jm, { subscribe: false }); } catch {} }
      syncLists().catch(() => {});
      syncInbox().catch(() => {});
      syncFollows().catch(() => {}); // the Follow button should be right on first paint
      syncMutes().catch(() => {});   // and a muted author shouldn't flash past before the list lands
      registerPush().catch(() => {}); // silent refresh when permission already granted
    },
    stop() {
      for (const u of allUnsubs) { try { u(); } catch {} }
      allUnsubs = [];
      rooms.clear();
      threads.clear();
      pendingDirect.clear();
      seenWraps.clear(); wrapLog = null; // the next account must decrypt wraps this one couldn't
      clearTimeout(drainTimer);
      pendingWraps.clear();
      dmStarted = false;
      listsSynced = false;
      if (zapLiveUnsub) { try { zapLiveUnsub(); } catch {} zapLiveUnsub = null; }
      clearTimeout(zapTimer); zapTimer = null; zapQueue = new Set(); zapRecent = [];
      stopFeedWatch();
      follows = null; followsAt = 0; feed = null; feedAt = 0; relayLists = null;
      mutes = null; mutesAt = 0;
      reacts.clear(); boosts.clear(); seenNoteEv.clear(); myReactEv.clear(); quoted.clear();
      clearTimeout(zapSaveT); zapSaveT = null; zapSeed = null;
      zapTotals.clear(); zapAsked.clear(); zapPending.clear(); // 'mine' is per identity — refetch under the next
    },
  };
}